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 | lgpl-2.1 | b3cd6136fd08022d3a64bf6a9e9d9fef559b52b6 | 0 | levants/lightmare | package org.lightmare.deploy;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptors;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import org.apache.log4j.Logger;
import org.lightmare.cache.ConnectionContainer;
import org.lightmare.cache.ConnectionData;
import org.lightmare.cache.ConnectionSemaphore;
import org.lightmare.cache.DeployData;
import org.lightmare.cache.InjectionData;
import org.lightmare.cache.InterceptorData;
import org.lightmare.cache.MetaContainer;
import org.lightmare.cache.MetaData;
import org.lightmare.config.Configuration;
import org.lightmare.ejb.exceptions.BeanInUseException;
import org.lightmare.jpa.datasource.InitMessages;
import org.lightmare.jpa.datasource.Initializer;
import org.lightmare.libraries.LibraryLoader;
import org.lightmare.rest.providers.RestProvider;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.LogUtils;
import org.lightmare.utils.NamingUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.beans.BeanUtils;
import org.lightmare.utils.fs.FileUtils;
import org.lightmare.utils.fs.WatchUtils;
import org.lightmare.utils.reflect.MetaUtils;
import org.lightmare.utils.rest.RestCheck;
/**
* Class for running in distinct thread to initialize
* {@link javax.sql.DataSource}s load libraries and {@link javax.ejb.Stateless}
* session beans and cache them and clean resources after deployments
*
* @author levan
*
*/
public class BeanLoader {
private static final Logger LOG = Logger.getLogger(BeanLoader.class);
/**
* PrivilegedAction implementation to set
* {@link Executors#privilegedCallableUsingCurrentClassLoader()} passed
* {@link Callable} class
*
* @author levan
*
* @param <T>
*/
private static class ContextLoaderAction<T> implements
PrivilegedAction<Callable<T>> {
private final Callable<T> current;
public ContextLoaderAction(Callable<T> current) {
this.current = current;
}
@Override
public Callable<T> run() {
Callable<T> privileged = Executors.privilegedCallable(current);
return privileged;
}
}
/**
* {@link Runnable} implementation for initializing and deploying
* {@link javax.sql.DataSource}
*
* @author levan
*
*/
private static class ConnectionDeployer implements Callable<Boolean> {
private Properties properties;
private CountDownLatch blocker;
private boolean countedDown;
public ConnectionDeployer(DataSourceParameters parameters) {
this.properties = parameters.properties;
this.blocker = parameters.blocker;
}
private void releaseBlocker() {
if (ObjectUtils.notTrue(countedDown)) {
blocker.countDown();
countedDown = Boolean.TRUE;
}
}
@Override
public Boolean call() throws Exception {
boolean result;
ClassLoader loader = LoaderPoolManager.getCurrent();
try {
Initializer.registerDataSource(properties);
result = Boolean.TRUE;
} catch (IOException ex) {
result = Boolean.FALSE;
LOG.error(InitMessages.INITIALIZING_ERROR, ex);
} finally {
releaseBlocker();
LibraryLoader.loadCurrentLibraries(loader);
}
return result;
}
}
/**
* {@link Runnable} implementation for temporal resources removal
*
* @author levan
*
*/
private static class ResourceCleaner implements Callable<Boolean> {
List<File> tmpFiles;
public ResourceCleaner(List<File> tmpFiles) {
this.tmpFiles = tmpFiles;
}
/**
* Removes temporal resources after deploy {@link Thread} notifies
*
* @throws InterruptedException
*/
private void clearTmpData() throws InterruptedException {
synchronized (tmpFiles) {
tmpFiles.wait();
}
for (File tmpFile : tmpFiles) {
FileUtils.deleteFile(tmpFile);
LOG.info(String.format("Cleaning temporal resource %s done",
tmpFile.getName()));
}
}
@Override
public Boolean call() throws Exception {
boolean result;
ClassLoader loader = LoaderPoolManager.getCurrent();
try {
clearTmpData();
result = Boolean.TRUE;
} catch (InterruptedException ex) {
result = Boolean.FALSE;
LOG.error("Coluld not clean temporary resources", ex);
} finally {
LibraryLoader.loadCurrentLibraries(loader);
}
return result;
}
}
/**
* {@link Callable} implementation for deploying {@link javax.ejb.Stateless}
* session beans and cache {@link MetaData} keyed by bean name
*
* @author levan
*
*/
private static class BeanDeployer implements Callable<String> {
private MetaCreator creator;
private String beanName;
private String className;
private ClassLoader loader;
private List<File> tmpFiles;
private MetaData metaData;
private CountDownLatch blocker;
private boolean countedDown;
private List<Field> unitFields;
private DeployData deployData;
private boolean chekcWatch;
private Configuration configuration;
public BeanDeployer(BeanParameters parameters) {
this.creator = parameters.creator;
this.beanName = parameters.beanName;
this.className = parameters.className;
this.loader = parameters.loader;
this.tmpFiles = parameters.tmpFiles;
this.metaData = parameters.metaData;
this.blocker = parameters.blocker;
this.deployData = parameters.deployData;
this.configuration = parameters.configuration;
}
/**
* Locks {@link ConnectionSemaphore} if needed for connection processing
*
* @param semaphore
* @param unitName
* @param jndiName
* @throws IOException
*/
private void lockSemaphore(ConnectionSemaphore semaphore,
String unitName, String jndiName) throws IOException {
synchronized (semaphore) {
if (ObjectUtils.notTrue(semaphore.isCheck())) {
try {
creator.configureConnection(unitName, beanName, loader,
configuration);
} finally {
semaphore.notifyAll();
}
}
}
}
/**
* Increases {@link CountDownLatch} blocker if it is first time in
* current thread
*/
private void releaseBlocker() {
if (ObjectUtils.notTrue(countedDown)) {
blocker.countDown();
countedDown = Boolean.TRUE;
}
}
/**
* Checks if bean {@link MetaData} with same name already cached if it
* is increases {@link CountDownLatch} for connection and throws
* {@link BeanInUseException} else caches meta data with associated name
*
* @param beanEjbName
* @throws BeanInUseException
*/
private void checkAndSetBean(String beanEjbName)
throws BeanInUseException {
try {
MetaContainer.checkAndAddMetaData(beanEjbName, metaData);
} catch (BeanInUseException ex) {
releaseBlocker();
throw ex;
}
}
private void addUnitField(Field unitField) {
if (unitFields == null) {
unitFields = new ArrayList<Field>();
}
unitFields.add(unitField);
}
/**
* Checks weather connection with passed unit or jndi name already
* exists
*
* @param unitName
* @param jndiName
* @return <code>boolean</code>
*/
private boolean checkOnEmf(String unitName, String jndiName) {
boolean checkForEmf = ConnectionContainer.checkForEmf(unitName);
if (ObjectUtils.available(jndiName)) {
jndiName = NamingUtils.createJpaJndiName(jndiName);
checkForEmf = checkForEmf
&& ConnectionContainer.checkForEmf(jndiName);
}
return checkForEmf;
}
/**
* Creates {@link ConnectionSemaphore} if such does not exists
*
* @param context
* @param field
* @return <code>boolean</code>
* @throws IOException
*/
private void identifyConnections(PersistenceContext context,
Field connectionField) throws IOException {
ConnectionData connection = new ConnectionData();
connection.setConnectionField(connectionField);
String unitName = context.unitName();
String jndiName = context.name();
connection.setUnitName(unitName);
connection.setJndiName(jndiName);
boolean checkForEmf = checkOnEmf(unitName, jndiName);
ConnectionSemaphore semaphore;
if (checkForEmf) {
releaseBlocker();
semaphore = ConnectionContainer.getSemaphore(unitName);
connection.setConnection(semaphore);
} else {
// Sets connection semaphore for this connection
semaphore = ConnectionContainer.cacheSemaphore(unitName,
jndiName);
connection.setConnection(semaphore);
releaseBlocker();
if (ObjectUtils.notNull(semaphore)) {
lockSemaphore(semaphore, unitName, jndiName);
}
}
metaData.addConnection(connection);
}
/**
* Caches {@link EJB} annotated fields
*
* @param beanClass
*/
private void cacheInjectFields(Field field) {
EJB ejb = field.getAnnotation(EJB.class);
Class<?> interfaceClass = ejb.beanInterface();
if (interfaceClass == null || interfaceClass.equals(Object.class)) {
interfaceClass = field.getType();
}
String name = ejb.beanName();
if (name == null || name.isEmpty()) {
name = BeanUtils.nameFromInterface(interfaceClass);
}
String description = ejb.description();
String mappedName = ejb.mappedName();
Class<?>[] interfaceClasses = { interfaceClass };
InjectionData injectionData = new InjectionData();
injectionData.setField(field);
injectionData.setInterfaceClasses(interfaceClasses);
injectionData.setName(name);
injectionData.setDescription(description);
injectionData.setMappedName(mappedName);
metaData.addInject(injectionData);
}
/**
* Finds and caches {@link PersistenceContext}, {@link PersistenceUnit}
* and {@link Resource} annotated {@link Field}s in bean class and
* configures connections and creates {@link ConnectionSemaphore}s if it
* does not exists for {@link PersistenceContext#unitName()} object
*
* @throws IOException
*/
private void retrieveConnections() throws IOException {
Class<?> beanClass = metaData.getBeanClass();
Field[] fields = beanClass.getDeclaredFields();
PersistenceUnit unit;
PersistenceContext context;
Resource resource;
EJB ejbAnnot;
if (ObjectUtils.notAvailable(fields)) {
releaseBlocker();
}
for (Field field : fields) {
context = field.getAnnotation(PersistenceContext.class);
resource = field.getAnnotation(Resource.class);
unit = field.getAnnotation(PersistenceUnit.class);
ejbAnnot = field.getAnnotation(EJB.class);
if (ObjectUtils.notNull(context)) {
identifyConnections(context, field);
} else if (ObjectUtils.notNull(resource)) {
metaData.setTransactionField(field);
} else if (ObjectUtils.notNull(unit)) {
addUnitField(field);
} else if (ObjectUtils.notNull(ejbAnnot)) {
// caches EJB annotated fields
cacheInjectFields(field);
}
}
if (ObjectUtils.available(unitFields)) {
metaData.addUnitFields(unitFields);
}
}
/**
* Creates {@link MetaData} for bean class
*
* @param beanClass
* @throws ClassNotFoundException
*/
private void createMeta(Class<?> beanClass) throws IOException {
metaData.setBeanClass(beanClass);
if (Configuration.isServer()) {
retrieveConnections();
} else {
releaseBlocker();
}
metaData.setLoader(loader);
}
/**
* Checks if bean class is annotated as {@link TransactionAttribute} and
* {@link TransactionManagement} and caches
* {@link TransactionAttribute#value()} and
* {@link TransactionManagement#value()} in {@link MetaData} object
*
* @param beanClass
*/
private void checkOnTransactional(Class<?> beanClass) {
TransactionAttribute transactionAttribute = beanClass
.getAnnotation(TransactionAttribute.class);
TransactionManagement transactionManagement = beanClass
.getAnnotation(TransactionManagement.class);
boolean transactional = Boolean.FALSE;
TransactionAttributeType transactionAttrType;
TransactionManagementType transactionManType;
if (transactionAttribute == null) {
transactional = Boolean.TRUE;
transactionAttrType = TransactionAttributeType.REQUIRED;
transactionManType = TransactionManagementType.CONTAINER;
} else if (transactionManagement == null) {
transactionAttrType = transactionAttribute.value();
transactionManType = TransactionManagementType.CONTAINER;
} else {
transactionAttrType = transactionAttribute.value();
transactionManType = transactionManagement.value();
}
metaData.setTransactional(transactional);
metaData.setTransactionAttrType(transactionAttrType);
metaData.setTransactionManType(transactionManType);
}
/**
* Caches {@link Interceptors} annotation defined data
*
* @param beanClass
* @param interceptorClasses
* @throws IOException
*/
private void cacheInterceptors(Class<?> beanClass,
Class<?>[] interceptorClasses, Method beanMethod)
throws IOException {
int length = interceptorClasses.length;
Class<?> interceptorClass;
List<Method> interceptorMethods;
Method interceptorMethod;
for (int i = 0; i < length; i++) {
interceptorClass = interceptorClasses[i];
interceptorMethods = MetaUtils.getAnnotatedMethods(beanClass,
AroundInvoke.class);
interceptorMethod = CollectionUtils
.getFirst(interceptorMethods);
InterceptorData data = new InterceptorData();
data.setBeanClass(beanClass);
data.setBeanMethod(beanMethod);
data.setInterceptorClass(interceptorClass);
data.setInterceptorMethod(interceptorMethod);
metaData.addInterceptor(data);
}
}
private void cacheInterceptors(Interceptors interceptors,
Class<?> beanClass, Method... beanMethods) throws IOException {
Class<?>[] interceptorClasses = interceptors.value();
if (ObjectUtils.available(interceptorClasses)) {
Method beanMethod = CollectionUtils.getFirst(beanMethods);
cacheInterceptors(beanClass, interceptorClasses, beanMethod);
}
}
/**
* Identifies and caches {@link Interceptors} annotation data
*
* @throws IOException
*/
private void identifyInterceptors(Class<?> beanClass)
throws IOException {
Interceptors interceptors = beanClass
.getAnnotation(Interceptors.class);
if (ObjectUtils.notNull(interceptors)) {
cacheInterceptors(interceptors, beanClass);
}
List<Method> beanMethods = MetaUtils.getAnnotatedMethods(beanClass,
Interceptors.class);
if (ObjectUtils.available(beanMethods)) {
for (Method beanMethod : beanMethods) {
interceptors = beanMethod.getAnnotation(Interceptors.class);
cacheInterceptors(interceptors, beanClass, beanMethod);
}
}
}
/**
* Identifies and caches bean interfaces
*
* @param beanClass
*/
private void indentifyInterfaces(Class<?> beanClass) {
Class<?>[] remoteInterface = null;
Class<?>[] localInterface = null;
Class<?>[] interfaces;
List<Class<?>> interfacesList;
Remote remote = beanClass.getAnnotation(Remote.class);
Local local = beanClass.getAnnotation(Local.class);
interfaces = beanClass.getInterfaces();
if (ObjectUtils.notNull(remote)) {
remoteInterface = remote.value();
}
interfacesList = new ArrayList<Class<?>>();
for (Class<?> interfaceClass : interfaces) {
if (interfaceClass.isAnnotationPresent(Remote.class))
interfacesList.add(interfaceClass);
}
if (ObjectUtils.available(interfacesList)) {
remoteInterface = interfacesList
.toArray(new Class<?>[interfacesList.size()]);
}
if (ObjectUtils.notNull(local)) {
localInterface = local.value();
}
interfacesList = new ArrayList<Class<?>>();
for (Class<?> interfaceClass : interfaces) {
if (interfaceClass.isAnnotationPresent(Local.class))
interfacesList.add(interfaceClass);
}
if (ObjectUtils.available(interfacesList)) {
localInterface = interfacesList
.toArray(new Class<?>[interfacesList.size()]);
}
if (ObjectUtils.notAvailable(localInterface)
&& ObjectUtils.notAvailable(remoteInterface)) {
localInterface = interfaces;
}
metaData.setLocalInterfaces(localInterface);
metaData.setRemoteInterfaces(remoteInterface);
}
/**
* Loads and caches bean {@link Class} by name
*
* @return
* @throws IOException
*/
private String createBeanClass() throws IOException {
try {
Class<?> beanClass = MetaUtils.classForName(className,
Boolean.FALSE, loader);
checkOnTransactional(beanClass);
String beanEjbName = BeanUtils.beanName(beanClass);
checkAndSetBean(beanEjbName);
if (RestCheck.check(beanClass)) {
RestProvider.add(beanClass);
}
createMeta(beanClass);
indentifyInterfaces(beanClass);
identifyInterceptors(beanClass);
metaData.setInProgress(Boolean.FALSE);
return beanEjbName;
} catch (IOException ex) {
releaseBlocker();
throw ex;
}
}
private String deployFile() {
String deployed = beanName;
ClassLoader currentLoader = LoaderPoolManager.getCurrent();
try {
LibraryLoader.loadCurrentLibraries(loader);
deployed = createBeanClass();
chekcWatch = WatchUtils.checkForWatch(deployData);
if (chekcWatch) {
URL url = deployData.getUrl();
url = WatchUtils.clearURL(url);
MetaContainer.addBeanName(url, deployed);
}
LogUtils.info(LOG, "bean %s deployed", beanName);
} catch (IOException ex) {
LogUtils.error(LOG, ex, "Could not deploy bean %s cause %s",
beanName, ex.getMessage());
} finally {
LibraryLoader.loadCurrentLibraries(currentLoader);
}
return deployed;
}
private String deployExtracted() {
String deployed;
synchronized (tmpFiles) {
try {
deployed = deployFile();
} finally {
tmpFiles.notifyAll();
}
}
return deployed;
}
private String deploy() {
synchronized (metaData) {
String deployed;
try {
if (ObjectUtils.notNull(tmpFiles)) {
deployed = deployExtracted();
} else {
deployed = deployFile();
}
} catch (Exception ex) {
LOG.error(ex.getMessage(), ex);
deployed = null;
} finally {
releaseBlocker();
metaData.notifyAll();
}
return deployed;
}
}
@Override
public String call() throws Exception {
String deployed = deploy();
return deployed;
}
}
/**
* Contains parameters for bean deploy classes
*
* @author levan
*
*/
public static class BeanParameters {
public MetaCreator creator;
public String className;
public String beanName;
public ClassLoader loader;
public List<File> tmpFiles;
public CountDownLatch blocker;
public MetaData metaData;
public DeployData deployData;
public boolean server;
public Configuration configuration;
}
/**
* Contains parameters for data source deploy classes
*
* @author levan
*
*/
public static class DataSourceParameters {
public Properties properties;
public Properties poolProperties;
public String poolPath;
public CountDownLatch blocker;
}
/**
* Creates and starts bean deployment process
*
* @param creator
* @param className
* @param loader
* @param tmpFiles
* @param conn
* @return {@link Future}
* @throws IOException
*/
public static Future<String> loadBean(BeanParameters parameters)
throws IOException {
parameters.metaData = new MetaData();
String beanName = BeanUtils.parseName(parameters.className);
parameters.beanName = beanName;
BeanDeployer beanDeployer = new BeanDeployer(parameters);
Future<String> future = LoaderPoolManager.submit(beanDeployer);
return future;
}
/**
* Initialized {@link javax.sql.DataSource}s in parallel mode
*
* @param initializer
* @param properties
* @param sdLatch
*/
public static void initializeDatasource(DataSourceParameters parameters)
throws IOException {
final ConnectionDeployer connectionDeployer = new ConnectionDeployer(
parameters);
Callable<Boolean> privileged = AccessController
.doPrivileged(new ContextLoaderAction<Boolean>(
connectionDeployer));
LoaderPoolManager.submit(privileged);
}
/**
* Creates and starts temporal resources removal process
*
* @param tmpFiles
*/
public static void removeResources(List<File> tmpFiles) {
ResourceCleaner cleaner = new ResourceCleaner(tmpFiles);
Callable<Boolean> privileged = AccessController
.doPrivileged(new ContextLoaderAction<Boolean>(cleaner));
LoaderPoolManager.submit(privileged);
}
}
| src/main/java/org/lightmare/deploy/BeanLoader.java | package org.lightmare.deploy;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptors;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import org.apache.log4j.Logger;
import org.lightmare.cache.ConnectionContainer;
import org.lightmare.cache.ConnectionData;
import org.lightmare.cache.ConnectionSemaphore;
import org.lightmare.cache.DeployData;
import org.lightmare.cache.InjectionData;
import org.lightmare.cache.InterceptorData;
import org.lightmare.cache.MetaContainer;
import org.lightmare.cache.MetaData;
import org.lightmare.config.Configuration;
import org.lightmare.ejb.exceptions.BeanInUseException;
import org.lightmare.jpa.datasource.InitMessages;
import org.lightmare.jpa.datasource.Initializer;
import org.lightmare.libraries.LibraryLoader;
import org.lightmare.rest.providers.RestProvider;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.LogUtils;
import org.lightmare.utils.NamingUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.beans.BeanUtils;
import org.lightmare.utils.fs.FileUtils;
import org.lightmare.utils.fs.WatchUtils;
import org.lightmare.utils.reflect.MetaUtils;
import org.lightmare.utils.rest.RestCheck;
/**
* Class for running in distinct thread to initialize
* {@link javax.sql.DataSource}s load libraries and {@link javax.ejb.Stateless}
* session beans and cache them and clean resources after deployments
*
* @author levan
*
*/
public class BeanLoader {
private static final Logger LOG = Logger.getLogger(BeanLoader.class);
/**
* PrivilegedAction implementation to set
* {@link Executors#privilegedCallableUsingCurrentClassLoader()} passed
* {@link Callable} class
*
* @author levan
*
* @param <T>
*/
private static class ContextLoaderAction<T> implements
PrivilegedAction<Callable<T>> {
private final Callable<T> current;
public ContextLoaderAction(Callable<T> current) {
this.current = current;
}
@Override
public Callable<T> run() {
Callable<T> privileged = Executors.privilegedCallable(current);
return privileged;
}
}
/**
* {@link Runnable} implementation for initializing and deploying
* {@link javax.sql.DataSource}
*
* @author levan
*
*/
private static class ConnectionDeployer implements Callable<Boolean> {
private Properties properties;
private CountDownLatch blocker;
private boolean countedDown;
public ConnectionDeployer(DataSourceParameters parameters) {
this.properties = parameters.properties;
this.blocker = parameters.blocker;
}
private void releaseBlocker() {
if (ObjectUtils.notTrue(countedDown)) {
blocker.countDown();
countedDown = Boolean.TRUE;
}
}
@Override
public Boolean call() throws Exception {
boolean result;
ClassLoader loader = LoaderPoolManager.getCurrent();
try {
Initializer.registerDataSource(properties);
result = Boolean.TRUE;
} catch (IOException ex) {
result = Boolean.FALSE;
LOG.error(InitMessages.INITIALIZING_ERROR, ex);
} finally {
releaseBlocker();
LibraryLoader.loadCurrentLibraries(loader);
}
return result;
}
}
/**
* {@link Runnable} implementation for temporal resources removal
*
* @author levan
*
*/
private static class ResourceCleaner implements Callable<Boolean> {
List<File> tmpFiles;
public ResourceCleaner(List<File> tmpFiles) {
this.tmpFiles = tmpFiles;
}
/**
* Removes temporal resources after deploy {@link Thread} notifies
*
* @throws InterruptedException
*/
private void clearTmpData() throws InterruptedException {
synchronized (tmpFiles) {
tmpFiles.wait();
}
for (File tmpFile : tmpFiles) {
FileUtils.deleteFile(tmpFile);
LOG.info(String.format("Cleaning temporal resource %s done",
tmpFile.getName()));
}
}
@Override
public Boolean call() throws Exception {
boolean result;
ClassLoader loader = LoaderPoolManager.getCurrent();
try {
clearTmpData();
result = Boolean.TRUE;
} catch (InterruptedException ex) {
result = Boolean.FALSE;
LOG.error("Coluld not clean temporary resources", ex);
} finally {
LibraryLoader.loadCurrentLibraries(loader);
}
return result;
}
}
/**
* {@link Callable} implementation for deploying {@link javax.ejb.Stateless}
* session beans and cache {@link MetaData} keyed by bean name
*
* @author levan
*
*/
private static class BeanDeployer implements Callable<String> {
private MetaCreator creator;
private String beanName;
private String className;
private ClassLoader loader;
private List<File> tmpFiles;
private MetaData metaData;
private CountDownLatch blocker;
private boolean countedDown;
private List<Field> unitFields;
private DeployData deployData;
private boolean chekcWatch;
private Configuration configuration;
public BeanDeployer(BeanParameters parameters) {
this.creator = parameters.creator;
this.beanName = parameters.beanName;
this.className = parameters.className;
this.loader = parameters.loader;
this.tmpFiles = parameters.tmpFiles;
this.metaData = parameters.metaData;
this.blocker = parameters.blocker;
this.deployData = parameters.deployData;
this.configuration = parameters.configuration;
}
/**
* Locks {@link ConnectionSemaphore} if needed for connection processing
*
* @param semaphore
* @param unitName
* @param jndiName
* @throws IOException
*/
private void lockSemaphore(ConnectionSemaphore semaphore,
String unitName, String jndiName) throws IOException {
synchronized (semaphore) {
if (ObjectUtils.notTrue(semaphore.isCheck())) {
try {
creator.configureConnection(unitName, beanName, loader,
configuration);
} finally {
semaphore.notifyAll();
}
}
}
}
/**
* Increases {@link CountDownLatch} blocker if it is first time in
* current thread
*/
private void releaseBlocker() {
if (ObjectUtils.notTrue(countedDown)) {
blocker.countDown();
countedDown = Boolean.TRUE;
}
}
/**
* Checks if bean {@link MetaData} with same name already cached if it
* is increases {@link CountDownLatch} for connection and throws
* {@link BeanInUseException} else caches meta data with associated name
*
* @param beanEjbName
* @throws BeanInUseException
*/
private void checkAndSetBean(String beanEjbName)
throws BeanInUseException {
try {
MetaContainer.checkAndAddMetaData(beanEjbName, metaData);
} catch (BeanInUseException ex) {
releaseBlocker();
throw ex;
}
}
private void addUnitField(Field unitField) {
if (unitFields == null) {
unitFields = new ArrayList<Field>();
}
unitFields.add(unitField);
}
/**
* Checks weather connection with passed unit or jndi name already
* exists
*
* @param unitName
* @param jndiName
* @return <code>boolean</code>
*/
private boolean checkOnEmf(String unitName, String jndiName) {
boolean checkForEmf = ConnectionContainer.checkForEmf(unitName);
if (ObjectUtils.available(jndiName)) {
jndiName = NamingUtils.createJpaJndiName(jndiName);
checkForEmf = checkForEmf
&& ConnectionContainer.checkForEmf(jndiName);
}
return checkForEmf;
}
/**
* Creates {@link ConnectionSemaphore} if such does not exists
*
* @param context
* @param field
* @return <code>boolean</code>
* @throws IOException
*/
private void identifyConnections(PersistenceContext context,
Field connectionField) throws IOException {
ConnectionData connection = new ConnectionData();
connection.setConnectionField(connectionField);
String unitName = context.unitName();
String jndiName = context.name();
connection.setUnitName(unitName);
connection.setJndiName(jndiName);
boolean checkForEmf = checkOnEmf(unitName, jndiName);
ConnectionSemaphore semaphore;
if (checkForEmf) {
releaseBlocker();
semaphore = ConnectionContainer.getSemaphore(unitName);
connection.setConnection(semaphore);
} else {
// Sets connection semaphore for this connection
semaphore = ConnectionContainer.cacheSemaphore(unitName,
jndiName);
connection.setConnection(semaphore);
releaseBlocker();
if (ObjectUtils.notNull(semaphore)) {
lockSemaphore(semaphore, unitName, jndiName);
}
}
metaData.addConnection(connection);
}
/**
* Caches {@link EJB} annotated fields
*
* @param beanClass
*/
private void cacheInjectFields(Field field) {
EJB ejb = field.getAnnotation(EJB.class);
Class<?> interfaceClass = ejb.beanInterface();
if (interfaceClass == null || interfaceClass.equals(Object.class)) {
interfaceClass = field.getType();
}
String name = ejb.beanName();
if (name == null || name.isEmpty()) {
name = BeanUtils.nameFromInterface(interfaceClass);
}
String description = ejb.description();
String mappedName = ejb.mappedName();
Class<?>[] interfaceClasses = { interfaceClass };
InjectionData injectionData = new InjectionData();
injectionData.setField(field);
injectionData.setInterfaceClasses(interfaceClasses);
injectionData.setName(name);
injectionData.setDescription(description);
injectionData.setMappedName(mappedName);
metaData.addInject(injectionData);
}
/**
* Finds and caches {@link PersistenceContext}, {@link PersistenceUnit}
* and {@link Resource} annotated {@link Field}s in bean class and
* configures connections and creates {@link ConnectionSemaphore}s if it
* does not exists for {@link PersistenceContext#unitName()} object
*
* @throws IOException
*/
private void retrieveConnections() throws IOException {
Class<?> beanClass = metaData.getBeanClass();
Field[] fields = beanClass.getDeclaredFields();
PersistenceUnit unit;
PersistenceContext context;
Resource resource;
EJB ejbAnnot;
if (ObjectUtils.notAvailable(fields)) {
releaseBlocker();
}
for (Field field : fields) {
context = field.getAnnotation(PersistenceContext.class);
resource = field.getAnnotation(Resource.class);
unit = field.getAnnotation(PersistenceUnit.class);
ejbAnnot = field.getAnnotation(EJB.class);
if (ObjectUtils.notNull(context)) {
identifyConnections(context, field);
} else if (ObjectUtils.notNull(resource)) {
metaData.setTransactionField(field);
} else if (ObjectUtils.notNull(unit)) {
addUnitField(field);
} else if (ObjectUtils.notNull(ejbAnnot)) {
// caches EJB annotated fields
cacheInjectFields(field);
}
}
if (ObjectUtils.available(unitFields)) {
metaData.addUnitFields(unitFields);
}
}
/**
* Creates {@link MetaData} for bean class
*
* @param beanClass
* @throws ClassNotFoundException
*/
private void createMeta(Class<?> beanClass) throws IOException {
metaData.setBeanClass(beanClass);
if (Configuration.isServer()) {
retrieveConnections();
} else {
releaseBlocker();
}
metaData.setLoader(loader);
}
/**
* Checks if bean class is annotated as {@link TransactionAttribute} and
* {@link TransactionManagement} and caches
* {@link TransactionAttribute#value()} and
* {@link TransactionManagement#value()} in {@link MetaData} object
*
* @param beanClass
*/
private void checkOnTransactional(Class<?> beanClass) {
TransactionAttribute transactionAttribute = beanClass
.getAnnotation(TransactionAttribute.class);
TransactionManagement transactionManagement = beanClass
.getAnnotation(TransactionManagement.class);
boolean transactional = Boolean.FALSE;
TransactionAttributeType transactionAttrType;
TransactionManagementType transactionManType;
if (transactionAttribute == null) {
transactional = Boolean.TRUE;
transactionAttrType = TransactionAttributeType.REQUIRED;
transactionManType = TransactionManagementType.CONTAINER;
} else if (transactionManagement == null) {
transactionAttrType = transactionAttribute.value();
transactionManType = TransactionManagementType.CONTAINER;
} else {
transactionAttrType = transactionAttribute.value();
transactionManType = transactionManagement.value();
}
metaData.setTransactional(transactional);
metaData.setTransactionAttrType(transactionAttrType);
metaData.setTransactionManType(transactionManType);
}
/**
* Caches {@link Interceptors} annotation defined data
*
* @param beanClass
* @param interceptorClasses
* @throws IOException
*/
private void cacheInterceptors(Class<?> beanClass,
Class<?>[] interceptorClasses, Method beanMethod)
throws IOException {
int length = interceptorClasses.length;
Class<?> interceptorClass;
List<Method> interceptorMethods;
Method interceptorMethod;
for (int i = 0; i < length; i++) {
interceptorClass = interceptorClasses[i];
interceptorMethods = MetaUtils.getAnnotatedMethods(beanClass,
AroundInvoke.class);
interceptorMethod = CollectionUtils
.getFirst(interceptorMethods);
InterceptorData data = new InterceptorData();
data.setBeanClass(beanClass);
data.setBeanMethod(beanMethod);
data.setInterceptorClass(interceptorClass);
data.setInterceptorMethod(interceptorMethod);
metaData.addInterceptor(data);
}
}
private void cacheInterceptors(Interceptors interceptors,
Class<?> beanClass, Method... beanMethods) throws IOException {
Class<?>[] interceptorClasses = interceptors.value();
if (ObjectUtils.available(interceptorClasses)) {
Method beanMethod = CollectionUtils.getFirst(beanMethods);
cacheInterceptors(beanClass, interceptorClasses, beanMethod);
}
}
/**
* Identifies and caches {@link Interceptors} annotation data
*
* @throws IOException
*/
private void identifyInterceptors(Class<?> beanClass)
throws IOException {
Interceptors interceptors = beanClass
.getAnnotation(Interceptors.class);
if (ObjectUtils.notNull(interceptors)) {
cacheInterceptors(interceptors, beanClass);
}
List<Method> beanMethods = MetaUtils.getAnnotatedMethods(beanClass,
Interceptors.class);
if (ObjectUtils.available(beanMethods)) {
for (Method beanMethod : beanMethods) {
interceptors = beanMethod.getAnnotation(Interceptors.class);
cacheInterceptors(interceptors, beanClass, beanMethod);
}
}
}
/**
* Identifies and caches bean interfaces
*
* @param beanClass
*/
private void indentifyInterfaces(Class<?> beanClass) {
Class<?>[] remoteInterface = null;
Class<?>[] localInterface = null;
Class<?>[] interfaces;
List<Class<?>> interfacesList;
Remote remote = beanClass.getAnnotation(Remote.class);
Local local = beanClass.getAnnotation(Local.class);
interfaces = beanClass.getInterfaces();
if (ObjectUtils.notNull(remote)) {
remoteInterface = remote.value();
}
interfacesList = new ArrayList<Class<?>>();
for (Class<?> interfaceClass : interfaces) {
if (interfaceClass.isAnnotationPresent(Remote.class))
interfacesList.add(interfaceClass);
}
if (ObjectUtils.available(interfacesList)) {
remoteInterface = interfacesList
.toArray(new Class<?>[interfacesList.size()]);
}
if (ObjectUtils.notNull(local)) {
localInterface = local.value();
}
interfacesList = new ArrayList<Class<?>>();
for (Class<?> interfaceClass : interfaces) {
if (interfaceClass.isAnnotationPresent(Local.class))
interfacesList.add(interfaceClass);
}
if (ObjectUtils.available(interfacesList)) {
localInterface = interfacesList
.toArray(new Class<?>[interfacesList.size()]);
}
if (ObjectUtils.notAvailable(localInterface)
&& ObjectUtils.notAvailable(remoteInterface)) {
localInterface = interfaces;
}
metaData.setLocalInterfaces(localInterface);
metaData.setRemoteInterfaces(remoteInterface);
}
/**
* Loads and caches bean {@link Class} by name
*
* @return
* @throws IOException
*/
private String createBeanClass() throws IOException {
try {
Class<?> beanClass = MetaUtils.classForName(className,
Boolean.FALSE, loader);
checkOnTransactional(beanClass);
String beanEjbName = BeanUtils.beanName(beanClass);
checkAndSetBean(beanEjbName);
if (RestCheck.check(beanClass)) {
RestProvider.add(beanClass);
}
createMeta(beanClass);
indentifyInterfaces(beanClass);
identifyInterceptors(beanClass);
metaData.setInProgress(Boolean.FALSE);
return beanEjbName;
} catch (IOException ex) {
releaseBlocker();
throw ex;
}
}
private String deployFile() {
String deployed = beanName;
ClassLoader currentLoader = LoaderPoolManager.getCurrent();
try {
LibraryLoader.loadCurrentLibraries(loader);
deployed = createBeanClass();
chekcWatch = WatchUtils.checkForWatch(deployData);
if (chekcWatch) {
URL url = deployData.getUrl();
url = WatchUtils.clearURL(url);
MetaContainer.addBeanName(url, deployed);
}
LogUtils.info(LOG, "bean %s deployed", beanName);
} catch (IOException ex) {
LOG.error(String.format("Could not deploy bean %s cause %s",
beanName, ex.getMessage()), ex);
} finally {
LibraryLoader.loadCurrentLibraries(currentLoader);
}
return deployed;
}
private String deployExtracted() {
String deployed;
synchronized (tmpFiles) {
try {
deployed = deployFile();
} finally {
tmpFiles.notifyAll();
}
}
return deployed;
}
private String deploy() {
synchronized (metaData) {
String deployed;
try {
if (ObjectUtils.notNull(tmpFiles)) {
deployed = deployExtracted();
} else {
deployed = deployFile();
}
} catch (Exception ex) {
LOG.error(ex.getMessage(), ex);
deployed = null;
} finally {
releaseBlocker();
metaData.notifyAll();
}
return deployed;
}
}
@Override
public String call() throws Exception {
String deployed = deploy();
return deployed;
}
}
/**
* Contains parameters for bean deploy classes
*
* @author levan
*
*/
public static class BeanParameters {
public MetaCreator creator;
public String className;
public String beanName;
public ClassLoader loader;
public List<File> tmpFiles;
public CountDownLatch blocker;
public MetaData metaData;
public DeployData deployData;
public boolean server;
public Configuration configuration;
}
/**
* Contains parameters for data source deploy classes
*
* @author levan
*
*/
public static class DataSourceParameters {
public Properties properties;
public Properties poolProperties;
public String poolPath;
public CountDownLatch blocker;
}
/**
* Creates and starts bean deployment process
*
* @param creator
* @param className
* @param loader
* @param tmpFiles
* @param conn
* @return {@link Future}
* @throws IOException
*/
public static Future<String> loadBean(BeanParameters parameters)
throws IOException {
parameters.metaData = new MetaData();
String beanName = BeanUtils.parseName(parameters.className);
parameters.beanName = beanName;
BeanDeployer beanDeployer = new BeanDeployer(parameters);
Future<String> future = LoaderPoolManager.submit(beanDeployer);
return future;
}
/**
* Initialized {@link javax.sql.DataSource}s in parallel mode
*
* @param initializer
* @param properties
* @param sdLatch
*/
public static void initializeDatasource(DataSourceParameters parameters)
throws IOException {
final ConnectionDeployer connectionDeployer = new ConnectionDeployer(
parameters);
Callable<Boolean> privileged = AccessController
.doPrivileged(new ContextLoaderAction<Boolean>(
connectionDeployer));
LoaderPoolManager.submit(privileged);
}
/**
* Creates and starts temporal resources removal process
*
* @param tmpFiles
*/
public static void removeResources(List<File> tmpFiles) {
ResourceCleaner cleaner = new ResourceCleaner(tmpFiles);
Callable<Boolean> privileged = AccessController
.doPrivileged(new ContextLoaderAction<Boolean>(cleaner));
LoaderPoolManager.submit(privileged);
}
}
| improved BeanLoader class | src/main/java/org/lightmare/deploy/BeanLoader.java | improved BeanLoader class |
|
Java | lgpl-2.1 | 49a799e9832f083e9a1d3023a90ac4b94224bc2f | 0 | kimrutherford/intermine,kimrutherford/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,tomck/intermine,kimrutherford/intermine,elsiklab/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,tomck/intermine,kimrutherford/intermine,JoeCarlson/intermine,joshkh/intermine,JoeCarlson/intermine,joshkh/intermine,justincc/intermine,joshkh/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,tomck/intermine,JoeCarlson/intermine,zebrafishmine/intermine,joshkh/intermine,tomck/intermine,drhee/toxoMine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,zebrafishmine/intermine,elsiklab/intermine,joshkh/intermine,justincc/intermine,joshkh/intermine,justincc/intermine,joshkh/intermine,tomck/intermine,elsiklab/intermine,zebrafishmine/intermine,drhee/toxoMine,JoeCarlson/intermine,drhee/toxoMine,elsiklab/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,joshkh/intermine,drhee/toxoMine,JoeCarlson/intermine,kimrutherford/intermine,kimrutherford/intermine,zebrafishmine/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,drhee/toxoMine,zebrafishmine/intermine,elsiklab/intermine,tomck/intermine,drhee/toxoMine,kimrutherford/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,justincc/intermine,drhee/toxoMine,zebrafishmine/intermine,zebrafishmine/intermine,JoeCarlson/intermine,kimrutherford/intermine,elsiklab/intermine,tomck/intermine,justincc/intermine,elsiklab/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine | package org.intermine.web.logic.profile;
/*
* Copyright (C) 2002-2009 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.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.ObjectStoreWriter;
import org.intermine.web.logic.Constants;
import org.intermine.web.logic.bag.InterMineBag;
import org.intermine.web.logic.query.SavedQuery;
import org.intermine.web.struts.InterMineAction;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
/**
* @author Xavier Watkins
*
*/
public abstract class LoginHandler extends InterMineAction
{
/**
* Abstract class containing the methods for login in and copying current
* history, bags,... into profile
*
* @param servletContext
* The servlet context
* @param request
* The HttpServletRequest
* @param response
* The HttpServletResponse
* @param session
* The session
* @param pm
* The profile manager
* @param username
* The username
* @param password
* The password
* @return the map containing the renamed bags the user created before they were logged in
*/
public Map doLogin(ServletContext servletContext, HttpServletRequest request,
HttpServletResponse response, HttpSession session, ProfileManager pm, String username,
String password) {
// Merge current history into loaded profile
Profile currentProfile = (Profile) session.getAttribute(Constants.PROFILE);
ObjectStoreWriter uosw = ((ProfileManager) servletContext.getAttribute(
Constants.PROFILE_MANAGER)).getProfileObjectStoreWriter();
Map mergeQueries = Collections.EMPTY_MAP;
Map mergeBags = Collections.EMPTY_MAP;
if (currentProfile != null && StringUtils.isEmpty(currentProfile.getUsername())) {
mergeQueries = new HashMap(currentProfile.getHistory());
mergeBags = new HashMap(currentProfile.getSavedBags());
}
Profile profile = setUpProfile(session, pm, username, password);
// Merge in anonymous query history
for (Iterator iter = mergeQueries.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
SavedQuery query = (SavedQuery) entry.getValue();
profile.saveHistory(query);
}
// Merge anonymous bags
Map renamedBags = new HashMap();
for (Iterator iter = mergeBags.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
InterMineBag bag = (InterMineBag) entry.getValue();
// Make sure the userId gets set to be the profile one
try {
bag.setProfileId(profile.getUserId(), uosw);
String name = makeUniqueQueryName((String) entry.getKey(), profile.getSavedBags()
.keySet());
if (!((String) entry.getKey()).equals(name)) {
renamedBags.put(entry.getKey(), name);
}
bag.setName(name, uosw);
profile.saveBag(name, bag);
} catch (ObjectStoreException iex) {
throw new RuntimeException(iex.getMessage());
}
}
return renamedBags;
}
/**
* Retrieves profile (creates or gets from ProfileManager) and saves it to session.
*
* @param session http session
* @param pm profile manager
* @param username user name
* @param password password
* @return profile
*/
public static Profile setUpProfile(HttpSession session, ProfileManager pm,
String username, String password) {
Profile profile;
if (pm.hasProfile(username)) {
profile = pm.getProfile(username, password);
} else {
profile = new Profile(pm, username, null, password, new HashMap(), new HashMap(),
new HashMap());
pm.saveProfile(profile);
}
session.setAttribute(Constants.PROFILE, profile);
if (profile.getUsername().equals(pm.getSuperuser())) {
session.setAttribute(Constants.IS_SUPERUSER, Boolean.TRUE);
}
return profile;
}
private String makeUniqueQueryName(String name, Set names) {
String newName = name;
int i = 1;
while (names.contains(newName)) {
newName = name + "_" + i;
i++;
}
return name;
}
}
| intermine/web/main/src/org/intermine/web/logic/profile/LoginHandler.java | package org.intermine.web.logic.profile;
/*
* Copyright (C) 2002-2009 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.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.ObjectStoreWriter;
import org.intermine.web.logic.Constants;
import org.intermine.web.logic.bag.InterMineBag;
import org.intermine.web.logic.query.SavedQuery;
import org.intermine.web.struts.InterMineAction;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
/**
* @author Xavier Watkins
*
*/
public abstract class LoginHandler extends InterMineAction
{
/**
* Abstract class containing the methods for login in and copying current
* history, bags,... into profile
*
* @param servletContext
* The servlet context
* @param request
* The HttpServletRequest
* @param response
* The HttpServletResponse
* @param session
* The session
* @param pm
* The profile manager
* @param username
* The username
* @param password
* The password
* @return the map containing the renamed bags the user created before they were logged in
*/
public Map doLogin(ServletContext servletContext, HttpServletRequest request,
HttpServletResponse response, HttpSession session, ProfileManager pm, String username,
String password) {
// Merge current history into loaded profile
Profile currentProfile = (Profile) session.getAttribute(Constants.PROFILE);
ObjectStoreWriter uosw = ((ProfileManager) servletContext.getAttribute(
Constants.PROFILE_MANAGER)).getProfileObjectStoreWriter();
Map mergeQueries = Collections.EMPTY_MAP;
Map mergeBags = Collections.EMPTY_MAP;
if (currentProfile != null && StringUtils.isEmpty(currentProfile.getUsername())) {
mergeQueries = new HashMap(currentProfile.getHistory());
mergeBags = new HashMap(currentProfile.getSavedBags());
}
Profile profile = setUpProfile(session, pm, username, password);
// Merge in anonymous query history
for (Iterator iter = mergeQueries.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
SavedQuery query = (SavedQuery) entry.getValue();
String name = makeUniqueQueryName((String) entry.getKey(), profile.getHistory()
.keySet());
profile.saveHistory(query);
}
// Merge anonymous bags
Map renamedBags = new HashMap();
for (Iterator iter = mergeBags.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
InterMineBag bag = (InterMineBag) entry.getValue();
// Make sure the userId gets set to be the profile one
try {
bag.setProfileId(profile.getUserId(), uosw);
String name = makeUniqueQueryName((String) entry.getKey(), profile.getSavedBags()
.keySet());
if (!((String) entry.getKey()).equals(name)) {
renamedBags.put((String) entry.getKey(), name);
}
bag.setName(name, uosw);
profile.saveBag(name, bag);
} catch (ObjectStoreException iex) {
throw new RuntimeException(iex.getMessage());
}
}
return renamedBags;
}
/**
* Retrieves profile (creates or gets from ProfileManager) and saves it to session.
*
* @param session http session
* @param pm profile manager
* @param username user name
* @param password password
* @return profile
*/
public static Profile setUpProfile(HttpSession session, ProfileManager pm,
String username, String password) {
Profile profile;
if (pm.hasProfile(username)) {
profile = pm.getProfile(username, password);
} else {
profile = new Profile(pm, username, null, password, new HashMap(), new HashMap(),
new HashMap());
pm.saveProfile(profile);
}
session.setAttribute(Constants.PROFILE, profile);
if (profile.getUsername().equals(pm.getSuperuser())) {
session.setAttribute(Constants.IS_SUPERUSER, Boolean.TRUE);
}
return profile;
}
private String makeUniqueQueryName(String name, Set names) {
String original = name;
int i = 1;
while (names.contains(name)) {
name = original + "_" + i;
i++;
}
return name;
}
}
| checkstyle
| intermine/web/main/src/org/intermine/web/logic/profile/LoginHandler.java | checkstyle |
|
Java | lgpl-2.1 | 04a71d6a2984c3e47a20c7d3a25fc60ad9c666b2 | 0 | JordanReiter/railo,modius/railo,getrailo/railo,JordanReiter/railo,getrailo/railo,getrailo/railo,modius/railo | package railo.runtime.type;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import railo.commons.lang.StringList;
import railo.commons.lang.StringUtil;
import railo.runtime.exp.ExpressionException;
import railo.runtime.exp.PageException;
import railo.runtime.op.Caster;
import railo.runtime.type.Collection.Key;
import railo.runtime.type.comparator.NumberComparator;
import railo.runtime.type.comparator.TextComparator;
import railo.runtime.type.util.ArrayUtil;
/**
* List is not a type, only some static method to manipulate String lists
*/
public final class List {
/**
* casts a list to Array object, the list can be have quoted (",') arguments and delimter in this arguments are ignored. quotes are not removed
* example:
* listWithQuotesToArray("aab,a'a,b',a\"a,b\"",",","\"'") will be translated to ["aab","a'a,b'","a\"a,b\""]
*
*
*
* @param list list to cast
* @param delimeter delimter of the list
* @param quotes quotes of the list
* @return Array Object
*/
public static Array listWithQuotesToArray(String list, String delimeter,String quotes) {
if(list.length()==0) return new ArrayImpl();
int len=list.length();
int last=0;
char[] del=delimeter.toCharArray();
char[] quo=quotes.toCharArray();
char c;
char inside=0;
ArrayImpl array=new ArrayImpl();
try{
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<quo.length;y++){
if(c==quo[y]) {
if(c==inside)inside=0;
else if(inside==0)inside=c;
continue;
}
}
for(int y=0;y<del.length;y++) {
if(inside==0 && c==del[y]) {
array._append(list.substring(last,i));
last=i+1;
}
}
}
if(last<=len)array.append(list.substring(last));
}
catch(ExpressionException e){}
return array;
}
/**
* casts a list to Array object
* @param list list to cast
* @param delimeter delimter of the list
* @return Array Object
*/
public static Array listToArray(String list, String delimeter) {
if(delimeter.length()==1)return listToArray(list, delimeter.charAt(0));
if(list.length()==0) return new ArrayImpl();
int len=list.length();
int last=0;
char[] del=delimeter.toCharArray();
char c;
ArrayImpl array=new ArrayImpl();
try{
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
array.appendEL(list.substring(last,i));
last=i+1;
}
}
}
if(last<=len)array.append(list.substring(last));
}
catch(ExpressionException e){}
return array;
}
public static Array listToArray(String list, String delimeter, boolean multiCharDelim) {
if(!multiCharDelim) return listToArray(list, delimeter);
if(delimeter.length()==1)return listToArray(list, delimeter.charAt(0));
int len=list.length();
if(len==0) return new ArrayImpl();
Array array=new ArrayImpl();
int from=0;
int index;
int dl=delimeter.length();
while((index=list.indexOf(delimeter,from))!=-1){
array.appendEL(list.substring(from,index));
from=index+dl;
}
array.appendEL(list.substring(from,len));
return array;
}
/**
* casts a list to Array object
* @param list list to cast
* @param delimeter delimter of the list
* @return Array Object
*/
public static Array listToArray(String list, char delimeter) {
if(list.length()==0) return new ArrayImpl();
int len=list.length();
int last=0;
Array array=new ArrayImpl();
try{
for(int i=0;i<len;i++) {
if(list.charAt(i)==delimeter) {
array.append(list.substring(last,i));
last=i+1;
}
}
if(last<=len)array.append(list.substring(last));
}
catch(PageException e){}
return array;
}
/**
* casts a list to Array object remove Empty Elements
* @param list list to cast
* @param delimeter delimter of the list
* @return Array Object
*/
public static Array listToArrayRemoveEmpty(String list, String delimeter, boolean multiCharDelim) {
if(!multiCharDelim) return listToArrayRemoveEmpty(list, delimeter);
if(delimeter.length()==1)return listToArrayRemoveEmpty(list, delimeter.charAt(0));
int len=list.length();
if(len==0) return new ArrayImpl();
Array array=new ArrayImpl();
int from=0;
int index;
int dl=delimeter.length();
while((index=list.indexOf(delimeter,from))!=-1){
if(from<index)array.appendEL(list.substring(from,index));
from=index+dl;
}
if(from<len)array.appendEL(list.substring(from,len));
return array;
}
public static Array listToArrayRemoveEmpty(String list, String delimeter) {
if(delimeter.length()==1)return listToArrayRemoveEmpty(list, delimeter.charAt(0));
int len=list.length();
ArrayImpl array=new ArrayImpl();
if(len==0) return array;
int last=0;
char[] del = delimeter.toCharArray();
char c;
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
if(last<i)array._append(list.substring(last,i));
last=i+1;
}
}
}
if(last<len)array._append(list.substring(last));
return array;
}
/**
* casts a list to Array object remove Empty Elements
* @param list list to cast
* @param delimeter delimter of the list
* @return Array Object
*/
public static Array listToArrayRemoveEmpty(String list, char delimeter) {
int len=list.length();
ArrayImpl array=new ArrayImpl();
if(len==0) return array;
int last=0;
for(int i=0;i<len;i++) {
if(list.charAt(i)==delimeter) {
if(last<i)array._append(list.substring(last,i));
last=i+1;
}
}
if(last<len)array._append(list.substring(last));
return array;
}
/**
* casts a list to Array object remove Empty Elements
* @param list list to cast
* @param delimeter delimter of the list
* @return Array Object
*/
public static String rest(String list, String delimeter, boolean ignoreEmpty) {
//if(delimeter.length()==1)return rest(list, delimeter.charAt(0));
int len=list.length();
if(len==0) return "";
//int last=-1;
char[] del = delimeter.toCharArray();
char c;
if(ignoreEmpty)list=ltrim(list,del);
len=list.length();
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
return ignoreEmpty?ltrim(list.substring(i+1),del):list.substring(i+1);
}
}
}
return "";
}
private static String ltrim(String list,char[] del) {
int len=list.length();
char c;
// remove at start
outer:while(len>0) {
c=list.charAt(0);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
list=list.substring(1);
len=list.length();
continue outer;
}
}
break;
}
return list;
}
/**
* casts a list to Array object remove Empty Elements
* @param list list to cast
* @param delimeter delimter of the list
* @return Array Object
*/
public static StringList listToStringListRemoveEmpty(String list, char delimeter) {
int len=list.length();
StringList rtn=new StringList();
if(len==0) return rtn.reset();
int last=0;
for(int i=0;i<len;i++) {
if(list.charAt(i)==delimeter) {
if(last<i)rtn.add(list.substring(last,i));
last=i+1;
}
}
if(last<len)rtn.add(list.substring(last));
return rtn.reset();
}
/**
* casts a list to Array object, remove all empty items at start and end of the list
* @param list list to cast
* @param delimeter delimter of the list
* @return Array Object
*/
public static Array listToArrayTrim(String list, String delimeter) {
if(delimeter.length()==1)return listToArrayTrim(list, delimeter.charAt(0));
if(list.length()==0) return new ArrayImpl();
char[] del = delimeter.toCharArray();
char c;
// remove at start
outer:while(list.length()>0) {
c=list.charAt(0);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
list=list.substring(1);
continue outer;
}
}
break;
}
int len;
outer:while(list.length()>0) {
c=list.charAt(list.length()-1);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
len=list.length();
list=list.substring(0,len-1<0?0:len-1);
continue outer;
}
}
break;
}
return listToArray(list, delimeter);
}
/**
* casts a list to Array object, remove all empty items at start and end of the list and store count to info
* @param list list to cast
* @param delimeter delimter of the list
* @param info
* @return Array Object
*/
public static Array listToArrayTrim(String list, String delimeter, int[] info) {
if(delimeter.length()==1)return listToArrayTrim(list, delimeter.charAt(0),info);
if(list.length()==0) return new ArrayImpl();
char[] del = delimeter.toCharArray();
char c;
// remove at start
outer:while(list.length()>0) {
c=list.charAt(0);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
info[0]++;
list=list.substring(1);
continue outer;
}
}
break;
}
int len;
outer:while(list.length()>0) {
c=list.charAt(list.length()-1);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
info[1]++;
len=list.length();
list=list.substring(0,len-1<0?0:len-1);
continue outer;
}
}
break;
}
return listToArray(list, delimeter);
}
/**
* casts a list to Array object, remove all empty items at start and end of the list and store count to info
* @param list list to cast
* @param delimeter delimter of the list
* @param info
* @return Array Object
* @throws ExpressionException
*/
public static String listInsertAt(String list, int pos, String value, String delimeter, boolean ignoreEmpty) throws ExpressionException {
if(pos<1)
throw new ExpressionException("invalid string list index ["+(pos)+"]");
char[] del = delimeter.toCharArray();
char c;
StringBuffer result=new StringBuffer();
String end="";
int len;
// remove at start
if(ignoreEmpty){
outer:while(list.length()>0) {
c=list.charAt(0);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
list=list.substring(1);
result.append(c);
continue outer;
}
}
break;
}
}
// remove at end
if(ignoreEmpty){
outer:while(list.length()>0) {
c=list.charAt(list.length()-1);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
len=list.length();
list=list.substring(0,len-1<0?0:len-1);
end=c+end;
continue outer;
}
}
break;
}
}
len=list.length();
int last=0;
int count=0;
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
if(!ignoreEmpty || last<i) {
if(pos==++count){
result.append(value);
result.append(del[0]);
}
}
result.append(list.substring(last,i));
result.append(c);
last=i+1;
}
}
}
count++;
if(last<=len){
if(pos==count) {
result.append(value);
result.append(del[0]);
}
result.append(list.substring(last));
}
if(pos>count) {
throw new ExpressionException("invalid string list index ["+(pos)+"], indexes go from 1 to "+(count));
}
return result+end;
}
/**
* casts a list to Array object, remove all empty items at start and end of the list
* @param list list to cast
* @param delimeter delimter of the list
* @return Array Object
*/
public static Array listToArrayTrim(String list, char delimeter) {
if(list.length()==0) return new ArrayImpl();
// remove at start
while(list.indexOf(delimeter)==0) {
list=list.substring(1);
}
int len=list.length();
if(len==0) return new ArrayImpl();
while(list.lastIndexOf(delimeter)==len-1) {
list=list.substring(0,len-1<0?0:len-1);
len=list.length();
}
return listToArray(list, delimeter);
}
/**
* @param list
* @param delimeter
* @return trimmed list
*/
public static StringList toListTrim(String list, char delimeter) {
if(list.length()==0) return new StringList();
// remove at start
while(list.indexOf(delimeter)==0) {
list=list.substring(1);
}
int len=list.length();
if(len==0) return new StringList();
while(list.lastIndexOf(delimeter)==len-1) {
list=list.substring(0,len-1<0?0:len-1);
len=list.length();
}
return toList(list, delimeter);
}
/**
* @param list
* @param delimeter
* @return list
*/
public static StringList toList(String list, char delimeter) {
if(list.length()==0) return new StringList();
int len=list.length();
int last=0;
StringList rtn=new StringList();
for(int i=0;i<len;i++) {
if(list.charAt(i)==delimeter) {
rtn.add(list.substring(last,i));
last=i+1;
}
}
if(last<=len)rtn.add(list.substring(last));
rtn.reset();
return rtn;
}
public static StringList toWordList(String list) {
if(list.length()==0) return new StringList();
int len=list.length();
int last=0;
char c,l=0;
StringList rtn=new StringList();
for(int i=0;i<len;i++) {
if(StringUtil.isWhiteSpace(c=list.charAt(i))) {
rtn.add(list.substring(last,i),l);
l=c;
last=i+1;
}
}
if(last<=len)rtn.add(list.substring(last),l);
rtn.reset();
return rtn;
}
/**
* casts a list to Array object, remove all empty items at start and end of the list
* @param list list to cast
* @param delimeter delimter of the list
* @param info
* @return Array Object
*/
public static Array listToArrayTrim(String list, char delimeter, int[] info) {
if(list.length()==0) return new ArrayImpl();
// remove at start
while(list.indexOf(delimeter)==0) {
info[0]++;
list=list.substring(1);
}
int len=list.length();
if(len==0) return new ArrayImpl();
while(list.lastIndexOf(delimeter)==len-1) {
info[1]++;
list=list.substring(0,len-1<0?0:len-1);
len=list.length();
}
return listToArray(list, delimeter);
}
/**
* finds a value inside a list, ignore case
* @param list list to search
* @param value value to find
* @return position in list (0-n) or -1
*/
public static int listFindNoCase(String list, String value) {
return listFindNoCase(list, value, ",", true);
}
/**
* finds a value inside a list, do not ignore case
* @param list list to search
* @param value value to find
* @param delimeter delimeter of the list
* @return position in list (0-n) or -1
*/
public static int listFindNoCase(String list, String value, String delimeter) {
return listFindNoCase(list, value, delimeter, true);
}
/**
* finds a value inside a list, do not ignore case
* @param list list to search
* @param value value to find
* @param delimeter delimeter of the list
* @param trim trim the list or not
* @return position in list (0-n) or -1
*/
public static int listFindNoCase(String list, String value, String delimeter,boolean trim) {
Array arr = trim?listToArrayTrim(list,delimeter):listToArray(list,delimeter);
int len=arr.size();
for(int i=1;i<=len;i++) {
if(((String)arr.get(i,"")).equalsIgnoreCase(value)) return i-1;
}
return -1;
}
public static int listFindForSwitch(String list, String value, String delimeter) {
if(list.indexOf(delimeter)==-1 && list.equalsIgnoreCase(value)) return 1;
Array arr = listToArray(list,delimeter);
int len=arr.size();
for(int i=1;i<=len;i++) {
if(((String)arr.get(i,"")).equalsIgnoreCase(value)) return i;
}
return -1;
}
/**
* finds a value inside a list, ignore case, ignore empty items
* @param list list to search
* @param value value to find
* @param delimeter delimeter of the list
* @return position in list or 0
*/
public static int listFindNoCaseIgnoreEmpty(String list, String value, String delimeter) {
if(delimeter.length()==1)return listFindNoCaseIgnoreEmpty(list, value, delimeter.charAt(0));
if(list==null) return -1;
int len=list.length();
if(len==0) return -1;
int last=0;
int count=0;
char[] del = delimeter.toCharArray();
char c;
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
if(last<i) {
if(list.substring(last,i).equalsIgnoreCase(value)) return count;
count++;
}
last=i+1;
}
}
}
if(last<len) {
if(list.substring(last).equalsIgnoreCase(value)) return count;
}
return -1;
}
/**
* finds a value inside a list, ignore case, ignore empty items
* @param list list to search
* @param value value to find
* @param delimeter delimeter of the list
* @return position in list or 0
*/
public static int listFindNoCaseIgnoreEmpty(String list, String value, char delimeter) {
if(list==null) return -1;
int len=list.length();
if(len==0) return -1;
int last=0;
int count=0;
for(int i=0;i<len;i++) {
if(list.charAt(i)==delimeter) {
if(last<i) {
if(list.substring(last,i).equalsIgnoreCase(value)) return count;
count++;
}
last=i+1;
}
}
if(last<len) {
if(list.substring(last).equalsIgnoreCase(value)) return count;
}
return -1;
}
/**
* finds a value inside a list, case sensitive
* @param list list to search
* @param value value to find
* @return position in list or 0
*/
public static int listFind(String list, String value) {
return listFind(list, value, ",");
}
/**
* finds a value inside a list, do not case sensitive
* @param list list to search
* @param value value to find
* @param delimeter delimeter of the list
* @return position in list or 0
*/
public static int listFind(String list, String value, String delimeter) {
Array arr = listToArrayTrim(list,delimeter);
int len=arr.size();
for(int i=1;i<=len;i++) {
if(arr.get(i,"").equals(value)) return i-1;
}
return -1;
}
/**
* finds a value inside a list, case sensitive, ignore empty items
* @param list list to search
* @param value value to find
* @param delimeter delimeter of the list
* @return position in list or 0
*/
public static int listFindIgnoreEmpty(String list, String value, String delimeter) {
if(delimeter.length()==1)return listFindIgnoreEmpty(list, value, delimeter.charAt(0));
if(list==null) return -1;
int len=list.length();
if(len==0) return -1;
int last=0;
int count=0;
char[] del = delimeter.toCharArray();
char c;
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
if(last<i) {
if(list.substring(last,i).equals(value)) return count;
count++;
}
last=i+1;
}
}
}
if(last<len) {
if(list.substring(last).equals(value)) return count;
}
return -1;
}
/**
* finds a value inside a list, case sensitive, ignore empty items
* @param list list to search
* @param value value to find
* @param delimeter delimeter of the list
* @return position in list or 0
*/
public static int listFindIgnoreEmpty(String list, String value, char delimeter) {
if(list==null) return -1;
int len=list.length();
if(len==0) return -1;
int last=0;
int count=0;
for(int i=0;i<len;i++) {
if(list.charAt(i)==delimeter) {
if(last<i) {
if(list.substring(last,i).equals(value)) return count;
count++;
}
last=i+1;
}
}
if(last<len) {
if(list.substring(last).equals(value)) return count;
}
return -1;
}
/**
* returns if a value of the list contains given value, ignore case
* @param list list to search in
* @param value value to serach
* @param delimeter delimeter of the list
* @return position in list or 0
*/
public static int listContainsNoCase(String list, String value, String delimeter) {
if(StringUtil.isEmpty(value)) return -1;
Array arr=listToArray(list,delimeter);
int len=arr.size();
for(int i=1;i<=len;i++) {
if(StringUtil.indexOfIgnoreCase(arr.get(i,"").toString(), value)!=-1) return i-1;
}
return -1;
}
/**
* returns if a value of the list contains given value, ignore case, ignore empty values
* @param list list to search in
* @param value value to serach
* @param delimeter delimeter of the list
* @return position in list or 0
*/
public static int listContainsIgnoreEmptyNoCase(String list, String value, String delimeter) {
if(StringUtil.isEmpty(value)) return -1;
Array arr=listToArrayRemoveEmpty(list,delimeter);
int count=0;
int len=arr.size();
for(int i=1;i<=len;i++) {
String item=arr.get(i,"").toString();
if(StringUtil.indexOfIgnoreCase(item, value)!=-1) return count;
count++;
}
return -1;
}
/**
* returns if a value of the list contains given value, case sensitive
* @param list list to search in
* @param value value to serach
* @param delimeter delimeter of the list
* @return position in list or 0
*/
public static int listContains(String list, String value, String delimeter) {
if(StringUtil.isEmpty(value)) return -1;
Array arr=listToArray(list,delimeter);
int len=arr.size();
for(int i=1;i<=len;i++) {
if(arr.get(i,"").toString().indexOf(value)!=-1) return i-1;
}
return -1;
}
/**
* returns if a value of the list contains given value, case sensitive, ignore empty positions
* @param list list to search in
* @param value value to serach
* @param delimeter delimeter of the list
* @return position in list or 0
*/
public static int listContainsIgnoreEmpty(String list, String value, String delimeter) {
if(StringUtil.isEmpty(value)) return -1;
Array arr=listToArrayRemoveEmpty(list,delimeter);
int count=0;
int len=arr.size();
for(int i=1;i<=len;i++) {
String item=arr.get(i,"").toString();
if(item.indexOf(value)!=-1) return count;
count++;
}
return -1;
}
/**
* convert a string array to string list, removes empty values at begin and end of the list
* @param array array to convert
* @param delimeter delimeter for the new list
* @return list generated from string array
*/
public static String arrayToListTrim(String[] array, String delimeter) {
return trim(arrayToList(array,delimeter),delimeter);
}
/**
* convert a string array to string list
* @param array array to convert
* @param delimeter delimeter for the new list
* @return list generated from string array
*/
public static String arrayToList(String[] array, String delimeter) {
if(ArrayUtil.isEmpty(array)) return "";
StringBuffer sb=new StringBuffer(array[0]);
if(delimeter.length()==1) {
char c=delimeter.charAt(0);
for(int i=1;i<array.length;i++) {
sb.append(c);
sb.append(array[i]);
}
}
else {
for(int i=1;i<array.length;i++) {
sb.append(delimeter);
sb.append(array[i]);
}
}
return sb.toString();
}
public static String arrayToList(Collection.Key[] array, String delimeter) {
if(array.length==0) return "";
StringBuffer sb=new StringBuffer(array[0].getString());
if(delimeter.length()==1) {
char c=delimeter.charAt(0);
for(int i=1;i<array.length;i++) {
sb.append(c);
sb.append(array[i].getString());
}
}
else {
for(int i=1;i<array.length;i++) {
sb.append(delimeter);
sb.append(array[i].getString());
}
}
return sb.toString();
}
/**
* convert Array Object to string list
* @param array array to convert
* @param delimeter delimeter for the new list
* @return list generated from string array
* @throws PageException
*/
public static String arrayToList(Array array, String delimeter) throws PageException {
if(array.size()==0) return "";
StringBuffer sb=new StringBuffer(Caster.toString(array.getE(1)));
int len=array.size();
for(int i=2;i<=len;i++) {
sb.append(delimeter);
sb.append(array.get(i,""));
}
return sb.toString();
}
public static String listToList(java.util.List list, String delimeter) throws PageException {
if(list.size()==0) return "";
StringBuffer sb=new StringBuffer();
Iterator it = list.iterator();
if(it.hasNext()) sb.append(Caster.toString(it.next()));
while(it.hasNext()) {
sb.append(delimeter);
sb.append(Caster.toString(it.next()));
}
return sb.toString();
}
/**
* trims a string array, removes all empty array positions at the start and the end of the array
* @param array array to remove elements
* @return cleared array
*/
public static String[] trim(String[] array) {
int from=0;
int to=0;
// test start
for(int i=0;i<array.length;i++) {
from=i;
if(array[i].length()!=0)break;
}
// test end
for(int i=array.length-1;i>=0;i--) {
to=i;
if(array[i].length()!=0)break;
}
int newLen=to-from+1;
if(newLen<array.length) {
String[] rtn=new String[newLen];
System.arraycopy(array,from,rtn,0,newLen);
return rtn;
}
return array;
}
/**
* trims a string list, remove all empty delimeter at start and the end
* @param list list to trim
* @param delimeter delimeter of the list
* @return trimed list
*/
public static String trim(String list, String delimeter) {
return trim(list,delimeter,new int[2]);
}
/**
* trims a string list, remove all empty delimeter at start and the end
* @param list list to trim
* @param delimeter delimeter of the list
* @param removeInfo int array contain count of removed values (removeInfo[0]=at the begin;removeInfo[1]=at the end)
* @return trimed list
*/
public static String trim(String list, String delimeter,int[] removeInfo) {
if(list.length()==0)return "";
int from=0;
int to=list.length();
//int len=delimeter.length();
char[] del=delimeter.toCharArray();
char c;
// remove at start
outer:while(list.length()>from) {
c=list.charAt(from);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
from++;
removeInfo[0]++;
//list=list.substring(from);
continue outer;
}
}
break;
}
//int len;
outer:while(to>from) {
c=list.charAt(to-1);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
to--;
removeInfo[1]++;
continue outer;
}
}
break;
}
int newLen=to-from;
if(newLen<list.length()) {
return list.substring(from,to);
}
return list;
}
/**
* sorts a string list
* @param list list to sort
* @param sortType sort type (numeric,text,textnocase)
* @param sortOrder sort order (asc,desc)
* @param delimiter list delimeter
* @return sorted list
* @throws PageException
*/
public static String sortIgnoreEmpty(String list, String sortType, String sortOrder, String delimiter) throws PageException {
return _sort(toStringArray(listToArrayRemoveEmpty(list,delimiter)),sortType, sortOrder, delimiter);
}
/**
* sorts a string list
* @param list list to sort
* @param sortType sort type (numeric,text,textnocase)
* @param sortOrder sort order (asc,desc)
* @param delimiter list delimeter
* @return sorted list
* @throws PageException
*/
public static String sort(String list, String sortType, String sortOrder, String delimiter) throws PageException {
return _sort(toStringArray(listToArray(list,delimiter)),sortType, sortOrder, delimiter);
}
private static String _sort(Object[] arr, String sortType, String sortOrder, String delimiter) throws ExpressionException {
// check sortorder
boolean isAsc=true;
PageException ee=null;
if(sortOrder.equalsIgnoreCase("asc"))isAsc=true;
else if(sortOrder.equalsIgnoreCase("desc"))isAsc=false;
else throw new ExpressionException("invalid sort order type ["+sortOrder+"], sort order types are [asc and desc]");
// text
if(sortType.equalsIgnoreCase("text")) {
TextComparator comp=new TextComparator(isAsc,false);
Arrays.sort(arr,comp);
ee=comp.getPageException();
}
// text no case
else if(sortType.equalsIgnoreCase("textnocase")) {
TextComparator comp=new TextComparator(isAsc,true);
Arrays.sort(arr,comp);
ee=comp.getPageException();
}
// numeric
else if(sortType.equalsIgnoreCase("numeric")) {
NumberComparator comp=new NumberComparator(isAsc);
Arrays.sort(arr,comp);
ee=comp.getPageException();
}
else {
throw new ExpressionException("invalid sort type ["+sortType+"], sort types are [text, textNoCase, numeric]");
}
if(ee!=null) {
throw new ExpressionException("invalid value to sort the list",ee.getMessage());
}
StringBuffer sb=new StringBuffer();
for(int i=0;i<arr.length;i++) {
if(i!=0)sb.append(delimiter);
sb.append(arr[i]);
}
return sb.toString();
}
/**
* cast a Object Array to a String Array
* @param array
* @return String Array
*/
public static String[] toStringArrayEL(Array array) {
String[] arr=new String[array.size()];
for(int i=0;i<arr.length;i++) {
arr[i]=Caster.toString(array.get(i+1,null),null);
}
return arr;
}
/**
* cast a Object Array to a String Array
* @param array
* @return String Array
* @throws PageException
*/
public static String[] toStringArray(Array array) throws PageException {
String[] arr=new String[array.size()];
for(int i=0;i<arr.length;i++) {
arr[i]=Caster.toString(array.get(i+1,null));
}
return arr;
}
/**
* cast a Object Array to a String Array
* @param array
* @param defaultValue
* @return String Array
*/
public static String[] toStringArray(Array array,String defaultValue) {
String[] arr=new String[array.size()];
for(int i=0;i<arr.length;i++) {
arr[i]=Caster.toString(array.get(i+1,defaultValue),defaultValue);
}
return arr;
}
/**
* cast a Object Array to a String Array and trim all values
* @param array
* @return String Array
* @throws PageException
*/
public static String[] toStringArrayTrim(Array array) throws PageException {
String[] arr=new String[array.size()];
for(int i=0;i<arr.length;i++) {
arr[i]=Caster.toString(array.get(i+1,"")).trim();
}
return arr;
}
/**
* return first element of the list
* @param list
* @param delimeter
* @return returns the first element of the list
* @deprecated use instead first(String list, String delimeter, boolean ignoreEmpty)
*/
public static String first(String list, String delimeter) {
return first(list, delimeter,true);
}
/**
* return first element of the list
* @param list
* @param delimeter
* @param ignoreEmpty
* @return returns the first element of the list
*/
public static String first(String list, String delimeter, boolean ignoreEmpty) {
if(StringUtil.isEmpty(list)) return "";
char[] del;
if(StringUtil.isEmpty(delimeter)) {
del=new char[]{','};
}
else {
del=delimeter.toCharArray();
}
int offset=0;
int index;
int x;
while(true) {
index=-1;
for(int i=0;i<del.length;i++) {
x=list.indexOf(del[i],offset);
if(x!=-1 && (x<index || index==-1))index=x;
}
//index=list.indexOf(index,offset);
if(index==-1) {
if(offset>0) return list.substring(offset);
return list;
}
if(!ignoreEmpty && index==0) {
return "";
}
else if(index==offset) {
offset++;
}
else {
if(offset>0)return list.substring(offset,index);
return list.substring(0,index);
}
}
}
/**
* return last element of the list
* @param list
* @param delimeter
* @return returns the last Element of a list
* @deprecated use instead last(String list, String delimeter, boolean ignoreEmpty)
*/
public static String last(String list, String delimeter) {
return last(list, delimeter, true);
}
/**
* return last element of the list
* @param list
* @param delimeter
* @param ignoreEmpty
* @return returns the last Element of a list
*/
public static String last(String list, String delimeter, boolean ignoreEmpty) {
if(StringUtil.isEmpty(list)) return "";
int len=list.length();
char[] del;
if(StringUtil.isEmpty(delimeter)) {
del=new char[]{','};
}
else del=delimeter.toCharArray();
int index;
int x;
while(true) {
index=-1;
for(int i=0;i<del.length;i++) {
x=list.lastIndexOf(del[i]);
if(x>index)index=x;
}
if(index==-1) {
return list;
}
else if(index+1==len) {
if(!ignoreEmpty) return"";
list=list.substring(0,len-1);
len--;
}
else {
return list.substring(index+1);
}
}
}
/**
* return last element of the list
* @param list
* @param delimeter
* @return returns the last Element of a list
*/
public static String last(String list, char delimeter) {
int len=list.length();
if(len==0) return "";
int index=0;
while(true) {
index=list.lastIndexOf(delimeter);
if(index==-1) {
return list;
}
else if(index+1==len) {
list=list.substring(0,len-1);
len--;
}
else {
return list.substring(index+1);
}
}
}
/**
* returns count of items in the list
* @param list
* @param delimeter
* @return list len
*/
public static int len(String list, char delimeter,boolean ignoreEmpty) {
int len=list.length();
if(list==null || len==0) return 0;
int count=0;
int last=0;
for(int i=0;i<len;i++) {
if(list.charAt(i)==delimeter) {
if(!ignoreEmpty || last<i)count++;
last=i+1;
}
}
if(!ignoreEmpty || last<len)count++;
return count;
}
/**
* returns count of items in the list
* @param list
* @param delimeter
* @return list len
*/
public static int len(String list, String delimeter, boolean ignoreEmpty) {
if(delimeter.length()==1)return len(list, delimeter.charAt(0),ignoreEmpty);
char[] del=delimeter.toCharArray();
int len=list.length();
if(list==null || len==0) return 0;
int count=0;
int last=0;
char c;
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
if(!ignoreEmpty || last<i)count++;
last=i+1;
}
}
}
if(!ignoreEmpty || last<len)count++;
return count;
}
/* *
* cast a int into a char
* @param i int to cast
* @return int as char
* /
private char c(int i) {
return (char)i;
}*/
/**
* gets a value from list
* @param list list to cast
* @param delimeter delimter of the list
* @param position
* @return Array Object
*/
public static String getAt(String list, String delimeter, int position, boolean ignoreEmpty) {
if(delimeter.length()==1)return getAt(list, delimeter.charAt(0), position,ignoreEmpty);
int len=list.length();
if(len==0) return null;
int last=0;
int count=0;
char[] del = delimeter.toCharArray();
char c;
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
if(!ignoreEmpty || last<i) {
if(count++==position) {
return list.substring(last,i);
}
}
last=i+1;
}
}
}
if(last<len && position==count) return (list.substring(last));
return null;
}
/**
* get a elemnt at a specified position in list
* @param list list to cast
* @param delimeter delimter of the list
* @param position
* @return Array Object
*/
public static String getAt(String list, char delimeter, int position, boolean ignoreEmpty) {
int len=list.length();
if(len==0) return null;
int last=0;
int count=0;
for(int i=0;i<len;i++) {
if(list.charAt(i)==delimeter) {
if(!ignoreEmpty || last<i) {
if(count++==position) {
return list.substring(last,i);
}
}
last=i+1;
}
}
if(last<len && position==count) return (list.substring(last));
return null;
}
public static String[] listToStringArray(String list, char delimeter) {
Array array = List.listToArrayRemoveEmpty(list,delimeter);
String[] arr=new String[array.size()];
for(int i=0;i<arr.length;i++) {
arr[i]=Caster.toString(array.get(i+1,""),"");
}
return arr;
}
/**
* trim every single item of the array
* @param arr
* @return
*/
public static String[] trimItems(String[] arr) {
for(int i=0;i<arr.length;i++) {
arr[i]=arr[i].trim();
}
return arr;
}
/**
* trim every single item of the array
* @param arr
* @return
* @throws PageException
*/
public static Array trimItems(Array arr) throws PageException {
Key[] keys = arr.keys();
for(int i=0;i<keys.length;i++) {
arr.setEL(keys[i], Caster.toString(arr.get(keys[i],null)).trim());
}
return arr;
}
public static Set<String> listToSet(String list, String delimeter,boolean trim) {
if(list.length()==0) return new HashSet<String>();
int len=list.length();
int last=0;
char[] del=delimeter.toCharArray();
char c;
HashSet<String> set=new HashSet<String>();
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
set.add(trim?list.substring(last,i).trim():list.substring(last,i));
last=i+1;
}
}
}
if(last<=len)set.add(list.substring(last));
return set;
}
public static Set<String> listToSet(String list, char delimeter,boolean trim) {
if(list.length()==0) return new HashSet<String>();
int len=list.length();
int last=0;
char c;
HashSet<String> set=new HashSet<String>();
for(int i=0;i<len;i++) {
c=list.charAt(i);
if(c==delimeter) {
set.add(trim?list.substring(last,i).trim():list.substring(last,i));
last=i+1;
}
}
if(last<=len)set.add(list.substring(last));
return set;
}
public static Set<String> toSet(String[] arr) {
Set<String> set=new HashSet<String>();
for(int i=0;i<arr.length;i++){
set.add(arr[i]);
}
return set;
}
} | railo-java/railo-core/src/railo/runtime/type/List.java | package railo.runtime.type;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import railo.commons.lang.StringList;
import railo.commons.lang.StringUtil;
import railo.runtime.exp.ExpressionException;
import railo.runtime.exp.PageException;
import railo.runtime.op.Caster;
import railo.runtime.type.Collection.Key;
import railo.runtime.type.comparator.NumberComparator;
import railo.runtime.type.comparator.TextComparator;
import railo.runtime.type.util.ArrayUtil;
/**
* List is not a type, only some static method to manipulate String lists
*/
public final class List {
/**
* casts a list to Array object, the list can be have quoted (",') arguments and delimter in this arguments are ignored. quotes are not removed
* example:
* listWithQuotesToArray("aab,a'a,b',a\"a,b\"",",","\"'") will be translated to ["aab","a'a,b'","a\"a,b\""]
*
*
*
* @param list list to cast
* @param delimeter delimter of the list
* @param quotes quotes of the list
* @return Array Object
*/
public static Array listWithQuotesToArray(String list, String delimeter,String quotes) {
if(list.length()==0) return new ArrayImpl();
int len=list.length();
int last=0;
char[] del=delimeter.toCharArray();
char[] quo=quotes.toCharArray();
char c;
char inside=0;
ArrayImpl array=new ArrayImpl();
try{
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<quo.length;y++){
if(c==quo[y]) {
if(c==inside)inside=0;
else if(inside==0)inside=c;
continue;
}
}
for(int y=0;y<del.length;y++) {
if(inside==0 && c==del[y]) {
array._append(list.substring(last,i));
last=i+1;
}
}
}
if(last<=len)array.append(list.substring(last));
}
catch(ExpressionException e){}
return array;
}
/**
* casts a list to Array object
* @param list list to cast
* @param delimeter delimter of the list
* @return Array Object
*/
public static Array listToArray(String list, String delimeter) {
if(delimeter.length()==1)return listToArray(list, delimeter.charAt(0));
if(list.length()==0) return new ArrayImpl();
int len=list.length();
int last=0;
char[] del=delimeter.toCharArray();
char c;
ArrayImpl array=new ArrayImpl();
try{
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
array.appendEL(list.substring(last,i));
last=i+1;
}
}
}
if(last<=len)array.append(list.substring(last));
}
catch(ExpressionException e){}
return array;
}
public static Array listToArray(String list, String delimeter, boolean multiCharDelim) {
if(!multiCharDelim) return listToArray(list, delimeter);
if(delimeter.length()==1)return listToArray(list, delimeter.charAt(0));
int len=list.length();
if(len==0) return new ArrayImpl();
Array array=new ArrayImpl();
int from=0;
int index;
int dl=delimeter.length();
while((index=list.indexOf(delimeter,from))!=-1){
array.appendEL(list.substring(from,index));
from=index+dl;
}
array.appendEL(list.substring(from,len));
return array;
}
/**
* casts a list to Array object
* @param list list to cast
* @param delimeter delimter of the list
* @return Array Object
*/
public static Array listToArray(String list, char delimeter) {
if(list.length()==0) return new ArrayImpl();
int len=list.length();
int last=0;
Array array=new ArrayImpl();
try{
for(int i=0;i<len;i++) {
if(list.charAt(i)==delimeter) {
array.append(list.substring(last,i));
last=i+1;
}
}
if(last<=len)array.append(list.substring(last));
}
catch(PageException e){}
return array;
}
/**
* casts a list to Array object remove Empty Elements
* @param list list to cast
* @param delimeter delimter of the list
* @return Array Object
*/
public static Array listToArrayRemoveEmpty(String list, String delimeter, boolean multiCharDelim) {
if(!multiCharDelim) return listToArrayRemoveEmpty(list, delimeter);
if(delimeter.length()==1)return listToArrayRemoveEmpty(list, delimeter.charAt(0));
int len=list.length();
if(len==0) return new ArrayImpl();
Array array=new ArrayImpl();
int from=0;
int index;
int dl=delimeter.length();
while((index=list.indexOf(delimeter,from))!=-1){
if(from<index)array.appendEL(list.substring(from,index));
from=index+dl;
}
if(from<len)array.appendEL(list.substring(from,len));
return array;
}
public static Array listToArrayRemoveEmpty(String list, String delimeter) {
if(delimeter.length()==1)return listToArrayRemoveEmpty(list, delimeter.charAt(0));
int len=list.length();
ArrayImpl array=new ArrayImpl();
if(len==0) return array;
int last=0;
char[] del = delimeter.toCharArray();
char c;
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
if(last<i)array._append(list.substring(last,i));
last=i+1;
}
}
}
if(last<len)array._append(list.substring(last));
return array;
}
/**
* casts a list to Array object remove Empty Elements
* @param list list to cast
* @param delimeter delimter of the list
* @return Array Object
*/
public static Array listToArrayRemoveEmpty(String list, char delimeter) {
int len=list.length();
ArrayImpl array=new ArrayImpl();
if(len==0) return array;
int last=0;
for(int i=0;i<len;i++) {
if(list.charAt(i)==delimeter) {
if(last<i)array._append(list.substring(last,i));
last=i+1;
}
}
if(last<len)array._append(list.substring(last));
return array;
}
/**
* casts a list to Array object remove Empty Elements
* @param list list to cast
* @param delimeter delimter of the list
* @return Array Object
*/
public static String rest(String list, String delimeter, boolean ignoreEmpty) {
//if(delimeter.length()==1)return rest(list, delimeter.charAt(0));
int len=list.length();
if(len==0) return "";
//int last=-1;
char[] del = delimeter.toCharArray();
char c;
if(ignoreEmpty)list=ltrim(list,del);
len=list.length();
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
return ignoreEmpty?ltrim(list.substring(i+1),del):list.substring(i+1);
}
}
}
return "";
}
private static String ltrim(String list,char[] del) {
int len=list.length();
char c;
// remove at start
outer:while(len>0) {
c=list.charAt(0);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
list=list.substring(1);
list.length();
continue outer;
}
}
break;
}
return list;
}
/**
* casts a list to Array object remove Empty Elements
* @param list list to cast
* @param delimeter delimter of the list
* @return Array Object
*/
public static StringList listToStringListRemoveEmpty(String list, char delimeter) {
int len=list.length();
StringList rtn=new StringList();
if(len==0) return rtn.reset();
int last=0;
for(int i=0;i<len;i++) {
if(list.charAt(i)==delimeter) {
if(last<i)rtn.add(list.substring(last,i));
last=i+1;
}
}
if(last<len)rtn.add(list.substring(last));
return rtn.reset();
}
/**
* casts a list to Array object, remove all empty items at start and end of the list
* @param list list to cast
* @param delimeter delimter of the list
* @return Array Object
*/
public static Array listToArrayTrim(String list, String delimeter) {
if(delimeter.length()==1)return listToArrayTrim(list, delimeter.charAt(0));
if(list.length()==0) return new ArrayImpl();
char[] del = delimeter.toCharArray();
char c;
// remove at start
outer:while(list.length()>0) {
c=list.charAt(0);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
list=list.substring(1);
continue outer;
}
}
break;
}
int len;
outer:while(list.length()>0) {
c=list.charAt(list.length()-1);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
len=list.length();
list=list.substring(0,len-1<0?0:len-1);
continue outer;
}
}
break;
}
return listToArray(list, delimeter);
}
/**
* casts a list to Array object, remove all empty items at start and end of the list and store count to info
* @param list list to cast
* @param delimeter delimter of the list
* @param info
* @return Array Object
*/
public static Array listToArrayTrim(String list, String delimeter, int[] info) {
if(delimeter.length()==1)return listToArrayTrim(list, delimeter.charAt(0),info);
if(list.length()==0) return new ArrayImpl();
char[] del = delimeter.toCharArray();
char c;
// remove at start
outer:while(list.length()>0) {
c=list.charAt(0);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
info[0]++;
list=list.substring(1);
continue outer;
}
}
break;
}
int len;
outer:while(list.length()>0) {
c=list.charAt(list.length()-1);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
info[1]++;
len=list.length();
list=list.substring(0,len-1<0?0:len-1);
continue outer;
}
}
break;
}
return listToArray(list, delimeter);
}
/**
* casts a list to Array object, remove all empty items at start and end of the list and store count to info
* @param list list to cast
* @param delimeter delimter of the list
* @param info
* @return Array Object
* @throws ExpressionException
*/
public static String listInsertAt(String list, int pos, String value, String delimeter, boolean ignoreEmpty) throws ExpressionException {
if(pos<1)
throw new ExpressionException("invalid string list index ["+(pos)+"]");
char[] del = delimeter.toCharArray();
char c;
StringBuffer result=new StringBuffer();
String end="";
int len;
// remove at start
if(ignoreEmpty){
outer:while(list.length()>0) {
c=list.charAt(0);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
list=list.substring(1);
result.append(c);
continue outer;
}
}
break;
}
}
// remove at end
if(ignoreEmpty){
outer:while(list.length()>0) {
c=list.charAt(list.length()-1);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
len=list.length();
list=list.substring(0,len-1<0?0:len-1);
end=c+end;
continue outer;
}
}
break;
}
}
len=list.length();
int last=0;
int count=0;
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
if(!ignoreEmpty || last<i) {
if(pos==++count){
result.append(value);
result.append(del[0]);
}
}
result.append(list.substring(last,i));
result.append(c);
last=i+1;
}
}
}
count++;
if(last<=len){
if(pos==count) {
result.append(value);
result.append(del[0]);
}
result.append(list.substring(last));
}
if(pos>count) {
throw new ExpressionException("invalid string list index ["+(pos)+"], indexes go from 1 to "+(count));
}
return result+end;
}
/**
* casts a list to Array object, remove all empty items at start and end of the list
* @param list list to cast
* @param delimeter delimter of the list
* @return Array Object
*/
public static Array listToArrayTrim(String list, char delimeter) {
if(list.length()==0) return new ArrayImpl();
// remove at start
while(list.indexOf(delimeter)==0) {
list=list.substring(1);
}
int len=list.length();
if(len==0) return new ArrayImpl();
while(list.lastIndexOf(delimeter)==len-1) {
list=list.substring(0,len-1<0?0:len-1);
len=list.length();
}
return listToArray(list, delimeter);
}
/**
* @param list
* @param delimeter
* @return trimmed list
*/
public static StringList toListTrim(String list, char delimeter) {
if(list.length()==0) return new StringList();
// remove at start
while(list.indexOf(delimeter)==0) {
list=list.substring(1);
}
int len=list.length();
if(len==0) return new StringList();
while(list.lastIndexOf(delimeter)==len-1) {
list=list.substring(0,len-1<0?0:len-1);
len=list.length();
}
return toList(list, delimeter);
}
/**
* @param list
* @param delimeter
* @return list
*/
public static StringList toList(String list, char delimeter) {
if(list.length()==0) return new StringList();
int len=list.length();
int last=0;
StringList rtn=new StringList();
for(int i=0;i<len;i++) {
if(list.charAt(i)==delimeter) {
rtn.add(list.substring(last,i));
last=i+1;
}
}
if(last<=len)rtn.add(list.substring(last));
rtn.reset();
return rtn;
}
public static StringList toWordList(String list) {
if(list.length()==0) return new StringList();
int len=list.length();
int last=0;
char c,l=0;
StringList rtn=new StringList();
for(int i=0;i<len;i++) {
if(StringUtil.isWhiteSpace(c=list.charAt(i))) {
rtn.add(list.substring(last,i),l);
l=c;
last=i+1;
}
}
if(last<=len)rtn.add(list.substring(last),l);
rtn.reset();
return rtn;
}
/**
* casts a list to Array object, remove all empty items at start and end of the list
* @param list list to cast
* @param delimeter delimter of the list
* @param info
* @return Array Object
*/
public static Array listToArrayTrim(String list, char delimeter, int[] info) {
if(list.length()==0) return new ArrayImpl();
// remove at start
while(list.indexOf(delimeter)==0) {
info[0]++;
list=list.substring(1);
}
int len=list.length();
if(len==0) return new ArrayImpl();
while(list.lastIndexOf(delimeter)==len-1) {
info[1]++;
list=list.substring(0,len-1<0?0:len-1);
len=list.length();
}
return listToArray(list, delimeter);
}
/**
* finds a value inside a list, ignore case
* @param list list to search
* @param value value to find
* @return position in list (0-n) or -1
*/
public static int listFindNoCase(String list, String value) {
return listFindNoCase(list, value, ",", true);
}
/**
* finds a value inside a list, do not ignore case
* @param list list to search
* @param value value to find
* @param delimeter delimeter of the list
* @return position in list (0-n) or -1
*/
public static int listFindNoCase(String list, String value, String delimeter) {
return listFindNoCase(list, value, delimeter, true);
}
/**
* finds a value inside a list, do not ignore case
* @param list list to search
* @param value value to find
* @param delimeter delimeter of the list
* @param trim trim the list or not
* @return position in list (0-n) or -1
*/
public static int listFindNoCase(String list, String value, String delimeter,boolean trim) {
Array arr = trim?listToArrayTrim(list,delimeter):listToArray(list,delimeter);
int len=arr.size();
for(int i=1;i<=len;i++) {
if(((String)arr.get(i,"")).equalsIgnoreCase(value)) return i-1;
}
return -1;
}
public static int listFindForSwitch(String list, String value, String delimeter) {
if(list.indexOf(delimeter)==-1 && list.equalsIgnoreCase(value)) return 1;
Array arr = listToArray(list,delimeter);
int len=arr.size();
for(int i=1;i<=len;i++) {
if(((String)arr.get(i,"")).equalsIgnoreCase(value)) return i;
}
return -1;
}
/**
* finds a value inside a list, ignore case, ignore empty items
* @param list list to search
* @param value value to find
* @param delimeter delimeter of the list
* @return position in list or 0
*/
public static int listFindNoCaseIgnoreEmpty(String list, String value, String delimeter) {
if(delimeter.length()==1)return listFindNoCaseIgnoreEmpty(list, value, delimeter.charAt(0));
if(list==null) return -1;
int len=list.length();
if(len==0) return -1;
int last=0;
int count=0;
char[] del = delimeter.toCharArray();
char c;
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
if(last<i) {
if(list.substring(last,i).equalsIgnoreCase(value)) return count;
count++;
}
last=i+1;
}
}
}
if(last<len) {
if(list.substring(last).equalsIgnoreCase(value)) return count;
}
return -1;
}
/**
* finds a value inside a list, ignore case, ignore empty items
* @param list list to search
* @param value value to find
* @param delimeter delimeter of the list
* @return position in list or 0
*/
public static int listFindNoCaseIgnoreEmpty(String list, String value, char delimeter) {
if(list==null) return -1;
int len=list.length();
if(len==0) return -1;
int last=0;
int count=0;
for(int i=0;i<len;i++) {
if(list.charAt(i)==delimeter) {
if(last<i) {
if(list.substring(last,i).equalsIgnoreCase(value)) return count;
count++;
}
last=i+1;
}
}
if(last<len) {
if(list.substring(last).equalsIgnoreCase(value)) return count;
}
return -1;
}
/**
* finds a value inside a list, case sensitive
* @param list list to search
* @param value value to find
* @return position in list or 0
*/
public static int listFind(String list, String value) {
return listFind(list, value, ",");
}
/**
* finds a value inside a list, do not case sensitive
* @param list list to search
* @param value value to find
* @param delimeter delimeter of the list
* @return position in list or 0
*/
public static int listFind(String list, String value, String delimeter) {
Array arr = listToArrayTrim(list,delimeter);
int len=arr.size();
for(int i=1;i<=len;i++) {
if(arr.get(i,"").equals(value)) return i-1;
}
return -1;
}
/**
* finds a value inside a list, case sensitive, ignore empty items
* @param list list to search
* @param value value to find
* @param delimeter delimeter of the list
* @return position in list or 0
*/
public static int listFindIgnoreEmpty(String list, String value, String delimeter) {
if(delimeter.length()==1)return listFindIgnoreEmpty(list, value, delimeter.charAt(0));
if(list==null) return -1;
int len=list.length();
if(len==0) return -1;
int last=0;
int count=0;
char[] del = delimeter.toCharArray();
char c;
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
if(last<i) {
if(list.substring(last,i).equals(value)) return count;
count++;
}
last=i+1;
}
}
}
if(last<len) {
if(list.substring(last).equals(value)) return count;
}
return -1;
}
/**
* finds a value inside a list, case sensitive, ignore empty items
* @param list list to search
* @param value value to find
* @param delimeter delimeter of the list
* @return position in list or 0
*/
public static int listFindIgnoreEmpty(String list, String value, char delimeter) {
if(list==null) return -1;
int len=list.length();
if(len==0) return -1;
int last=0;
int count=0;
for(int i=0;i<len;i++) {
if(list.charAt(i)==delimeter) {
if(last<i) {
if(list.substring(last,i).equals(value)) return count;
count++;
}
last=i+1;
}
}
if(last<len) {
if(list.substring(last).equals(value)) return count;
}
return -1;
}
/**
* returns if a value of the list contains given value, ignore case
* @param list list to search in
* @param value value to serach
* @param delimeter delimeter of the list
* @return position in list or 0
*/
public static int listContainsNoCase(String list, String value, String delimeter) {
if(StringUtil.isEmpty(value)) return -1;
Array arr=listToArray(list,delimeter);
int len=arr.size();
for(int i=1;i<=len;i++) {
if(StringUtil.indexOfIgnoreCase(arr.get(i,"").toString(), value)!=-1) return i-1;
}
return -1;
}
/**
* returns if a value of the list contains given value, ignore case, ignore empty values
* @param list list to search in
* @param value value to serach
* @param delimeter delimeter of the list
* @return position in list or 0
*/
public static int listContainsIgnoreEmptyNoCase(String list, String value, String delimeter) {
if(StringUtil.isEmpty(value)) return -1;
Array arr=listToArrayRemoveEmpty(list,delimeter);
int count=0;
int len=arr.size();
for(int i=1;i<=len;i++) {
String item=arr.get(i,"").toString();
if(StringUtil.indexOfIgnoreCase(item, value)!=-1) return count;
count++;
}
return -1;
}
/**
* returns if a value of the list contains given value, case sensitive
* @param list list to search in
* @param value value to serach
* @param delimeter delimeter of the list
* @return position in list or 0
*/
public static int listContains(String list, String value, String delimeter) {
if(StringUtil.isEmpty(value)) return -1;
Array arr=listToArray(list,delimeter);
int len=arr.size();
for(int i=1;i<=len;i++) {
if(arr.get(i,"").toString().indexOf(value)!=-1) return i-1;
}
return -1;
}
/**
* returns if a value of the list contains given value, case sensitive, ignore empty positions
* @param list list to search in
* @param value value to serach
* @param delimeter delimeter of the list
* @return position in list or 0
*/
public static int listContainsIgnoreEmpty(String list, String value, String delimeter) {
if(StringUtil.isEmpty(value)) return -1;
Array arr=listToArrayRemoveEmpty(list,delimeter);
int count=0;
int len=arr.size();
for(int i=1;i<=len;i++) {
String item=arr.get(i,"").toString();
if(item.indexOf(value)!=-1) return count;
count++;
}
return -1;
}
/**
* convert a string array to string list, removes empty values at begin and end of the list
* @param array array to convert
* @param delimeter delimeter for the new list
* @return list generated from string array
*/
public static String arrayToListTrim(String[] array, String delimeter) {
return trim(arrayToList(array,delimeter),delimeter);
}
/**
* convert a string array to string list
* @param array array to convert
* @param delimeter delimeter for the new list
* @return list generated from string array
*/
public static String arrayToList(String[] array, String delimeter) {
if(ArrayUtil.isEmpty(array)) return "";
StringBuffer sb=new StringBuffer(array[0]);
if(delimeter.length()==1) {
char c=delimeter.charAt(0);
for(int i=1;i<array.length;i++) {
sb.append(c);
sb.append(array[i]);
}
}
else {
for(int i=1;i<array.length;i++) {
sb.append(delimeter);
sb.append(array[i]);
}
}
return sb.toString();
}
public static String arrayToList(Collection.Key[] array, String delimeter) {
if(array.length==0) return "";
StringBuffer sb=new StringBuffer(array[0].getString());
if(delimeter.length()==1) {
char c=delimeter.charAt(0);
for(int i=1;i<array.length;i++) {
sb.append(c);
sb.append(array[i].getString());
}
}
else {
for(int i=1;i<array.length;i++) {
sb.append(delimeter);
sb.append(array[i].getString());
}
}
return sb.toString();
}
/**
* convert Array Object to string list
* @param array array to convert
* @param delimeter delimeter for the new list
* @return list generated from string array
* @throws PageException
*/
public static String arrayToList(Array array, String delimeter) throws PageException {
if(array.size()==0) return "";
StringBuffer sb=new StringBuffer(Caster.toString(array.getE(1)));
int len=array.size();
for(int i=2;i<=len;i++) {
sb.append(delimeter);
sb.append(array.get(i,""));
}
return sb.toString();
}
public static String listToList(java.util.List list, String delimeter) throws PageException {
if(list.size()==0) return "";
StringBuffer sb=new StringBuffer();
Iterator it = list.iterator();
if(it.hasNext()) sb.append(Caster.toString(it.next()));
while(it.hasNext()) {
sb.append(delimeter);
sb.append(Caster.toString(it.next()));
}
return sb.toString();
}
/**
* trims a string array, removes all empty array positions at the start and the end of the array
* @param array array to remove elements
* @return cleared array
*/
public static String[] trim(String[] array) {
int from=0;
int to=0;
// test start
for(int i=0;i<array.length;i++) {
from=i;
if(array[i].length()!=0)break;
}
// test end
for(int i=array.length-1;i>=0;i--) {
to=i;
if(array[i].length()!=0)break;
}
int newLen=to-from+1;
if(newLen<array.length) {
String[] rtn=new String[newLen];
System.arraycopy(array,from,rtn,0,newLen);
return rtn;
}
return array;
}
/**
* trims a string list, remove all empty delimeter at start and the end
* @param list list to trim
* @param delimeter delimeter of the list
* @return trimed list
*/
public static String trim(String list, String delimeter) {
return trim(list,delimeter,new int[2]);
}
/**
* trims a string list, remove all empty delimeter at start and the end
* @param list list to trim
* @param delimeter delimeter of the list
* @param removeInfo int array contain count of removed values (removeInfo[0]=at the begin;removeInfo[1]=at the end)
* @return trimed list
*/
public static String trim(String list, String delimeter,int[] removeInfo) {
if(list.length()==0)return "";
int from=0;
int to=list.length();
//int len=delimeter.length();
char[] del=delimeter.toCharArray();
char c;
// remove at start
outer:while(list.length()>from) {
c=list.charAt(from);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
from++;
removeInfo[0]++;
//list=list.substring(from);
continue outer;
}
}
break;
}
//int len;
outer:while(to>from) {
c=list.charAt(to-1);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
to--;
removeInfo[1]++;
continue outer;
}
}
break;
}
int newLen=to-from;
if(newLen<list.length()) {
return list.substring(from,to);
}
return list;
}
/**
* sorts a string list
* @param list list to sort
* @param sortType sort type (numeric,text,textnocase)
* @param sortOrder sort order (asc,desc)
* @param delimiter list delimeter
* @return sorted list
* @throws PageException
*/
public static String sortIgnoreEmpty(String list, String sortType, String sortOrder, String delimiter) throws PageException {
return _sort(toStringArray(listToArrayRemoveEmpty(list,delimiter)),sortType, sortOrder, delimiter);
}
/**
* sorts a string list
* @param list list to sort
* @param sortType sort type (numeric,text,textnocase)
* @param sortOrder sort order (asc,desc)
* @param delimiter list delimeter
* @return sorted list
* @throws PageException
*/
public static String sort(String list, String sortType, String sortOrder, String delimiter) throws PageException {
return _sort(toStringArray(listToArray(list,delimiter)),sortType, sortOrder, delimiter);
}
private static String _sort(Object[] arr, String sortType, String sortOrder, String delimiter) throws ExpressionException {
// check sortorder
boolean isAsc=true;
PageException ee=null;
if(sortOrder.equalsIgnoreCase("asc"))isAsc=true;
else if(sortOrder.equalsIgnoreCase("desc"))isAsc=false;
else throw new ExpressionException("invalid sort order type ["+sortOrder+"], sort order types are [asc and desc]");
// text
if(sortType.equalsIgnoreCase("text")) {
TextComparator comp=new TextComparator(isAsc,false);
Arrays.sort(arr,comp);
ee=comp.getPageException();
}
// text no case
else if(sortType.equalsIgnoreCase("textnocase")) {
TextComparator comp=new TextComparator(isAsc,true);
Arrays.sort(arr,comp);
ee=comp.getPageException();
}
// numeric
else if(sortType.equalsIgnoreCase("numeric")) {
NumberComparator comp=new NumberComparator(isAsc);
Arrays.sort(arr,comp);
ee=comp.getPageException();
}
else {
throw new ExpressionException("invalid sort type ["+sortType+"], sort types are [text, textNoCase, numeric]");
}
if(ee!=null) {
throw new ExpressionException("invalid value to sort the list",ee.getMessage());
}
StringBuffer sb=new StringBuffer();
for(int i=0;i<arr.length;i++) {
if(i!=0)sb.append(delimiter);
sb.append(arr[i]);
}
return sb.toString();
}
/**
* cast a Object Array to a String Array
* @param array
* @return String Array
*/
public static String[] toStringArrayEL(Array array) {
String[] arr=new String[array.size()];
for(int i=0;i<arr.length;i++) {
arr[i]=Caster.toString(array.get(i+1,null),null);
}
return arr;
}
/**
* cast a Object Array to a String Array
* @param array
* @return String Array
* @throws PageException
*/
public static String[] toStringArray(Array array) throws PageException {
String[] arr=new String[array.size()];
for(int i=0;i<arr.length;i++) {
arr[i]=Caster.toString(array.get(i+1,null));
}
return arr;
}
/**
* cast a Object Array to a String Array
* @param array
* @param defaultValue
* @return String Array
*/
public static String[] toStringArray(Array array,String defaultValue) {
String[] arr=new String[array.size()];
for(int i=0;i<arr.length;i++) {
arr[i]=Caster.toString(array.get(i+1,defaultValue),defaultValue);
}
return arr;
}
/**
* cast a Object Array to a String Array and trim all values
* @param array
* @return String Array
* @throws PageException
*/
public static String[] toStringArrayTrim(Array array) throws PageException {
String[] arr=new String[array.size()];
for(int i=0;i<arr.length;i++) {
arr[i]=Caster.toString(array.get(i+1,"")).trim();
}
return arr;
}
/**
* return first element of the list
* @param list
* @param delimeter
* @return returns the first element of the list
* @deprecated use instead first(String list, String delimeter, boolean ignoreEmpty)
*/
public static String first(String list, String delimeter) {
return first(list, delimeter,true);
}
/**
* return first element of the list
* @param list
* @param delimeter
* @param ignoreEmpty
* @return returns the first element of the list
*/
public static String first(String list, String delimeter, boolean ignoreEmpty) {
if(StringUtil.isEmpty(list)) return "";
char[] del;
if(StringUtil.isEmpty(delimeter)) {
del=new char[]{','};
}
else {
del=delimeter.toCharArray();
}
int offset=0;
int index;
int x;
while(true) {
index=-1;
for(int i=0;i<del.length;i++) {
x=list.indexOf(del[i],offset);
if(x!=-1 && (x<index || index==-1))index=x;
}
//index=list.indexOf(index,offset);
if(index==-1) {
if(offset>0) return list.substring(offset);
return list;
}
if(!ignoreEmpty && index==0) {
return "";
}
else if(index==offset) {
offset++;
}
else {
if(offset>0)return list.substring(offset,index);
return list.substring(0,index);
}
}
}
/**
* return last element of the list
* @param list
* @param delimeter
* @return returns the last Element of a list
* @deprecated use instead last(String list, String delimeter, boolean ignoreEmpty)
*/
public static String last(String list, String delimeter) {
return last(list, delimeter, true);
}
/**
* return last element of the list
* @param list
* @param delimeter
* @param ignoreEmpty
* @return returns the last Element of a list
*/
public static String last(String list, String delimeter, boolean ignoreEmpty) {
if(StringUtil.isEmpty(list)) return "";
int len=list.length();
char[] del;
if(StringUtil.isEmpty(delimeter)) {
del=new char[]{','};
}
else del=delimeter.toCharArray();
int index;
int x;
while(true) {
index=-1;
for(int i=0;i<del.length;i++) {
x=list.lastIndexOf(del[i]);
if(x>index)index=x;
}
if(index==-1) {
return list;
}
else if(index+1==len) {
if(!ignoreEmpty) return"";
list=list.substring(0,len-1);
len--;
}
else {
return list.substring(index+1);
}
}
}
/**
* return last element of the list
* @param list
* @param delimeter
* @return returns the last Element of a list
*/
public static String last(String list, char delimeter) {
int len=list.length();
if(len==0) return "";
int index=0;
while(true) {
index=list.lastIndexOf(delimeter);
if(index==-1) {
return list;
}
else if(index+1==len) {
list=list.substring(0,len-1);
len--;
}
else {
return list.substring(index+1);
}
}
}
/**
* returns count of items in the list
* @param list
* @param delimeter
* @return list len
*/
public static int len(String list, char delimeter,boolean ignoreEmpty) {
int len=list.length();
if(list==null || len==0) return 0;
int count=0;
int last=0;
for(int i=0;i<len;i++) {
if(list.charAt(i)==delimeter) {
if(!ignoreEmpty || last<i)count++;
last=i+1;
}
}
if(!ignoreEmpty || last<len)count++;
return count;
}
/**
* returns count of items in the list
* @param list
* @param delimeter
* @return list len
*/
public static int len(String list, String delimeter, boolean ignoreEmpty) {
if(delimeter.length()==1)return len(list, delimeter.charAt(0),ignoreEmpty);
char[] del=delimeter.toCharArray();
int len=list.length();
if(list==null || len==0) return 0;
int count=0;
int last=0;
char c;
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
if(!ignoreEmpty || last<i)count++;
last=i+1;
}
}
}
if(!ignoreEmpty || last<len)count++;
return count;
}
/* *
* cast a int into a char
* @param i int to cast
* @return int as char
* /
private char c(int i) {
return (char)i;
}*/
/**
* gets a value from list
* @param list list to cast
* @param delimeter delimter of the list
* @param position
* @return Array Object
*/
public static String getAt(String list, String delimeter, int position, boolean ignoreEmpty) {
if(delimeter.length()==1)return getAt(list, delimeter.charAt(0), position,ignoreEmpty);
int len=list.length();
if(len==0) return null;
int last=0;
int count=0;
char[] del = delimeter.toCharArray();
char c;
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
if(!ignoreEmpty || last<i) {
if(count++==position) {
return list.substring(last,i);
}
}
last=i+1;
}
}
}
if(last<len && position==count) return (list.substring(last));
return null;
}
/**
* get a elemnt at a specified position in list
* @param list list to cast
* @param delimeter delimter of the list
* @param position
* @return Array Object
*/
public static String getAt(String list, char delimeter, int position, boolean ignoreEmpty) {
int len=list.length();
if(len==0) return null;
int last=0;
int count=0;
for(int i=0;i<len;i++) {
if(list.charAt(i)==delimeter) {
if(!ignoreEmpty || last<i) {
if(count++==position) {
return list.substring(last,i);
}
}
last=i+1;
}
}
if(last<len && position==count) return (list.substring(last));
return null;
}
public static String[] listToStringArray(String list, char delimeter) {
Array array = List.listToArrayRemoveEmpty(list,delimeter);
String[] arr=new String[array.size()];
for(int i=0;i<arr.length;i++) {
arr[i]=Caster.toString(array.get(i+1,""),"");
}
return arr;
}
/**
* trim every single item of the array
* @param arr
* @return
*/
public static String[] trimItems(String[] arr) {
for(int i=0;i<arr.length;i++) {
arr[i]=arr[i].trim();
}
return arr;
}
/**
* trim every single item of the array
* @param arr
* @return
* @throws PageException
*/
public static Array trimItems(Array arr) throws PageException {
Key[] keys = arr.keys();
for(int i=0;i<keys.length;i++) {
arr.setEL(keys[i], Caster.toString(arr.get(keys[i],null)).trim());
}
return arr;
}
public static Set<String> listToSet(String list, String delimeter,boolean trim) {
if(list.length()==0) return new HashSet<String>();
int len=list.length();
int last=0;
char[] del=delimeter.toCharArray();
char c;
HashSet<String> set=new HashSet<String>();
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
set.add(trim?list.substring(last,i).trim():list.substring(last,i));
last=i+1;
}
}
}
if(last<=len)set.add(list.substring(last));
return set;
}
public static Set<String> listToSet(String list, char delimeter,boolean trim) {
if(list.length()==0) return new HashSet<String>();
int len=list.length();
int last=0;
char c;
HashSet<String> set=new HashSet<String>();
for(int i=0;i<len;i++) {
c=list.charAt(i);
if(c==delimeter) {
set.add(trim?list.substring(last,i).trim():list.substring(last,i));
last=i+1;
}
}
if(last<=len)set.add(list.substring(last));
return set;
}
public static Set<String> toSet(String[] arr) {
Set<String> set=new HashSet<String>();
for(int i=0;i<arr.length;i++){
set.add(arr[i]);
}
return set;
}
} | solved ticket https://issues.jboss.org/browse/RAILO-1862
| railo-java/railo-core/src/railo/runtime/type/List.java | solved ticket https://issues.jboss.org/browse/RAILO-1862 |
|
Java | apache-2.0 | 5dc836bb47b5014e5237df35d86b26c216baa053 | 0 | FlatBallFlyer/IBM-Data-Merge-Utility,FlatBallFlyer/IBM-Data-Merge-Utility,FlatBallFlyer/IBM-Data-Merge-Utility | /*
* Copyright 2015 IBM
*
* 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.tk;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Merge
*/
@WebServlet("/Merge")
public class Merge extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public Merge() {
// TODO Auto-generated constructor stub
}
/**
* @throws IOException
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
merge(req, res);
}
/**
* @throws IOException
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
merge(req, res);
}
/**
* @throws IOException - getWriter failed
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void merge(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Initialize initial replace hash map
HashMap<String,String> replace = new HashMap<String,String>();
replace.put("{collection}", "root");
replace.put("{column}","");
replace.put("{name}", "default");
// Testing Values for test template
// replace.put("{collection}", "test");
// replace.put("{name}", "testRoot");
// Iterate parameters, setting replace values or loging levels
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String paramName = parameterNames.nextElement();
String paramValue = request.getParameterValues(paramName)[0];
if ("CacheReset".equals(paramName) && "Yes".equals(paramValue) ) {
TemplateFactory.reset();
} else {
replace.put("{" + paramName + "}", paramValue);
}
}
// Do the Merge and Handle all Exceptions
try {
// Get a template from the factory
Template root = TemplateFactory.getTemplate(replace.get("{collection}"), replace.get("{column}"), replace.get("{name}"));
// Add replace values from the parameter list
root.getReplaceValues().putAll(replace);
// Perform the merge and write output
out.write(root.merge());
} catch (tkException e) {
out.write("MERGE FAILED! tkException " + e.getErrorCode() + "\n");
out.write(e.getMessage() + "\n");
e.printStackTrace(out);
} catch (tkSqlException e) {
out.write("MERGE FAILED! SQLException" + e.getErrorCode() + "\n");
out.write(" - QueryString:" + e.getQueryString() + "\n");
out.write(" - SQL Error:" + e.getSqlError() + "\n");
out.write(e.getMessage() + "\n");
e.printStackTrace(out);
} catch (IOException e) {
out.write("MERGE FAILED! IOException" + "\n");
out.write(e.getMessage());
e.printStackTrace(out);
}
}
} | src/com/ibm/tk/Merge.java | /*
* Copyright 2015 IBM
*
* 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.tk;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Merge
*/
@WebServlet("/Merge")
public class Merge extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public Merge() {
// TODO Auto-generated constructor stub
}
/**
* @throws IOException
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
merge(req, res);
}
/**
* @throws IOException
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
merge(req, res);
}
/**
* @throws IOException - getWriter failed
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void merge(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Initialize initial replace hash map
HashMap<String,String> replace = new HashMap<String,String>();
replace.put("{collection}", "root");
replace.put("{column}","");
replace.put("{name}", "default");
// Testing Values for test template
//replace.put("{collection}", "test");
//replace.put("{name}", "testRoot");
// Iterate parameters, setting replace values or loging levels
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String paramName = parameterNames.nextElement();
String paramValue = request.getParameterValues(paramName)[0];
if ("CacheReset".equals(paramName) && "Yes".equals(paramValue) ) {
TemplateFactory.reset();
} else {
replace.put("{" + paramName + "}", paramValue);
}
}
// Do the Merge and Handle all Exceptions
try {
// Get a template from the factory
Template root = TemplateFactory.getTemplate(replace.get("{collection}"), replace.get("{column}"), replace.get("{name}"));
// Add replace values from the parameter list
root.getReplaceValues().putAll(replace);
// Perform the merge and write output
out.write(root.merge());
} catch (tkException e) {
out.write("MERGE FAILED! tkException " + e.getErrorCode() + "\n");
out.write(e.getMessage() + "\n");
e.printStackTrace(out);
} catch (tkSqlException e) {
out.write("MERGE FAILED! SQLException" + e.getErrorCode() + "\n");
out.write(" - QueryString:" + e.getQueryString() + "\n");
out.write(" - SQL Error:" + e.getSqlError() + "\n");
out.write(e.getMessage() + "\n");
e.printStackTrace(out);
} catch (IOException e) {
out.write("MERGE FAILED! IOException" + "\n");
out.write(e.getMessage());
e.printStackTrace(out);
}
}
} | Version 1.4 Sync
| src/com/ibm/tk/Merge.java | Version 1.4 Sync |
|
Java | apache-2.0 | cb621638e1a273653a1311da1a8ffdb934f7b502 | 0 | mikesprague/urlbuilder,mikaelhg/urlbuilder | /*
Copyright 2014 Mikael Gueck
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 gumi.builders.url;
import static gumi.builders.url.UrlParameterMultimap.*;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.StringTokenizer;
/**
* Percent-decoding according to the URI and URL standards.
*/
public class Decoder {
protected static final boolean DECODE_PLUS_AS_SPACE = true;
protected static final boolean DO_NOT_DECODE_PLUS_AS_SPACE = false;
protected final Charset inputEncoding;
public Decoder(final Charset inputEncoding) {
this.inputEncoding = inputEncoding;
}
public String decodeUserInfo(final String userInfo) {
if (null == userInfo || userInfo.isEmpty()) {
return userInfo;
} else {
return urlDecode(userInfo, DECODE_PLUS_AS_SPACE);
}
}
public String decodeFragment(final String fragment) {
if (fragment == null || fragment.isEmpty()) {
return fragment;
}
return urlDecode(fragment, DO_NOT_DECODE_PLUS_AS_SPACE);
}
public UrlParameterMultimap parseQueryString(final String query) {
final UrlParameterMultimap ret = newMultimap();
if (query == null || query.isEmpty()) {
return ret;
}
for (final String part : query.split("&")) {
final String[] kvp = part.split("=", 2);
final String key, value;
key = urlDecode(kvp[0], DECODE_PLUS_AS_SPACE);
if (kvp.length == 2) {
value = urlDecode(kvp[1], DECODE_PLUS_AS_SPACE);
} else {
value = null;
}
ret.add(key, value);
}
return ret;
}
protected byte[] nextDecodeableSequence(final String input, final int position) {
final int len = input.length();
final byte[] data = new byte[len];
int j = 0;
for (int i = position; i < len; i++) {
final char c0 = input.charAt(i);
if (c0 != '%' || (len < i + 3)) {
return Arrays.copyOfRange(data, 0, j);
} else {
data[j++] = (byte) Integer.parseInt(input.substring(i + 1, i + 3), 16);
i += 2;
}
}
return Arrays.copyOfRange(data, 0, j);
}
public String decodePath(final String input) {
if (input == null || input.isEmpty()) {
return "";
}
final StringBuilder sb = new StringBuilder();
final boolean RETURN_DELIMETERS = true;
final StringTokenizer st = new StringTokenizer(input, "/", RETURN_DELIMETERS);
while (st.hasMoreElements()) {
final String element = st.nextToken();
if ("/".equals(element)) {
sb.append(element);
} else if (!element.isEmpty()) {
sb.append(urlDecode(element, DO_NOT_DECODE_PLUS_AS_SPACE));
}
}
return sb.toString();
}
protected String urlDecode(final String input, final boolean decodePlusAsSpace) {
final StringBuilder sb = new StringBuilder();
final int len = input.length();
for (int i = 0; i < len; i++) {
final char c0 = input.charAt(i);
if (c0 == '+' && decodePlusAsSpace) {
sb.append(' ');
} else if (c0 != '%') {
sb.append(c0);
} else if (len < i + 3) {
// the string will end before we will be able to read a sequence
int endIndex = Math.min(input.length(), i+2);
sb.append(input.substring(i, endIndex));
i += 3;
} else {
final byte[] bytes = nextDecodeableSequence(input, i);
sb.append(inputEncoding.decode(ByteBuffer.wrap(bytes)));
i += bytes.length * 3 - 1;
}
}
return sb.toString();
}
}
| src/main/java/gumi/builders/url/Decoder.java | /*
Copyright 2014 Mikael Gueck
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 gumi.builders.url;
import static gumi.builders.url.UrlParameterMultimap.*;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.StringTokenizer;
/**
* Percent-decoding according to the URI and URL standards.
*/
public class Decoder {
protected static final boolean DECODE_PLUS_AS_SPACE = true;
protected static final boolean DO_NOT_DECODE_PLUS_AS_SPACE = false;
protected final Charset inputEncoding;
public Decoder(final Charset inputEncoding) {
this.inputEncoding = inputEncoding;
}
public String decodeUserInfo(final String userInfo) {
if (null == userInfo || userInfo.isEmpty()) {
return userInfo;
} else {
return urlDecode(userInfo, DECODE_PLUS_AS_SPACE);
}
}
public String decodeFragment(final String fragment) {
if (fragment == null || fragment.isEmpty()) {
return fragment;
}
return urlDecode(fragment, DO_NOT_DECODE_PLUS_AS_SPACE);
}
public UrlParameterMultimap parseQueryString(final String query) {
final UrlParameterMultimap ret = newMultimap();
if (query == null || query.isEmpty()) {
return ret;
}
for (final String part : query.split("&")) {
final String[] kvp = part.split("=", 2);
final String key, value;
key = urlDecode(kvp[0], DECODE_PLUS_AS_SPACE);
if (kvp.length == 2) {
value = urlDecode(kvp[1], DECODE_PLUS_AS_SPACE);
} else {
value = null;
}
ret.add(key, value);
}
return ret;
}
protected byte[] nextDecodeableSequence(final String input, final int position) {
final int len = input.length();
final byte[] data = new byte[len];
int j = 0;
for (int i = position; i < len; i++) {
final char c0 = input.charAt(i);
if (c0 != '%' || (len < i + 2)) {
return Arrays.copyOfRange(data, 0, j);
} else {
data[j++] = (byte) Integer.parseInt(input.substring(i + 1, i + 3), 16);
i += 2;
}
}
return Arrays.copyOfRange(data, 0, j);
}
public String decodePath(final String input) {
if (input == null || input.isEmpty()) {
return "";
}
final StringBuilder sb = new StringBuilder();
final boolean RETURN_DELIMETERS = true;
final StringTokenizer st = new StringTokenizer(input, "/", RETURN_DELIMETERS);
while (st.hasMoreElements()) {
final String element = st.nextToken();
if ("/".equals(element)) {
sb.append(element);
} else if (!element.isEmpty()) {
sb.append(urlDecode(element, DO_NOT_DECODE_PLUS_AS_SPACE));
}
}
return sb.toString();
}
protected String urlDecode(final String input, final boolean decodePlusAsSpace) {
final StringBuilder sb = new StringBuilder();
final int len = input.length();
for (int i = 0; i < len; i++) {
final char c0 = input.charAt(i);
if (c0 == '+' && decodePlusAsSpace) {
sb.append(' ');
} else if (c0 != '%') {
sb.append(c0);
} else if (len < i + 2) {
// the string will end before we will be able to read a sequence
i += 2;
} else {
final byte[] bytes = nextDecodeableSequence(input, i);
sb.append(inputEncoding.decode(ByteBuffer.wrap(bytes)));
i += bytes.length * 3 - 1;
}
}
return sb.toString();
}
}
| Fix to prevent exceptions when dealing with URLs that end in broken percent encodings
| src/main/java/gumi/builders/url/Decoder.java | Fix to prevent exceptions when dealing with URLs that end in broken percent encodings |
|
Java | apache-2.0 | aef266bd6534368a0322195b89d81c1924b9f179 | 0 | httl/httl,sdgdsffdsfff/httl,fengshao0907/httl,xiangyong/httl | /*
* Copyright 2011-2013 HTTL Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package httl.web.springmvc;
import httl.web.WebEngine;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.servlet.view.AbstractTemplateViewResolver;
/**
* HttlViewResolver. (Integration, Singleton, ThreadSafe)
*
* @author Liang Fei (liangfei0201 AT gmail DOT com)
*/
public class HttlViewResolver extends AbstractTemplateViewResolver implements InitializingBean {
public HttlViewResolver() {
setViewClass(requiredViewClass());
}
@Override
protected Class<?> requiredViewClass() {
return HttlView.class;
}
public void afterPropertiesSet() throws Exception {
WebEngine.setServletContext(getServletContext());
if (getSuffix() == null || getSuffix().length() == 0) {
super.setSuffix(WebEngine.getTemplateSuffix());
}
}
} | httl-springmvc/src/main/java/httl/web/springmvc/HttlViewResolver.java | /*
* Copyright 2011-2013 HTTL Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package httl.web.springmvc;
import httl.web.WebEngine;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.servlet.view.AbstractTemplateViewResolver;
/**
* HttlViewResolver. (Integration, Singleton, ThreadSafe)
*
* @author Liang Fei (liangfei0201 AT gmail DOT com)
*/
public class HttlViewResolver extends AbstractTemplateViewResolver implements InitializingBean {
public HttlViewResolver() {
setViewClass(requiredViewClass());
}
@Override
protected Class<?> requiredViewClass() {
return HttlView.class;
}
public void afterPropertiesSet() throws Exception {
WebEngine.setServletContext(getServletContext());
if (super.getSuffix() == null || super.getSuffix().length() == 0) {
super.setSuffix(WebEngine.getTemplateSuffix());
}
}
} | 修改Adaptive
| httl-springmvc/src/main/java/httl/web/springmvc/HttlViewResolver.java | 修改Adaptive |
|
Java | apache-2.0 | 0ca678939bcaa4b2d2885b5dc6ea3604e744b754 | 0 | Tycheo/coffeemud,oriontribunal/CoffeeMud,Tycheo/coffeemud,MaxRau/CoffeeMud,Tycheo/coffeemud,sfunk1x/CoffeeMud,MaxRau/CoffeeMud,bozimmerman/CoffeeMud,MaxRau/CoffeeMud,bozimmerman/CoffeeMud,oriontribunal/CoffeeMud,sfunk1x/CoffeeMud,sfunk1x/CoffeeMud,oriontribunal/CoffeeMud,MaxRau/CoffeeMud,sfunk1x/CoffeeMud,Tycheo/coffeemud,oriontribunal/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud | package com.planet_ink.coffee_mud.Libraries;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2000-2009 Bo Zimmerman
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.
*/
@SuppressWarnings("unchecked")
public class TimsLibrary extends StdLibrary implements ItemBalanceLibrary
{
public String ID(){return "TimsLibrary";}
public int timsLevelCalculator(Item I)
{
int[] castMul=new int[1];
Ability[] RET=getTimsAdjResCast(I,castMul);
Ability ADJ=RET[0];
Ability RES=RET[1];
Ability CAST=RET[2];
return timsLevelCalculator(I,ADJ,RES,CAST,castMul[0]);
}
public int timsLevelCalculator(Item I, Ability ADJ, Ability RES, Ability CAST, int castMul)
{
int level=0;
Item savedI=(Item)I.copyOf();
savedI.recoverEnvStats();
I=(Item)I.copyOf();
I.recoverEnvStats();
int otherDam=0;
int otherAtt=0;
int otherArm=0;
if(ADJ!=null)
{
otherArm=CMParms.getParmPlus(ADJ.text(),"arm")*-1;
otherAtt=CMParms.getParmPlus(ADJ.text(),"att");
otherDam=CMParms.getParmPlus(ADJ.text(),"dam");
}
int curArmor=savedI.baseEnvStats().armor()+otherArm;
double curAttack=(double)(savedI.baseEnvStats().attackAdjustment()+otherAtt);
double curDamage=(double)(savedI.baseEnvStats().damage()+otherDam);
if(I instanceof Weapon)
{
double weight=(double)I.baseEnvStats().weight();
if(weight<1.0) weight=1.0;
double range=(double)savedI.maxRange();
level=(int)Math.round(Math.floor((2.0*curDamage/(2.0*(I.rawLogicalAnd()?2.0:1.0)+1.0)+(curAttack-weight)/5.0+range)*(range/weight+2.0)))+1;
}
else
{
long worndata=savedI.rawProperLocationBitmap();
double weightpts=0;
for(int i=0;i<Item.WORN_WEIGHTS.length-1;i++)
{
if(CMath.isSet(worndata,i))
{
weightpts+=Item.WORN_WEIGHTS[i+1];
if(!I.rawLogicalAnd()) break;
}
}
int[] leatherPoints={ 0, 0, 1, 5,10,16,23,31,40,49,58,67,76,85,94};
int[] clothPoints= { 0, 3, 7,12,18,25,33,42,52,62,72,82,92,102};
int[] metalPoints= { 0, 0, 0, 0, 1, 3, 5, 8,12,17,23,30,38,46,54,62,70,78,86,94};
int materialCode=savedI.material()&RawMaterial.MATERIAL_MASK;
int[] useArray=null;
switch(materialCode)
{
case RawMaterial.MATERIAL_METAL:
case RawMaterial.MATERIAL_MITHRIL:
case RawMaterial.MATERIAL_PRECIOUS:
case RawMaterial.MATERIAL_ENERGY:
useArray=metalPoints;
break;
case RawMaterial.MATERIAL_PLASTIC:
case RawMaterial.MATERIAL_LEATHER:
case RawMaterial.MATERIAL_GLASS:
case RawMaterial.MATERIAL_ROCK:
case RawMaterial.MATERIAL_WOODEN:
useArray=leatherPoints;
break;
default:
useArray=clothPoints;
break;
}
int which=(int)Math.round(CMath.div(curArmor,weightpts)+1);
if(which<0) which=0;
if(which>=useArray.length)
which=useArray.length-1;
level=useArray[which];
}
level+=I.baseEnvStats().ability()*5;
if(CAST!=null)
{
String ID=CAST.ID().toUpperCase();
Vector theSpells=new Vector();
String names=CAST.text();
int del=names.indexOf(";");
while(del>=0)
{
String thisOne=names.substring(0,del);
Ability A=CMClass.getAbility(thisOne);
if(A!=null) theSpells.addElement(A);
names=names.substring(del+1);
del=names.indexOf(";");
}
Ability A=CMClass.getAbility(names);
if(A!=null) theSpells.addElement(A);
for(int v=0;v<theSpells.size();v++)
{
A=(Ability)theSpells.elementAt(v);
int mul=1;
if(A.abstractQuality()==Ability.QUALITY_MALICIOUS) mul=-1;
if(ID.indexOf("HAVE")>=0)
level+=(mul*CMLib.ableMapper().lowestQualifyingLevel(A.ID()));
else
level+=(mul*CMLib.ableMapper().lowestQualifyingLevel(A.ID())/2);
}
}
if(ADJ!=null)
{
String newText=ADJ.text();
int ab=CMParms.getParmPlus(newText,"abi");
int arm=CMParms.getParmPlus(newText,"arm")*-1;
int att=CMParms.getParmPlus(newText,"att");
int dam=CMParms.getParmPlus(newText,"dam");
if(savedI instanceof Weapon)
level+=(arm*2);
else
if(savedI instanceof Armor)
{
level+=(att/2);
level+=(dam*3);
}
level+=ab*5;
int dis=CMParms.getParmPlus(newText,"dis");
if(dis!=0) level+=5;
int sen=CMParms.getParmPlus(newText,"sen");
if(sen!=0) level+=5;
level+=(int)Math.round(5.0*CMParms.getParmDoublePlus(newText,"spe"));
for(int i=0;i<CharStats.NUM_BASE_STATS;i++)
{
int stat=CMParms.getParmPlus(newText,CharStats.STAT_DESCS[i].substring(0,3).toLowerCase());
int max=CMParms.getParmPlus(newText,("max"+(CharStats.STAT_DESCS[i].substring(0,3).toLowerCase())));
level+=(stat*5);
level+=(max*5);
}
int hit=CMParms.getParmPlus(newText,"hit");
int man=CMParms.getParmPlus(newText,"man");
int mv=CMParms.getParmPlus(newText,"mov");
level+=(hit/5);
level+=(man/5);
level+=(mv/5);
}
return level;
}
public boolean fixRejuvItem(Item I)
{
Ability A=I.fetchEffect("ItemRejuv");
if(A!=null)
{
A=I.fetchEffect("ItemRejuv");
if(A.savable())
return false;
A.setSavable(false);
return true;
}
return false;
}
public Ability[] getTimsAdjResCast(Item I, int[] castMul)
{
Ability ADJ=I.fetchEffect("Prop_WearAdjuster");
if(ADJ==null) ADJ=I.fetchEffect("Prop_HaveAdjuster");
if(ADJ==null) ADJ=I.fetchEffect("Prop_RideAdjuster");
Ability RES=I.fetchEffect("Prop_WearResister");
if(RES==null) RES=I.fetchEffect("Prop_HaveResister");
Ability CAST=I.fetchEffect("Prop_WearSpellCast");
castMul[0]=1;
if(CAST==null) CAST=I.fetchEffect("Prop_UseSpellCast");
if(CAST==null) CAST=I.fetchEffect("Prop_UseSpellCast2");
if(CAST==null) CAST=I.fetchEffect("Prop_HaveSpellCast");
if(CAST==null){ CAST=I.fetchEffect("Prop_FightSpellCast"); castMul[0]=-1;}
Ability[] RET=new Ability[3];
RET[0]=ADJ;
RET[1]=RES;
RET[2]=CAST;
return RET;
}
public boolean itemFix(Item I, int lvlOr0)
{
if((I instanceof SpellHolder)
||((I instanceof Wand)&&(lvlOr0<=0)))
{
Vector spells=new Vector();
if(I instanceof SpellHolder)
spells=((SpellHolder)I).getSpells();
else
if(I instanceof Wand)
spells.add(((Wand)I).getSpell());
if(spells.size()==0) return false;
int levels=0;
for(Enumeration<Ability> e=spells.elements();e.hasMoreElements();)
levels+=CMLib.ableMapper().lowestQualifyingLevel(e.nextElement().ID());
int level=(int)Math.round(CMath.div(levels, spells.size()));
if(level==I.baseEnvStats().level()) return false;
I.baseEnvStats().setLevel(level);
I.envStats().setLevel(level);
if(CMLib.flags().isCataloged(I))
CMLib.catalog().updateCatalog(I);
return true;
}
else
if((I instanceof Weapon)||(I instanceof Armor))
{
int lvl=lvlOr0;
if(lvl <=0) lvl=I.baseEnvStats().level();
I.baseEnvStats().setLevel(lvl);
I.envStats().setLevel(lvl);
Ability[] RET=getTimsAdjResCast(I,new int[1]);
Ability ADJ=RET[0];
Ability RES=RET[1];
Ability CAST=RET[2];
int[] LVLS=getItemLevels(I,ADJ,RES,CAST);
int TLVL=totalLevels(LVLS);
if(lvl<0)
{
if(TLVL<=0)
lvl=1;
else
lvl=TLVL;
I.baseEnvStats().setLevel(lvl);
I.recoverEnvStats();
fixRejuvItem(I);
if(CMLib.flags().isCataloged(I))
CMLib.catalog().updateCatalog(I);
return true;
}
if((TLVL>0)&&(TLVL>(lvl+2)))
{
int FTLVL=TLVL;
Vector illegalNums=new Vector();
Log.sysOut("Reset",I.name()+"("+I.baseEnvStats().level()+") "+TLVL+", "+I.baseEnvStats().armor()+"/"+I.baseEnvStats().attackAdjustment()+"/"+I.baseEnvStats().damage()+"/"+((ADJ!=null)?ADJ.text():"null"));
while((TLVL>(lvl+2))&&(illegalNums.size()<4))
{
int highIndex=-1;
for(int i=0;i<LVLS.length;i++)
if(((highIndex<0)||(LVLS[i]>LVLS[highIndex]))
&&(!illegalNums.contains(new Integer(i))))
highIndex=i;
if(highIndex<0) break;
I.envStats().setWeight(I.envStats().weight()+2);
switch(highIndex)
{
case 0:
if(I instanceof Weapon)
{
String s=(ADJ!=null)?ADJ.text():"";
int oldAtt=I.baseEnvStats().attackAdjustment();
int oldDam=I.baseEnvStats().damage();
I.baseEnvStats().setWeight(I.baseEnvStats().weight()+10);
toneDownWeapon((Weapon)I,ADJ);
if((I.baseEnvStats().attackAdjustment()==oldAtt)
&&(I.baseEnvStats().damage()==oldDam)
&&((ADJ==null)||(ADJ.text().equals(s))))
illegalNums.addElement(new Integer(0));
}
else
{
String s=(ADJ!=null)?ADJ.text():"";
int oldArm=I.baseEnvStats().armor();
toneDownArmor((Armor)I,ADJ);
if((I.baseEnvStats().armor()==oldArm)
&&((ADJ==null)||(ADJ.text().equals(s))))
illegalNums.addElement(new Integer(0));
}
break;
case 1:
if(I.baseEnvStats().ability()>0)
I.baseEnvStats().setAbility(I.baseEnvStats().ability()-1);
else
illegalNums.addElement(new Integer(1));
break;
case 2:
illegalNums.addElement(new Integer(2));
// nothing I can do!;
break;
case 3:
if(ADJ==null)
illegalNums.addElement(new Integer(3));
else
{
String oldTxt=ADJ.text();
toneDownAdjuster(I,ADJ);
if(ADJ.text().equals(oldTxt))
illegalNums.addElement(new Integer(3));
}
break;
}
LVLS=getItemLevels(I,ADJ,RES,CAST);
TLVL=totalLevels(LVLS);
}
Log.sysOut("Reset",I.name()+"("+I.baseEnvStats().level()+") "+FTLVL+"->"+TLVL+", "+I.baseEnvStats().armor()+"/"+I.baseEnvStats().attackAdjustment()+"/"+I.baseEnvStats().damage()+"/"+((ADJ!=null)?ADJ.text():"null"));
fixRejuvItem(I);
if(CMLib.flags().isCataloged(I))
CMLib.catalog().updateCatalog(I);
return true;
}
}
if(fixRejuvItem(I))
{
if(CMLib.flags().isCataloged(I))
CMLib.catalog().updateCatalog(I);
return true;
}
return false;
}
public boolean toneDownValue(Item I)
{
int hands=0;
int weaponClass=0;
if(I instanceof Coins) return false;
if(I instanceof Weapon)
{
hands=I.rawLogicalAnd()?2:1;
weaponClass=((Weapon)I).weaponClassification();
}
else
if(!(I instanceof Armor))
return false;
Hashtable H=timsItemAdjustments(I,I.envStats().level(),I.material(),
I.baseEnvStats().weight(),hands,weaponClass,I.maxRange(),I.rawProperLocationBitmap());
int newValue=CMath.s_int((String)H.get("VALUE"));
if((I.baseGoldValue()>newValue)&&(newValue>0))
{
I.setBaseValue(newValue);
return true;
}
return false;
}
public void balanceItemByLevel(Item I)
{
int hands=0;
int weaponClass=0;
if(I instanceof Weapon)
{
hands=I.rawLogicalAnd()?2:1;
weaponClass=((Weapon)I).weaponClassification();
}
Hashtable H=timsItemAdjustments(I,I.envStats().level(),I.material(),
I.baseEnvStats().weight(),hands,weaponClass,I.maxRange(),I.rawProperLocationBitmap());
if(I instanceof Weapon)
{
I.baseEnvStats().setDamage(CMath.s_int((String)H.get("DAMAGE")));
I.baseEnvStats().setAttackAdjustment(CMath.s_int((String)H.get("ATTACK")));
I.setBaseValue(CMath.s_int((String)H.get("VALUE")));
I.recoverEnvStats();
}
else
if(I instanceof Armor)
{
I.baseEnvStats().setArmor(CMath.s_int((String)H.get("ARMOR")));
I.setBaseValue(CMath.s_int((String)H.get("VALUE")));
I.baseEnvStats().setWeight(CMath.s_int((String)H.get("WEIGHT")));
I.recoverEnvStats();
}
}
public Hashtable timsItemAdjustments(Item I,
int level,
int material,
int weight,
int hands,
int wclass,
int reach,
long worndata)
{
Hashtable vals=new Hashtable();
int materialvalue=RawMaterial.RESOURCE_DATA[material&RawMaterial.RESOURCE_MASK][1];
int[] castMul=new int[1];
Ability[] RET=getTimsAdjResCast(I,castMul);
Ability ADJ=RET[0];
Ability CAST=RET[2];
level-=levelsFromAbility(I);
level-=levelsFromAdjuster(I,ADJ);
level-=levelsFromCaster(I,CAST);
if(I instanceof Weapon)
{
int baseattack=0;
int basereach=0;
int maxreach=0;
int basematerial=RawMaterial.MATERIAL_WOODEN;
if(wclass==Weapon.CLASS_FLAILED) baseattack=-5;
if(wclass==Weapon.CLASS_POLEARM){ basereach=1; basematerial=RawMaterial.MATERIAL_METAL;}
if(wclass==Weapon.CLASS_RANGED){ basereach=1; maxreach=5;}
if(wclass==Weapon.CLASS_THROWN){ basereach=1; maxreach=5;}
if(wclass==Weapon.CLASS_EDGED){ baseattack=10; basematerial=RawMaterial.MATERIAL_METAL;}
if(wclass==Weapon.CLASS_DAGGER){ baseattack=10; basematerial=RawMaterial.MATERIAL_METAL;}
if(wclass==Weapon.CLASS_SWORD){ basematerial=RawMaterial.MATERIAL_METAL;}
if(weight==0) weight=10;
if(basereach>maxreach) maxreach=basereach;
if(reach<basereach)
{
reach=basereach;
vals.put("MINRANGE",""+basereach);
vals.put("MAXRANGE",""+maxreach);
}
else
if(reach>basereach)
basereach=reach;
int damage=((level-1)/((reach/weight)+2) + (weight-baseattack)/5 -reach)*(((hands*2)+1)/2);
int cost=2*((weight*materialvalue)+((2*damage)+baseattack+(reach*10))*damage)/(hands+1);
if(basematerial==RawMaterial.MATERIAL_METAL)
{
switch(material&RawMaterial.MATERIAL_MASK)
{
case RawMaterial.MATERIAL_MITHRIL:
case RawMaterial.MATERIAL_METAL:
case RawMaterial.MATERIAL_ENERGY:
break;
case RawMaterial.MATERIAL_WOODEN:
case RawMaterial.MATERIAL_PLASTIC:
damage-=4;
baseattack-=0;
break;
case RawMaterial.MATERIAL_PRECIOUS:
damage-=4;
baseattack-=10;
break;
case RawMaterial.MATERIAL_LEATHER:
damage-=6;
baseattack-=10;
break;
case RawMaterial.MATERIAL_ROCK:
damage-=2;
baseattack-=10;
break;
case RawMaterial.MATERIAL_GLASS:
damage-=4;
baseattack-=20;
break;
default:
damage-=8;
baseattack-=30;
break;
}
switch(material)
{
case RawMaterial.RESOURCE_BALSA:
case RawMaterial.RESOURCE_LIMESTONE:
case RawMaterial.RESOURCE_FLINT:
baseattack-=10;
damage-=2;
break;
case RawMaterial.RESOURCE_CLAY:
baseattack-=20;
damage-=4;
break;
case RawMaterial.RESOURCE_BONE:
baseattack+=20;
damage+=4;
break;
case RawMaterial.RESOURCE_GRANITE:
case RawMaterial.RESOURCE_OBSIDIAN:
case RawMaterial.RESOURCE_IRONWOOD:
baseattack+=10;
damage+=2;
break;
case RawMaterial.RESOURCE_SAND:
case RawMaterial.RESOURCE_COAL:
baseattack-=40;
damage-=8;
break;
}
}
if(basematerial==RawMaterial.MATERIAL_WOODEN)
{
switch(material&RawMaterial.MATERIAL_MASK)
{
case RawMaterial.MATERIAL_WOODEN:
case RawMaterial.MATERIAL_ENERGY:
break;
case RawMaterial.MATERIAL_METAL:
case RawMaterial.MATERIAL_MITHRIL:
damage+=2;
baseattack-=0;
break;
case RawMaterial.MATERIAL_PRECIOUS:
damage+=2;
baseattack-=10;
break;
case RawMaterial.MATERIAL_LEATHER:
case RawMaterial.MATERIAL_PLASTIC:
damage-=2;
baseattack-=0;
break;
case RawMaterial.MATERIAL_ROCK:
damage+=2;
baseattack-=10;
break;
case RawMaterial.MATERIAL_GLASS:
damage-=2;
baseattack-=10;
break;
default:
damage-=6;
baseattack-=30;
break;
}
switch(material)
{
case RawMaterial.RESOURCE_LIMESTONE:
case RawMaterial.RESOURCE_FLINT:
baseattack-=10;
damage-=2;
break;
case RawMaterial.RESOURCE_CLAY:
baseattack-=20;
damage-=4;
break;
case RawMaterial.RESOURCE_BONE:
baseattack+=20;
damage+=4;
break;
case RawMaterial.RESOURCE_GRANITE:
case RawMaterial.RESOURCE_OBSIDIAN:
baseattack+=10;
damage+=2;
break;
case RawMaterial.RESOURCE_SAND:
case RawMaterial.RESOURCE_COAL:
baseattack-=40;
damage-=8;
break;
}
}
if(damage<=0) damage=1;
vals.put("DAMAGE",""+damage);
vals.put("ATTACK",""+baseattack);
vals.put("VALUE",""+cost);
}
else
if(I instanceof Armor)
{
int[] leatherPoints={ 0, 0, 1, 5,10,16,23,31,40,49,58,67,76,85,94};
int[] clothPoints= { 0, 3, 7,12,18,25,33,42,52,62,72,82,92,102};
int[] metalPoints= { 0, 0, 0, 0, 1, 3, 5, 8,12,17,23,30,38,46,54,62,70,78,86,94};
double pts=0.0;
if(level<0) level=0;
int materialCode=material&RawMaterial.MATERIAL_MASK;
int[] useArray=null;
switch(materialCode)
{
case RawMaterial.MATERIAL_METAL:
case RawMaterial.MATERIAL_MITHRIL:
case RawMaterial.MATERIAL_PRECIOUS:
case RawMaterial.MATERIAL_ENERGY:
useArray=metalPoints;
break;
case RawMaterial.MATERIAL_PLASTIC:
case RawMaterial.MATERIAL_LEATHER:
case RawMaterial.MATERIAL_GLASS:
case RawMaterial.MATERIAL_ROCK:
case RawMaterial.MATERIAL_WOODEN:
useArray=leatherPoints;
break;
default:
useArray=clothPoints;
break;
}
if(level>=useArray[useArray.length-1])
pts=(double)(useArray.length-2);
else
for(int i=0;i<useArray.length;i++)
{
int lvl=useArray[i];
if(lvl>level)
{
pts=(double)(i-1);
break;
}
}
double totalpts=0.0;
double weightpts=0.0;
double wornweights=0.0;
for(int i=0;i<Item.WORN_WEIGHTS.length-1;i++)
{
if(CMath.isSet(worndata,i))
{
totalpts+=(pts*Item.WORN_WEIGHTS[i+1]);
wornweights+=Item.WORN_WEIGHTS[i+1];
switch(materialCode)
{
case RawMaterial.MATERIAL_METAL:
case RawMaterial.MATERIAL_MITHRIL:
case RawMaterial.MATERIAL_PRECIOUS:
weightpts+=Item.WORN_WEIGHT_POINTS[i+1][2];
break;
case RawMaterial.MATERIAL_LEATHER:
case RawMaterial.MATERIAL_GLASS:
case RawMaterial.MATERIAL_PLASTIC:
case RawMaterial.MATERIAL_ROCK:
case RawMaterial.MATERIAL_WOODEN:
weightpts+=Item.WORN_WEIGHT_POINTS[i+1][1];
break;
case RawMaterial.MATERIAL_ENERGY:
break;
default:
weightpts+=Item.WORN_WEIGHT_POINTS[i+1][0];
break;
}
if(hands==1) break;
}
}
int cost=(int)Math.round(((pts*pts) + (double)materialvalue)
* ( weightpts / 2));
int armor=(int)Math.round(totalpts);
switch(material)
{
case RawMaterial.RESOURCE_BALSA:
case RawMaterial.RESOURCE_LIMESTONE:
case RawMaterial.RESOURCE_FLINT:
armor-=1;
break;
case RawMaterial.RESOURCE_CLAY:
armor-=2;
break;
case RawMaterial.RESOURCE_BONE:
armor+=2;
break;
case RawMaterial.RESOURCE_GRANITE:
case RawMaterial.RESOURCE_OBSIDIAN:
case RawMaterial.RESOURCE_IRONWOOD:
armor+=1;
break;
case RawMaterial.RESOURCE_SAND:
case RawMaterial.RESOURCE_COAL:
armor-=4;
break;
}
vals.put("ARMOR",""+armor);
vals.put("VALUE",""+cost);
vals.put("WEIGHT",""+(int)Math.round(((double)armor)/wornweights*weightpts));
}
return vals;
}
public void toneDownWeapon(Weapon W, Ability ADJ)
{
boolean fixdam=true;
boolean fixatt=true;
if((ADJ!=null)&&(ADJ.text().toUpperCase().indexOf("DAMAGE+")>=0))
{
int a=ADJ.text().toUpperCase().indexOf("DAMAGE+");
int a2=ADJ.text().toUpperCase().indexOf(" ",a+4);
if(a2<0) a2=ADJ.text().length();
int num=CMath.s_int(ADJ.text().substring(a+7,a2));
if(num>W.baseEnvStats().damage())
{
fixdam=false;
ADJ.setMiscText(ADJ.text().substring(0,a+7)+(num/2)+ADJ.text().substring(a2));
}
}
if((ADJ!=null)&&(ADJ.text().toUpperCase().indexOf("ATTACK+")>=0))
{
int a=ADJ.text().toUpperCase().indexOf("ATTACK+");
int a2=ADJ.text().toUpperCase().indexOf(" ",a+4);
if(a2<0) a2=ADJ.text().length();
int num=CMath.s_int(ADJ.text().substring(a+7,a2));
if(num>W.baseEnvStats().attackAdjustment())
{
fixatt=false;
ADJ.setMiscText(ADJ.text().substring(0,a+7)+(num/2)+ADJ.text().substring(a2));
}
}
if(fixdam&&(W.baseEnvStats().damage()>=2))
W.baseEnvStats().setDamage(W.baseEnvStats().damage()/2);
if(fixatt&&(W.baseEnvStats().attackAdjustment()>=2))
W.baseEnvStats().setAttackAdjustment(W.baseEnvStats().attackAdjustment()/2);
W.recoverEnvStats();
}
public void toneDownArmor(Armor A, Ability ADJ)
{
boolean fixit=true;
if((ADJ!=null)&&(ADJ.text().toUpperCase().indexOf("ARMOR-")>=0))
{
int a=ADJ.text().toUpperCase().indexOf("ARMOR-");
int a2=ADJ.text().toUpperCase().indexOf(" ",a+4);
if(a2<0) a2=ADJ.text().length();
int num=CMath.s_int(ADJ.text().substring(a+6,a2));
if(num>A.baseEnvStats().armor())
{
fixit=false;
ADJ.setMiscText(ADJ.text().substring(0,a+6)+(num/2)+ADJ.text().substring(a2));
}
}
if(fixit&&(A.baseEnvStats().armor()>=2))
{
A.baseEnvStats().setArmor(A.baseEnvStats().armor()/2);
A.recoverEnvStats();
}
}
public void toneDownAdjuster(Item I, Ability ADJ)
{
String s=ADJ.text();
int plusminus=s.indexOf("+");
int minus=s.indexOf("-");
if((minus>=0)&&((plusminus<0)||(minus<plusminus)))
plusminus=minus;
while(plusminus>=0)
{
int spaceafter=s.indexOf(" ",plusminus+1);
if(spaceafter<0) spaceafter=s.length();
if(spaceafter>plusminus)
{
String number=s.substring(plusminus+1,spaceafter).trim();
if(CMath.isNumber(number))
{
int num=CMath.s_int(number);
int spacebefore=s.lastIndexOf(" ",plusminus);
if(spacebefore<0) spacebefore=0;
if(spacebefore<plusminus)
{
boolean proceed=true;
String wd=s.substring(spacebefore,plusminus).trim().toUpperCase();
if(wd.startsWith("DIS"))
proceed=false;
else
if(wd.startsWith("SEN"))
proceed=false;
else
if(wd.startsWith("ARM")&&(I instanceof Armor))
proceed=false;
else
if(wd.startsWith("ATT")&&(I instanceof Weapon))
proceed=false;
else
if(wd.startsWith("DAM")&&(I instanceof Weapon))
proceed=false;
else
if(wd.startsWith("ARM")&&(s.charAt(plusminus)=='+'))
proceed=false;
else
if((!wd.startsWith("ARM"))&&(s.charAt(plusminus)=='-'))
proceed=false;
if(proceed)
{
if((num!=1)&&(num!=-1))
s=s.substring(0,plusminus+1)+(num/2)+s.substring(spaceafter);
}
}
}
}
minus=s.indexOf("-",plusminus+1);
plusminus=s.indexOf("+",plusminus+1);
if((minus>=0)&&((plusminus<0)||(minus<plusminus)))
plusminus=minus;
}
ADJ.setMiscText(s);
}
public int[] getItemLevels(Item I, Ability ADJ, Ability RES, Ability CAST)
{
int[] LVLS=new int[4];
LVLS[0]=timsBaseLevel(I,ADJ);
LVLS[1]=levelsFromAbility(I);
LVLS[2]=levelsFromCaster(I,CAST);
LVLS[3]=levelsFromAdjuster(I,ADJ);
return LVLS;
}
public int totalLevels(int[] levels)
{
int lvl=levels[0];
for(int i=1;i<levels.length;i++)
lvl+=levels[i];
return lvl;
}
public int timsBaseLevel(Item I)
{
Ability[] RET=getTimsAdjResCast(I,new int[1]);
return timsBaseLevel(I,RET[0]);
}
public int timsBaseLevel(Item I, Ability ADJ)
{
int level=0;
int otherDam=0;
int otherAtt=0;
int otherArm=0;
if(ADJ!=null)
{
otherArm=CMParms.getParmPlus(ADJ.text(),"arm")*-1;
otherAtt=CMParms.getParmPlus(ADJ.text(),"att");
otherDam=CMParms.getParmPlus(ADJ.text(),"dam");
}
int curArmor=I.baseEnvStats().armor()+otherArm;
double curAttack=(double)(I.baseEnvStats().attackAdjustment()+otherAtt);
double curDamage=(double)(I.baseEnvStats().damage()+otherDam);
if(I instanceof Weapon)
{
double weight=(double)(I.baseEnvStats().weight());
if(weight<1.0) weight=1.0;
double range=(double)(I.maxRange());
level=(int)Math.round(Math.floor((2.0*curDamage/(2.0*(I.rawLogicalAnd()?2.0:1.0)+1.0)+(curAttack-weight)/5.0+range)*(range/weight+2.0)))+1;
}
else
{
long worndata=I.rawProperLocationBitmap();
double weightpts=0;
for(int i=0;i<Item.WORN_WEIGHTS.length-1;i++)
{
if(CMath.isSet(worndata,i))
{
weightpts+=Item.WORN_WEIGHTS[i+1];
if(!I.rawLogicalAnd()) break;
}
}
int[] leatherPoints={ 0, 0, 1, 5,10,16,23,31,40,49,58,67,76,85,94};
int[] clothPoints= { 0, 3, 7,12,18,25,33,42,52,62,72,82,92,102};
int[] metalPoints= { 0, 0, 0, 0, 1, 3, 5, 8,12,17,23,30,38,46,54,62,70,78,86,94};
int materialCode=I.material()&RawMaterial.MATERIAL_MASK;
int[] useArray=null;
switch(materialCode)
{
case RawMaterial.MATERIAL_METAL:
case RawMaterial.MATERIAL_MITHRIL:
case RawMaterial.MATERIAL_PRECIOUS:
case RawMaterial.MATERIAL_ENERGY:
useArray=metalPoints;
break;
case RawMaterial.MATERIAL_PLASTIC:
case RawMaterial.MATERIAL_LEATHER:
case RawMaterial.MATERIAL_GLASS:
case RawMaterial.MATERIAL_ROCK:
case RawMaterial.MATERIAL_WOODEN:
useArray=leatherPoints;
break;
default:
useArray=clothPoints;
break;
}
int which=(int)Math.round(CMath.div(curArmor,weightpts)+1);
if(which<0) which=0;
if(which>=useArray.length)
which=useArray.length-1;
level=useArray[which];
}
return level;
}
public int levelsFromAbility(Item savedI)
{ return savedI.baseEnvStats().ability()*5;}
public int levelsFromAdjuster(Item savedI, Ability ADJ)
{
int level=0;
if(ADJ!=null)
{
String newText=ADJ.text();
int ab=CMParms.getParmPlus(newText,"abi");
int arm=CMParms.getParmPlus(newText,"arm")*-1;
int att=CMParms.getParmPlus(newText,"att");
int dam=CMParms.getParmPlus(newText,"dam");
if(savedI instanceof Weapon)
level+=(arm*2);
else
if(savedI instanceof Armor)
{
level+=(att/2);
level+=(dam*3);
}
level+=ab*5;
int dis=CMParms.getParmPlus(newText,"dis");
if(dis!=0) level+=5;
int sen=CMParms.getParmPlus(newText,"sen");
if(sen!=0) level+=5;
level+=(int)Math.round(5.0*CMParms.getParmDoublePlus(newText,"spe"));
for(int i=0;i<CharStats.NUM_BASE_STATS;i++)
{
int stat=CMParms.getParmPlus(newText,CharStats.STAT_DESCS[i].substring(0,3).toLowerCase());
int max=CMParms.getParmPlus(newText,("max"+(CharStats.STAT_DESCS[i].substring(0,3).toLowerCase())));
level+=(stat*5);
level+=(max*5);
}
int hit=CMParms.getParmPlus(newText,"hit");
int man=CMParms.getParmPlus(newText,"man");
int mv=CMParms.getParmPlus(newText,"mov");
level+=(hit/5);
level+=(man/5);
level+=(mv/5);
}
return level;
}
public int levelsFromCaster(Item savedI, Ability CAST)
{
int level=0;
if(CAST!=null)
{
String ID=CAST.ID().toUpperCase();
Vector theSpells=new Vector();
String names=CAST.text();
int del=names.indexOf(";");
while(del>=0)
{
String thisOne=names.substring(0,del);
Ability A=CMClass.getAbility(thisOne);
if(A!=null) theSpells.addElement(A);
names=names.substring(del+1);
del=names.indexOf(";");
}
Ability A=CMClass.getAbility(names);
if(A!=null) theSpells.addElement(A);
for(int v=0;v<theSpells.size();v++)
{
A=(Ability)theSpells.elementAt(v);
int mul=1;
if(A.abstractQuality()==Ability.QUALITY_MALICIOUS) mul=-1;
if(ID.indexOf("HAVE")>=0)
level+=(mul*CMLib.ableMapper().lowestQualifyingLevel(A.ID()));
else
level+=(mul*CMLib.ableMapper().lowestQualifyingLevel(A.ID())/2);
}
}
return level;
}
public synchronized Vector getCombatSpellSet()
{
Vector spellSet=(Vector)Resources.getResource("COMPLETE_SPELL_SET");
if(spellSet==null)
{
spellSet=new Vector();
Ability A=null;
for(Enumeration e=CMClass.abilities();e.hasMoreElements();)
{
A=(Ability)e.nextElement();
if(((A.classificationCode()&(Ability.ALL_ACODES))==Ability.ACODE_SPELL))
{
int lowLevel=CMLib.ableMapper().lowestQualifyingLevel(A.ID());
if((lowLevel>0)&&(lowLevel<25))
spellSet.addElement(A);
}
}
Resources.submitResource("COMPLETE_SPELL_SET",spellSet);
}
return spellSet;
}
public Ability getCombatSpell(boolean malicious)
{
Vector spellSet=getCombatSpellSet();
int tries=0;
while(((++tries)<1000))
{
Ability A=(Ability)spellSet.elementAt(CMLib.dice().roll(1,spellSet.size(),-1));
if(((malicious)&&(A.canTarget(Ability.CAN_MOBS))&&(A.enchantQuality()==Ability.QUALITY_MALICIOUS)))
return A;
if((!malicious)
&&(A.canAffect(Ability.CAN_MOBS))
&&(A.enchantQuality()!=Ability.QUALITY_MALICIOUS)
&&(A.enchantQuality()!=Ability.QUALITY_INDIFFERENT))
return A;
}
return null;
}
public Item enchant(Item I, int pct)
{
if(CMLib.dice().rollPercentage()>pct) return I;
int bump=0;
while((CMLib.dice().rollPercentage()<=10)||(bump==0))
bump=bump+((CMLib.dice().rollPercentage()<=80)?1:-1);
if(bump<0) CMLib.flags().setRemovable(I,false);
I.baseEnvStats().setDisposition(I.baseEnvStats().disposition()|EnvStats.IS_BONUS);
I.recoverEnvStats();
if(I instanceof Ammunition)
{
int lvlChange=bump*3;
if(lvlChange<0) lvlChange=lvlChange*-1;
I.baseEnvStats().setLevel(I.baseEnvStats().level()+lvlChange);
switch(CMLib.dice().roll(1,2,0))
{
case 1:
{
Ability A=CMClass.getAbility("Prop_WearAdjuster");
if(A==null) return I;
A.setMiscText("att"+((bump<0)?"":"+")+(bump*5)+" dam="+((bump<0)?"":"+")+bump);
I.addNonUninvokableEffect(A);
break;
}
case 2:
{
Ability A=null;
if(bump<0)
A=CMClass.getAbility("Prayer_CurseItem");
else
{
A=CMClass.getAbility("Prop_FightSpellCast");
if(A!=null)
for(int a=0;a<bump;a++)
{
Ability A2=getCombatSpell(true);
if(A2!=null) A.setMiscText(A.text()+";"+A2.ID());
}
}
if(A==null) return I;
I.addNonUninvokableEffect(A);
break;
}
}
I.recoverEnvStats();
}
else
if(I instanceof Weapon)
{
switch(CMLib.dice().roll(1,2,0))
{
case 1:
{
I.baseEnvStats().setAbility(bump);
break;
}
case 2:
{
Ability A=null;
if(bump<0)
A=CMClass.getAbility("Prayer_CurseItem");
else
{
A=CMClass.getAbility("Prop_FightSpellCast");
if(A!=null)
for(int a=0;a<bump;a++)
{
Ability A2=getCombatSpell(true);
if(A2!=null) A.setMiscText(A.text()+";"+A2.ID());
}
I.baseEnvStats().setLevel(I.baseEnvStats().level()+levelsFromCaster(I,A));
}
if(A==null) return I;
I.addNonUninvokableEffect(A);
break;
}
}
I.recoverEnvStats();
}
else
if(I instanceof Armor)
{
switch(CMLib.dice().roll(1,2,0))
{
case 1:
{
I.baseEnvStats().setAbility(bump);
break;
}
case 2:
{
Ability A=null;
if(bump<0)
A=CMClass.getAbility("Prayer_CurseItem");
else
{
A=CMClass.getAbility("Prop_WearSpellCast");
if(A!=null)
for(int a=0;a<bump;a++)
{
Ability A2=getCombatSpell(false);
if(A2!=null) A.setMiscText(A.text()+";"+A2.ID());
}
I.baseEnvStats().setLevel(I.baseEnvStats().level()+levelsFromCaster(I,A));
}
if(A==null) return I;
I.addNonUninvokableEffect(A);
break;
}
}
I.recoverEnvStats();
}
return I;
}
}
| com/planet_ink/coffee_mud/Libraries/TimsLibrary.java | package com.planet_ink.coffee_mud.Libraries;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2000-2009 Bo Zimmerman
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.
*/
@SuppressWarnings("unchecked")
public class TimsLibrary extends StdLibrary implements ItemBalanceLibrary
{
public String ID(){return "TimsLibrary";}
public int timsLevelCalculator(Item I)
{
int[] castMul=new int[1];
Ability[] RET=getTimsAdjResCast(I,castMul);
Ability ADJ=RET[0];
Ability RES=RET[1];
Ability CAST=RET[2];
return timsLevelCalculator(I,ADJ,RES,CAST,castMul[0]);
}
public int timsLevelCalculator(Item I, Ability ADJ, Ability RES, Ability CAST, int castMul)
{
int level=0;
Item savedI=(Item)I.copyOf();
savedI.recoverEnvStats();
I=(Item)I.copyOf();
I.recoverEnvStats();
int otherDam=0;
int otherAtt=0;
int otherArm=0;
if(ADJ!=null)
{
otherArm=CMParms.getParmPlus(ADJ.text(),"arm")*-1;
otherAtt=CMParms.getParmPlus(ADJ.text(),"att");
otherDam=CMParms.getParmPlus(ADJ.text(),"dam");
}
int curArmor=savedI.baseEnvStats().armor()+otherArm;
double curAttack=(double)(savedI.baseEnvStats().attackAdjustment()+otherAtt);
double curDamage=(double)(savedI.baseEnvStats().damage()+otherDam);
if(I instanceof Weapon)
{
double weight=(double)I.baseEnvStats().weight();
if(weight<1.0) weight=1.0;
double range=(double)savedI.maxRange();
level=(int)Math.round(Math.floor((2.0*curDamage/(2.0*(I.rawLogicalAnd()?2.0:1.0)+1.0)+(curAttack-weight)/5.0+range)*(range/weight+2.0)))+1;
}
else
{
long worndata=savedI.rawProperLocationBitmap();
double weightpts=0;
for(int i=0;i<Item.WORN_WEIGHTS.length-1;i++)
{
if(CMath.isSet(worndata,i))
{
weightpts+=Item.WORN_WEIGHTS[i+1];
if(!I.rawLogicalAnd()) break;
}
}
int[] leatherPoints={ 0, 0, 1, 5,10,16,23,31,40,49,58,67,76,85,94};
int[] clothPoints= { 0, 3, 7,12,18,25,33,42,52,62,72,82,92,102};
int[] metalPoints= { 0, 0, 0, 0, 1, 3, 5, 8,12,17,23,30,38,46,54,62,70,78,86,94};
int materialCode=savedI.material()&RawMaterial.MATERIAL_MASK;
int[] useArray=null;
switch(materialCode)
{
case RawMaterial.MATERIAL_METAL:
case RawMaterial.MATERIAL_MITHRIL:
case RawMaterial.MATERIAL_PRECIOUS:
case RawMaterial.MATERIAL_ENERGY:
useArray=metalPoints;
break;
case RawMaterial.MATERIAL_PLASTIC:
case RawMaterial.MATERIAL_LEATHER:
case RawMaterial.MATERIAL_GLASS:
case RawMaterial.MATERIAL_ROCK:
case RawMaterial.MATERIAL_WOODEN:
useArray=leatherPoints;
break;
default:
useArray=clothPoints;
break;
}
int which=(int)Math.round(CMath.div(curArmor,weightpts)+1);
if(which<0) which=0;
if(which>=useArray.length)
which=useArray.length-1;
level=useArray[which];
}
level+=I.baseEnvStats().ability()*5;
if(CAST!=null)
{
String ID=CAST.ID().toUpperCase();
Vector theSpells=new Vector();
String names=CAST.text();
int del=names.indexOf(";");
while(del>=0)
{
String thisOne=names.substring(0,del);
Ability A=CMClass.getAbility(thisOne);
if(A!=null) theSpells.addElement(A);
names=names.substring(del+1);
del=names.indexOf(";");
}
Ability A=CMClass.getAbility(names);
if(A!=null) theSpells.addElement(A);
for(int v=0;v<theSpells.size();v++)
{
A=(Ability)theSpells.elementAt(v);
int mul=1;
if(A.abstractQuality()==Ability.QUALITY_MALICIOUS) mul=-1;
if(ID.indexOf("HAVE")>=0)
level+=(mul*CMLib.ableMapper().lowestQualifyingLevel(A.ID()));
else
level+=(mul*CMLib.ableMapper().lowestQualifyingLevel(A.ID())/2);
}
}
if(ADJ!=null)
{
String newText=ADJ.text();
int ab=CMParms.getParmPlus(newText,"abi");
int arm=CMParms.getParmPlus(newText,"arm")*-1;
int att=CMParms.getParmPlus(newText,"att");
int dam=CMParms.getParmPlus(newText,"dam");
if(savedI instanceof Weapon)
level+=(arm*2);
else
if(savedI instanceof Armor)
{
level+=(att/2);
level+=(dam*3);
}
level+=ab*5;
int dis=CMParms.getParmPlus(newText,"dis");
if(dis!=0) level+=5;
int sen=CMParms.getParmPlus(newText,"sen");
if(sen!=0) level+=5;
level+=(int)Math.round(5.0*CMParms.getParmDoublePlus(newText,"spe"));
for(int i=0;i<CharStats.NUM_BASE_STATS;i++)
{
int stat=CMParms.getParmPlus(newText,CharStats.STAT_DESCS[i].substring(0,3).toLowerCase());
int max=CMParms.getParmPlus(newText,("max"+(CharStats.STAT_DESCS[i].substring(0,3).toLowerCase())));
level+=(stat*5);
level+=(max*5);
}
int hit=CMParms.getParmPlus(newText,"hit");
int man=CMParms.getParmPlus(newText,"man");
int mv=CMParms.getParmPlus(newText,"mov");
level+=(hit/5);
level+=(man/5);
level+=(mv/5);
}
return level;
}
public boolean fixRejuvItem(Item I)
{
Ability A=I.fetchEffect("ItemRejuv");
if(A!=null)
{
A=I.fetchEffect("ItemRejuv");
if(A.savable())
return false;
A.setSavable(false);
return true;
}
return false;
}
public Ability[] getTimsAdjResCast(Item I, int[] castMul)
{
Ability ADJ=I.fetchEffect("Prop_WearAdjuster");
if(ADJ==null) ADJ=I.fetchEffect("Prop_HaveAdjuster");
if(ADJ==null) ADJ=I.fetchEffect("Prop_RideAdjuster");
Ability RES=I.fetchEffect("Prop_WearResister");
if(RES==null) RES=I.fetchEffect("Prop_HaveResister");
Ability CAST=I.fetchEffect("Prop_WearSpellCast");
castMul[0]=1;
if(CAST==null) CAST=I.fetchEffect("Prop_UseSpellCast");
if(CAST==null) CAST=I.fetchEffect("Prop_UseSpellCast2");
if(CAST==null) CAST=I.fetchEffect("Prop_HaveSpellCast");
if(CAST==null){ CAST=I.fetchEffect("Prop_FightSpellCast"); castMul[0]=-1;}
Ability[] RET=new Ability[3];
RET[0]=ADJ;
RET[1]=RES;
RET[2]=CAST;
return RET;
}
public boolean itemFix(Item I, int lvlOr0)
{
if((I instanceof SpellHolder)
||((I instanceof Wand)&&(lvlOr0<=0)))
{
Vector spells=new Vector();
if(I instanceof SpellHolder)
spells=((SpellHolder)I).getSpells();
else
if(I instanceof Wand)
spells.add(((Wand)I).getSpell());
if(spells.size()==0) return false;
int levels=0;
for(Enumeration<Ability> e=spells.elements();e.hasMoreElements();)
levels+=CMLib.ableMapper().lowestQualifyingLevel(e.nextElement().ID());
int level=(int)Math.round(CMath.div(levels, spells.size()));
if(level==I.baseEnvStats().level()) return false;
I.baseEnvStats().setLevel(level);
I.envStats().setLevel(level);
if(CMLib.flags().isCataloged(I))
CMLib.catalog().updateCatalog(I);
return true;
}
else
if((I instanceof Weapon)||(I instanceof Armor))
{
int lvl=lvlOr0;
if(lvl <=0) lvl=I.baseEnvStats().level();
I.baseEnvStats().setLevel(lvl);
I.envStats().setLevel(lvl);
Ability[] RET=getTimsAdjResCast(I,new int[1]);
Ability ADJ=RET[0];
Ability RES=RET[1];
Ability CAST=RET[2];
int[] LVLS=getItemLevels(I,ADJ,RES,CAST);
int TLVL=totalLevels(LVLS);
if(lvl<0)
{
if(TLVL<=0)
lvl=1;
else
lvl=TLVL;
I.baseEnvStats().setLevel(lvl);
I.recoverEnvStats();
fixRejuvItem(I);
if(CMLib.flags().isCataloged(I))
CMLib.catalog().updateCatalog(I);
return true;
}
if((TLVL>0)&&(TLVL>(lvl+25)))
{
int FTLVL=TLVL;
Vector illegalNums=new Vector();
Log.sysOut("Reset",I.name()+"("+I.baseEnvStats().level()+") "+TLVL+", "+I.baseEnvStats().armor()+"/"+I.baseEnvStats().attackAdjustment()+"/"+I.baseEnvStats().damage()+"/"+((ADJ!=null)?ADJ.text():"null"));
while((TLVL>(lvl+15))&&(illegalNums.size()<4))
{
int highIndex=-1;
for(int i=0;i<LVLS.length;i++)
if(((highIndex<0)||(LVLS[i]>LVLS[highIndex]))
&&(!illegalNums.contains(new Integer(i))))
highIndex=i;
if(highIndex<0) break;
switch(highIndex)
{
case 0:
if(I instanceof Weapon)
{
String s=(ADJ!=null)?ADJ.text():"";
int oldAtt=I.baseEnvStats().attackAdjustment();
int oldDam=I.baseEnvStats().damage();
toneDownWeapon((Weapon)I,ADJ);
if((I.baseEnvStats().attackAdjustment()==oldAtt)
&&(I.baseEnvStats().damage()==oldDam)
&&((ADJ==null)||(ADJ.text().equals(s))))
illegalNums.addElement(new Integer(0));
}
else
{
String s=(ADJ!=null)?ADJ.text():"";
int oldArm=I.baseEnvStats().armor();
toneDownArmor((Armor)I,ADJ);
if((I.baseEnvStats().armor()==oldArm)
&&((ADJ==null)||(ADJ.text().equals(s))))
illegalNums.addElement(new Integer(0));
}
break;
case 1:
if(I.baseEnvStats().ability()>0)
I.baseEnvStats().setAbility(I.baseEnvStats().ability()-1);
else
illegalNums.addElement(new Integer(1));
break;
case 2:
illegalNums.addElement(new Integer(2));
// nothing I can do!;
break;
case 3:
if(ADJ==null)
illegalNums.addElement(new Integer(3));
else
{
String oldTxt=ADJ.text();
toneDownAdjuster(I,ADJ);
if(ADJ.text().equals(oldTxt))
illegalNums.addElement(new Integer(3));
}
break;
}
LVLS=getItemLevels(I,ADJ,RES,CAST);
TLVL=totalLevels(LVLS);
}
Log.sysOut("Reset",I.name()+"("+I.baseEnvStats().level()+") "+FTLVL+"->"+TLVL+", "+I.baseEnvStats().armor()+"/"+I.baseEnvStats().attackAdjustment()+"/"+I.baseEnvStats().damage()+"/"+((ADJ!=null)?ADJ.text():"null"));
fixRejuvItem(I);
if(CMLib.flags().isCataloged(I))
CMLib.catalog().updateCatalog(I);
return true;
}
}
if(fixRejuvItem(I))
{
if(CMLib.flags().isCataloged(I))
CMLib.catalog().updateCatalog(I);
return true;
}
return false;
}
public boolean toneDownValue(Item I)
{
int hands=0;
int weaponClass=0;
if(I instanceof Coins) return false;
if(I instanceof Weapon)
{
hands=I.rawLogicalAnd()?2:1;
weaponClass=((Weapon)I).weaponClassification();
}
else
if(!(I instanceof Armor))
return false;
Hashtable H=timsItemAdjustments(I,I.envStats().level(),I.material(),
I.baseEnvStats().weight(),hands,weaponClass,I.maxRange(),I.rawProperLocationBitmap());
int newValue=CMath.s_int((String)H.get("VALUE"));
if((I.baseGoldValue()>newValue)&&(newValue>0))
{
I.setBaseValue(newValue);
return true;
}
return false;
}
public void balanceItemByLevel(Item I)
{
int hands=0;
int weaponClass=0;
if(I instanceof Weapon)
{
hands=I.rawLogicalAnd()?2:1;
weaponClass=((Weapon)I).weaponClassification();
}
Hashtable H=timsItemAdjustments(I,I.envStats().level(),I.material(),
I.baseEnvStats().weight(),hands,weaponClass,I.maxRange(),I.rawProperLocationBitmap());
if(I instanceof Weapon)
{
I.baseEnvStats().setDamage(CMath.s_int((String)H.get("DAMAGE")));
I.baseEnvStats().setAttackAdjustment(CMath.s_int((String)H.get("ATTACK")));
I.setBaseValue(CMath.s_int((String)H.get("VALUE")));
I.recoverEnvStats();
}
else
if(I instanceof Armor)
{
I.baseEnvStats().setArmor(CMath.s_int((String)H.get("ARMOR")));
I.setBaseValue(CMath.s_int((String)H.get("VALUE")));
I.baseEnvStats().setWeight(CMath.s_int((String)H.get("WEIGHT")));
I.recoverEnvStats();
}
}
public Hashtable timsItemAdjustments(Item I,
int level,
int material,
int weight,
int hands,
int wclass,
int reach,
long worndata)
{
Hashtable vals=new Hashtable();
int materialvalue=RawMaterial.RESOURCE_DATA[material&RawMaterial.RESOURCE_MASK][1];
int[] castMul=new int[1];
Ability[] RET=getTimsAdjResCast(I,castMul);
Ability ADJ=RET[0];
Ability CAST=RET[2];
level-=levelsFromAbility(I);
level-=levelsFromAdjuster(I,ADJ);
level-=levelsFromCaster(I,CAST);
if(I instanceof Weapon)
{
int baseattack=0;
int basereach=0;
int maxreach=0;
int basematerial=RawMaterial.MATERIAL_WOODEN;
if(wclass==Weapon.CLASS_FLAILED) baseattack=-5;
if(wclass==Weapon.CLASS_POLEARM){ basereach=1; basematerial=RawMaterial.MATERIAL_METAL;}
if(wclass==Weapon.CLASS_RANGED){ basereach=1; maxreach=5;}
if(wclass==Weapon.CLASS_THROWN){ basereach=1; maxreach=5;}
if(wclass==Weapon.CLASS_EDGED){ baseattack=10; basematerial=RawMaterial.MATERIAL_METAL;}
if(wclass==Weapon.CLASS_DAGGER){ baseattack=10; basematerial=RawMaterial.MATERIAL_METAL;}
if(wclass==Weapon.CLASS_SWORD){ basematerial=RawMaterial.MATERIAL_METAL;}
if(weight==0) weight=10;
if(basereach>maxreach) maxreach=basereach;
if(reach<basereach)
{
reach=basereach;
vals.put("MINRANGE",""+basereach);
vals.put("MAXRANGE",""+maxreach);
}
else
if(reach>basereach)
basereach=reach;
int damage=((level-1)/((reach/weight)+2) + (weight-baseattack)/5 -reach)*(((hands*2)+1)/2);
int cost=2*((weight*materialvalue)+((2*damage)+baseattack+(reach*10))*damage)/(hands+1);
if(basematerial==RawMaterial.MATERIAL_METAL)
{
switch(material&RawMaterial.MATERIAL_MASK)
{
case RawMaterial.MATERIAL_MITHRIL:
case RawMaterial.MATERIAL_METAL:
case RawMaterial.MATERIAL_ENERGY:
break;
case RawMaterial.MATERIAL_WOODEN:
case RawMaterial.MATERIAL_PLASTIC:
damage-=4;
baseattack-=0;
break;
case RawMaterial.MATERIAL_PRECIOUS:
damage-=4;
baseattack-=10;
break;
case RawMaterial.MATERIAL_LEATHER:
damage-=6;
baseattack-=10;
break;
case RawMaterial.MATERIAL_ROCK:
damage-=2;
baseattack-=10;
break;
case RawMaterial.MATERIAL_GLASS:
damage-=4;
baseattack-=20;
break;
default:
damage-=8;
baseattack-=30;
break;
}
switch(material)
{
case RawMaterial.RESOURCE_BALSA:
case RawMaterial.RESOURCE_LIMESTONE:
case RawMaterial.RESOURCE_FLINT:
baseattack-=10;
damage-=2;
break;
case RawMaterial.RESOURCE_CLAY:
baseattack-=20;
damage-=4;
break;
case RawMaterial.RESOURCE_BONE:
baseattack+=20;
damage+=4;
break;
case RawMaterial.RESOURCE_GRANITE:
case RawMaterial.RESOURCE_OBSIDIAN:
case RawMaterial.RESOURCE_IRONWOOD:
baseattack+=10;
damage+=2;
break;
case RawMaterial.RESOURCE_SAND:
case RawMaterial.RESOURCE_COAL:
baseattack-=40;
damage-=8;
break;
}
}
if(basematerial==RawMaterial.MATERIAL_WOODEN)
{
switch(material&RawMaterial.MATERIAL_MASK)
{
case RawMaterial.MATERIAL_WOODEN:
case RawMaterial.MATERIAL_ENERGY:
break;
case RawMaterial.MATERIAL_METAL:
case RawMaterial.MATERIAL_MITHRIL:
damage+=2;
baseattack-=0;
break;
case RawMaterial.MATERIAL_PRECIOUS:
damage+=2;
baseattack-=10;
break;
case RawMaterial.MATERIAL_LEATHER:
case RawMaterial.MATERIAL_PLASTIC:
damage-=2;
baseattack-=0;
break;
case RawMaterial.MATERIAL_ROCK:
damage+=2;
baseattack-=10;
break;
case RawMaterial.MATERIAL_GLASS:
damage-=2;
baseattack-=10;
break;
default:
damage-=6;
baseattack-=30;
break;
}
switch(material)
{
case RawMaterial.RESOURCE_LIMESTONE:
case RawMaterial.RESOURCE_FLINT:
baseattack-=10;
damage-=2;
break;
case RawMaterial.RESOURCE_CLAY:
baseattack-=20;
damage-=4;
break;
case RawMaterial.RESOURCE_BONE:
baseattack+=20;
damage+=4;
break;
case RawMaterial.RESOURCE_GRANITE:
case RawMaterial.RESOURCE_OBSIDIAN:
baseattack+=10;
damage+=2;
break;
case RawMaterial.RESOURCE_SAND:
case RawMaterial.RESOURCE_COAL:
baseattack-=40;
damage-=8;
break;
}
}
if(damage<=0) damage=1;
vals.put("DAMAGE",""+damage);
vals.put("ATTACK",""+baseattack);
vals.put("VALUE",""+cost);
}
else
if(I instanceof Armor)
{
int[] leatherPoints={ 0, 0, 1, 5,10,16,23,31,40,49,58,67,76,85,94};
int[] clothPoints= { 0, 3, 7,12,18,25,33,42,52,62,72,82,92,102};
int[] metalPoints= { 0, 0, 0, 0, 1, 3, 5, 8,12,17,23,30,38,46,54,62,70,78,86,94};
double pts=0.0;
if(level<0) level=0;
int materialCode=material&RawMaterial.MATERIAL_MASK;
int[] useArray=null;
switch(materialCode)
{
case RawMaterial.MATERIAL_METAL:
case RawMaterial.MATERIAL_MITHRIL:
case RawMaterial.MATERIAL_PRECIOUS:
case RawMaterial.MATERIAL_ENERGY:
useArray=metalPoints;
break;
case RawMaterial.MATERIAL_PLASTIC:
case RawMaterial.MATERIAL_LEATHER:
case RawMaterial.MATERIAL_GLASS:
case RawMaterial.MATERIAL_ROCK:
case RawMaterial.MATERIAL_WOODEN:
useArray=leatherPoints;
break;
default:
useArray=clothPoints;
break;
}
if(level>=useArray[useArray.length-1])
pts=(double)(useArray.length-2);
else
for(int i=0;i<useArray.length;i++)
{
int lvl=useArray[i];
if(lvl>level)
{
pts=(double)(i-1);
break;
}
}
double totalpts=0.0;
double weightpts=0.0;
double wornweights=0.0;
for(int i=0;i<Item.WORN_WEIGHTS.length-1;i++)
{
if(CMath.isSet(worndata,i))
{
totalpts+=(pts*Item.WORN_WEIGHTS[i+1]);
wornweights+=Item.WORN_WEIGHTS[i+1];
switch(materialCode)
{
case RawMaterial.MATERIAL_METAL:
case RawMaterial.MATERIAL_MITHRIL:
case RawMaterial.MATERIAL_PRECIOUS:
weightpts+=Item.WORN_WEIGHT_POINTS[i+1][2];
break;
case RawMaterial.MATERIAL_LEATHER:
case RawMaterial.MATERIAL_GLASS:
case RawMaterial.MATERIAL_PLASTIC:
case RawMaterial.MATERIAL_ROCK:
case RawMaterial.MATERIAL_WOODEN:
weightpts+=Item.WORN_WEIGHT_POINTS[i+1][1];
break;
case RawMaterial.MATERIAL_ENERGY:
break;
default:
weightpts+=Item.WORN_WEIGHT_POINTS[i+1][0];
break;
}
if(hands==1) break;
}
}
int cost=(int)Math.round(((pts*pts) + (double)materialvalue)
* ( weightpts / 2));
int armor=(int)Math.round(totalpts);
switch(material)
{
case RawMaterial.RESOURCE_BALSA:
case RawMaterial.RESOURCE_LIMESTONE:
case RawMaterial.RESOURCE_FLINT:
armor-=1;
break;
case RawMaterial.RESOURCE_CLAY:
armor-=2;
break;
case RawMaterial.RESOURCE_BONE:
armor+=2;
break;
case RawMaterial.RESOURCE_GRANITE:
case RawMaterial.RESOURCE_OBSIDIAN:
case RawMaterial.RESOURCE_IRONWOOD:
armor+=1;
break;
case RawMaterial.RESOURCE_SAND:
case RawMaterial.RESOURCE_COAL:
armor-=4;
break;
}
vals.put("ARMOR",""+armor);
vals.put("VALUE",""+cost);
vals.put("WEIGHT",""+(int)Math.round(((double)armor)/wornweights*weightpts));
}
return vals;
}
public void toneDownWeapon(Weapon W, Ability ADJ)
{
boolean fixdam=true;
boolean fixatt=true;
if((ADJ!=null)&&(ADJ.text().toUpperCase().indexOf("DAMAGE+")>=0))
{
int a=ADJ.text().toUpperCase().indexOf("DAMAGE+");
int a2=ADJ.text().toUpperCase().indexOf(" ",a+4);
if(a2<0) a2=ADJ.text().length();
int num=CMath.s_int(ADJ.text().substring(a+7,a2));
if(num>W.baseEnvStats().damage())
{
fixdam=false;
ADJ.setMiscText(ADJ.text().substring(0,a+7)+(num/2)+ADJ.text().substring(a2));
}
}
if((ADJ!=null)&&(ADJ.text().toUpperCase().indexOf("ATTACK+")>=0))
{
int a=ADJ.text().toUpperCase().indexOf("ATTACK+");
int a2=ADJ.text().toUpperCase().indexOf(" ",a+4);
if(a2<0) a2=ADJ.text().length();
int num=CMath.s_int(ADJ.text().substring(a+7,a2));
if(num>W.baseEnvStats().attackAdjustment())
{
fixatt=false;
ADJ.setMiscText(ADJ.text().substring(0,a+7)+(num/2)+ADJ.text().substring(a2));
}
}
if(fixdam&&(W.baseEnvStats().damage()>=2))
W.baseEnvStats().setDamage(W.baseEnvStats().damage()/2);
if(fixatt&&(W.baseEnvStats().attackAdjustment()>=2))
W.baseEnvStats().setAttackAdjustment(W.baseEnvStats().attackAdjustment()/2);
W.recoverEnvStats();
}
public void toneDownArmor(Armor A, Ability ADJ)
{
boolean fixit=true;
if((ADJ!=null)&&(ADJ.text().toUpperCase().indexOf("ARMOR-")>=0))
{
int a=ADJ.text().toUpperCase().indexOf("ARMOR-");
int a2=ADJ.text().toUpperCase().indexOf(" ",a+4);
if(a2<0) a2=ADJ.text().length();
int num=CMath.s_int(ADJ.text().substring(a+6,a2));
if(num>A.baseEnvStats().armor())
{
fixit=false;
ADJ.setMiscText(ADJ.text().substring(0,a+6)+(num/2)+ADJ.text().substring(a2));
}
}
if(fixit&&(A.baseEnvStats().armor()>=2))
{
A.baseEnvStats().setArmor(A.baseEnvStats().armor()/2);
A.recoverEnvStats();
}
}
public void toneDownAdjuster(Item I, Ability ADJ)
{
String s=ADJ.text();
int plusminus=s.indexOf("+");
int minus=s.indexOf("-");
if((minus>=0)&&((plusminus<0)||(minus<plusminus)))
plusminus=minus;
while(plusminus>=0)
{
int spaceafter=s.indexOf(" ",plusminus+1);
if(spaceafter<0) spaceafter=s.length();
if(spaceafter>plusminus)
{
String number=s.substring(plusminus+1,spaceafter).trim();
if(CMath.isNumber(number))
{
int num=CMath.s_int(number);
int spacebefore=s.lastIndexOf(" ",plusminus);
if(spacebefore<0) spacebefore=0;
if(spacebefore<plusminus)
{
boolean proceed=true;
String wd=s.substring(spacebefore,plusminus).trim().toUpperCase();
if(wd.startsWith("DIS"))
proceed=false;
else
if(wd.startsWith("SEN"))
proceed=false;
else
if(wd.startsWith("ARM")&&(I instanceof Armor))
proceed=false;
else
if(wd.startsWith("ATT")&&(I instanceof Weapon))
proceed=false;
else
if(wd.startsWith("DAM")&&(I instanceof Weapon))
proceed=false;
else
if(wd.startsWith("ARM")&&(s.charAt(plusminus)=='+'))
proceed=false;
else
if((!wd.startsWith("ARM"))&&(s.charAt(plusminus)=='-'))
proceed=false;
if(proceed)
{
if((num!=1)&&(num!=-1))
s=s.substring(0,plusminus+1)+(num/2)+s.substring(spaceafter);
}
}
}
}
minus=s.indexOf("-",plusminus+1);
plusminus=s.indexOf("+",plusminus+1);
if((minus>=0)&&((plusminus<0)||(minus<plusminus)))
plusminus=minus;
}
ADJ.setMiscText(s);
}
public int[] getItemLevels(Item I, Ability ADJ, Ability RES, Ability CAST)
{
int[] LVLS=new int[4];
LVLS[0]=timsBaseLevel(I,ADJ);
LVLS[1]=levelsFromAbility(I);
LVLS[2]=levelsFromCaster(I,CAST);
LVLS[3]=levelsFromAdjuster(I,ADJ);
return LVLS;
}
public int totalLevels(int[] levels)
{
int lvl=levels[0];
for(int i=1;i<levels.length;i++)
lvl+=levels[i];
return lvl;
}
public int timsBaseLevel(Item I)
{
Ability[] RET=getTimsAdjResCast(I,new int[1]);
return timsBaseLevel(I,RET[0]);
}
public int timsBaseLevel(Item I, Ability ADJ)
{
int level=0;
int otherDam=0;
int otherAtt=0;
int otherArm=0;
if(ADJ!=null)
{
otherArm=CMParms.getParmPlus(ADJ.text(),"arm")*-1;
otherAtt=CMParms.getParmPlus(ADJ.text(),"att");
otherDam=CMParms.getParmPlus(ADJ.text(),"dam");
}
int curArmor=I.baseEnvStats().armor()+otherArm;
double curAttack=(double)(I.baseEnvStats().attackAdjustment()+otherAtt);
double curDamage=(double)(I.baseEnvStats().damage()+otherDam);
if(I instanceof Weapon)
{
double weight=(double)(I.baseEnvStats().weight());
if(weight<1.0) weight=1.0;
double range=(double)(I.maxRange());
level=(int)Math.round(Math.floor((2.0*curDamage/(2.0*(I.rawLogicalAnd()?2.0:1.0)+1.0)+(curAttack-weight)/5.0+range)*(range/weight+2.0)))+1;
}
else
{
long worndata=I.rawProperLocationBitmap();
double weightpts=0;
for(int i=0;i<Item.WORN_WEIGHTS.length-1;i++)
{
if(CMath.isSet(worndata,i))
{
weightpts+=Item.WORN_WEIGHTS[i+1];
if(!I.rawLogicalAnd()) break;
}
}
int[] leatherPoints={ 0, 0, 1, 5,10,16,23,31,40,49,58,67,76,85,94};
int[] clothPoints= { 0, 3, 7,12,18,25,33,42,52,62,72,82,92,102};
int[] metalPoints= { 0, 0, 0, 0, 1, 3, 5, 8,12,17,23,30,38,46,54,62,70,78,86,94};
int materialCode=I.material()&RawMaterial.MATERIAL_MASK;
int[] useArray=null;
switch(materialCode)
{
case RawMaterial.MATERIAL_METAL:
case RawMaterial.MATERIAL_MITHRIL:
case RawMaterial.MATERIAL_PRECIOUS:
case RawMaterial.MATERIAL_ENERGY:
useArray=metalPoints;
break;
case RawMaterial.MATERIAL_PLASTIC:
case RawMaterial.MATERIAL_LEATHER:
case RawMaterial.MATERIAL_GLASS:
case RawMaterial.MATERIAL_ROCK:
case RawMaterial.MATERIAL_WOODEN:
useArray=leatherPoints;
break;
default:
useArray=clothPoints;
break;
}
int which=(int)Math.round(CMath.div(curArmor,weightpts)+1);
if(which<0) which=0;
if(which>=useArray.length)
which=useArray.length-1;
level=useArray[which];
}
return level;
}
public int levelsFromAbility(Item savedI)
{ return savedI.baseEnvStats().ability()*5;}
public int levelsFromAdjuster(Item savedI, Ability ADJ)
{
int level=0;
if(ADJ!=null)
{
String newText=ADJ.text();
int ab=CMParms.getParmPlus(newText,"abi");
int arm=CMParms.getParmPlus(newText,"arm")*-1;
int att=CMParms.getParmPlus(newText,"att");
int dam=CMParms.getParmPlus(newText,"dam");
if(savedI instanceof Weapon)
level+=(arm*2);
else
if(savedI instanceof Armor)
{
level+=(att/2);
level+=(dam*3);
}
level+=ab*5;
int dis=CMParms.getParmPlus(newText,"dis");
if(dis!=0) level+=5;
int sen=CMParms.getParmPlus(newText,"sen");
if(sen!=0) level+=5;
level+=(int)Math.round(5.0*CMParms.getParmDoublePlus(newText,"spe"));
for(int i=0;i<CharStats.NUM_BASE_STATS;i++)
{
int stat=CMParms.getParmPlus(newText,CharStats.STAT_DESCS[i].substring(0,3).toLowerCase());
int max=CMParms.getParmPlus(newText,("max"+(CharStats.STAT_DESCS[i].substring(0,3).toLowerCase())));
level+=(stat*5);
level+=(max*5);
}
int hit=CMParms.getParmPlus(newText,"hit");
int man=CMParms.getParmPlus(newText,"man");
int mv=CMParms.getParmPlus(newText,"mov");
level+=(hit/5);
level+=(man/5);
level+=(mv/5);
}
return level;
}
public int levelsFromCaster(Item savedI, Ability CAST)
{
int level=0;
if(CAST!=null)
{
String ID=CAST.ID().toUpperCase();
Vector theSpells=new Vector();
String names=CAST.text();
int del=names.indexOf(";");
while(del>=0)
{
String thisOne=names.substring(0,del);
Ability A=CMClass.getAbility(thisOne);
if(A!=null) theSpells.addElement(A);
names=names.substring(del+1);
del=names.indexOf(";");
}
Ability A=CMClass.getAbility(names);
if(A!=null) theSpells.addElement(A);
for(int v=0;v<theSpells.size();v++)
{
A=(Ability)theSpells.elementAt(v);
int mul=1;
if(A.abstractQuality()==Ability.QUALITY_MALICIOUS) mul=-1;
if(ID.indexOf("HAVE")>=0)
level+=(mul*CMLib.ableMapper().lowestQualifyingLevel(A.ID()));
else
level+=(mul*CMLib.ableMapper().lowestQualifyingLevel(A.ID())/2);
}
}
return level;
}
public synchronized Vector getCombatSpellSet()
{
Vector spellSet=(Vector)Resources.getResource("COMPLETE_SPELL_SET");
if(spellSet==null)
{
spellSet=new Vector();
Ability A=null;
for(Enumeration e=CMClass.abilities();e.hasMoreElements();)
{
A=(Ability)e.nextElement();
if(((A.classificationCode()&(Ability.ALL_ACODES))==Ability.ACODE_SPELL))
{
int lowLevel=CMLib.ableMapper().lowestQualifyingLevel(A.ID());
if((lowLevel>0)&&(lowLevel<25))
spellSet.addElement(A);
}
}
Resources.submitResource("COMPLETE_SPELL_SET",spellSet);
}
return spellSet;
}
public Ability getCombatSpell(boolean malicious)
{
Vector spellSet=getCombatSpellSet();
int tries=0;
while(((++tries)<1000))
{
Ability A=(Ability)spellSet.elementAt(CMLib.dice().roll(1,spellSet.size(),-1));
if(((malicious)&&(A.canTarget(Ability.CAN_MOBS))&&(A.enchantQuality()==Ability.QUALITY_MALICIOUS)))
return A;
if((!malicious)
&&(A.canAffect(Ability.CAN_MOBS))
&&(A.enchantQuality()!=Ability.QUALITY_MALICIOUS)
&&(A.enchantQuality()!=Ability.QUALITY_INDIFFERENT))
return A;
}
return null;
}
public Item enchant(Item I, int pct)
{
if(CMLib.dice().rollPercentage()>pct) return I;
int bump=0;
while((CMLib.dice().rollPercentage()<=10)||(bump==0))
bump=bump+((CMLib.dice().rollPercentage()<=80)?1:-1);
if(bump<0) CMLib.flags().setRemovable(I,false);
I.baseEnvStats().setDisposition(I.baseEnvStats().disposition()|EnvStats.IS_BONUS);
I.recoverEnvStats();
if(I instanceof Ammunition)
{
int lvlChange=bump*3;
if(lvlChange<0) lvlChange=lvlChange*-1;
I.baseEnvStats().setLevel(I.baseEnvStats().level()+lvlChange);
switch(CMLib.dice().roll(1,2,0))
{
case 1:
{
Ability A=CMClass.getAbility("Prop_WearAdjuster");
if(A==null) return I;
A.setMiscText("att"+((bump<0)?"":"+")+(bump*5)+" dam="+((bump<0)?"":"+")+bump);
I.addNonUninvokableEffect(A);
break;
}
case 2:
{
Ability A=null;
if(bump<0)
A=CMClass.getAbility("Prayer_CurseItem");
else
{
A=CMClass.getAbility("Prop_FightSpellCast");
if(A!=null)
for(int a=0;a<bump;a++)
{
Ability A2=getCombatSpell(true);
if(A2!=null) A.setMiscText(A.text()+";"+A2.ID());
}
}
if(A==null) return I;
I.addNonUninvokableEffect(A);
break;
}
}
I.recoverEnvStats();
}
else
if(I instanceof Weapon)
{
switch(CMLib.dice().roll(1,2,0))
{
case 1:
{
I.baseEnvStats().setAbility(bump);
break;
}
case 2:
{
Ability A=null;
if(bump<0)
A=CMClass.getAbility("Prayer_CurseItem");
else
{
A=CMClass.getAbility("Prop_FightSpellCast");
if(A!=null)
for(int a=0;a<bump;a++)
{
Ability A2=getCombatSpell(true);
if(A2!=null) A.setMiscText(A.text()+";"+A2.ID());
}
I.baseEnvStats().setLevel(I.baseEnvStats().level()+levelsFromCaster(I,A));
}
if(A==null) return I;
I.addNonUninvokableEffect(A);
break;
}
}
I.recoverEnvStats();
}
else
if(I instanceof Armor)
{
switch(CMLib.dice().roll(1,2,0))
{
case 1:
{
I.baseEnvStats().setAbility(bump);
break;
}
case 2:
{
Ability A=null;
if(bump<0)
A=CMClass.getAbility("Prayer_CurseItem");
else
{
A=CMClass.getAbility("Prop_WearSpellCast");
if(A!=null)
for(int a=0;a<bump;a++)
{
Ability A2=getCombatSpell(false);
if(A2!=null) A.setMiscText(A.text()+";"+A2.ID());
}
I.baseEnvStats().setLevel(I.baseEnvStats().level()+levelsFromCaster(I,A));
}
if(A==null) return I;
I.addNonUninvokableEffect(A);
break;
}
}
I.recoverEnvStats();
}
return I;
}
}
|
git-svn-id: svn://192.168.1.10/public/CoffeeMud@7868 0d6f1817-ed0e-0410-87c9-987e46238f29
| com/planet_ink/coffee_mud/Libraries/TimsLibrary.java | ||
Java | apache-2.0 | 4fe978f3c6a072373045f5395cd27b7ed1961d0d | 0 | jyeary/dnsjnio | /*
The contents of this file are subject to the Mozilla
Public Licence Version 1.1 (the "Licence"); you may
not use this file except in compliance with the
Licence. You may obtain a copy of the Licence at
http://www.mozilla.org/MPL
Software distributed under the Licence is distributed
on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
either express or implied. See the Licence of the
specific language governing rights and limitations
under the Licence.
The Original Code is dnsjnio.
The Initial Developer of the Original Code is
Nominet UK (www.nominet.org.uk). Portions created by
Nominet UK are Copyright (c) Nominet UK 2006.
All rights reserved.
*/
package uk.nominet.dnsjnio;
import java.util.LinkedList;
/**
* This class implements a simple queue.
* It blocks threads wishing to remove an object from the queue
* until an object is available.
*/
public class ResponseQueue
{
protected LinkedList list = new LinkedList();
protected int waitingThreads = 0;
/**
* This method is called internally to add a new Response to the queue.
* @param response the new Response
*/
public synchronized void insert(Response response)
{
list.addLast(response);
notify();
}
public synchronized Response getItem()
{
while ( isEmpty() ) {
try { waitingThreads++; wait();}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
//Thread.interrupted();
}
waitingThreads--;
}
return (Response)(list.removeFirst());
}
public boolean isEmpty() {
return (list.size() - waitingThreads <= 0);
}
}
| src/uk/nominet/dnsjnio/ResponseQueue.java | /*
The contents of this file are subject to the Mozilla
Public Licence Version 1.1 (the "Licence"); you may
not use this file except in compliance with the
Licence. You may obtain a copy of the Licence at
http://www.mozilla.org/MPL
Software distributed under the Licence is distributed
on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
either express or implied. See the Licence of the
specific language governing rights and limitations
under the Licence.
The Original Code is dnsjnio.
The Initial Developer of the Original Code is
Nominet UK (www.nominet.org.uk). Portions created by
Nominet UK are Copyright (c) Nominet UK 2006.
All rights reserved.
*/
package uk.nominet.dnsjnio;
import java.util.LinkedList;
/**
* This class implements a simple queue.
* It blocks threads wishing to remove an object from the queue
* until an object is available.
*/
public class ResponseQueue
{
protected LinkedList list = new LinkedList();
protected int waitingThreads = 0;
/**
* This method is called internally to add a new Response to the queue.
* @param response the new Response
*/
public synchronized void insert(Response response)
{
list.addLast(response);
notify();
}
public synchronized Response getItem()
{
while ( isEmpty() ) {
try { waitingThreads++; wait();}
catch (InterruptedException e) {Thread.interrupted();}
waitingThreads--;
}
return (Response)(list.removeFirst());
}
public boolean isEmpty() {
return (list.size() - waitingThreads <= 0);
}
}
| Fixing interrupt code
| src/uk/nominet/dnsjnio/ResponseQueue.java | Fixing interrupt code |
|
Java | apache-2.0 | 3ce69fdd840efd0105ac58dc13ee835621f58825 | 0 | AVnetWS/Hentoid,AVnetWS/Hentoid,AVnetWS/Hentoid | package me.devsaki.hentoid.parsers.images;
import android.util.Pair;
import androidx.annotation.NonNull;
import org.jsoup.nodes.Document;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import me.devsaki.hentoid.database.domains.Content;
import me.devsaki.hentoid.enums.Site;
import me.devsaki.hentoid.parsers.ParseHelper;
import me.devsaki.hentoid.util.JsonHelper;
import me.devsaki.hentoid.util.StringHelper;
import static me.devsaki.hentoid.util.network.HttpHelper.getOnlineDocument;
/**
* Created by robb_w on 01/31/2018.
* Handles parsing of content from pururin.to
*/
public class PururinParser extends BaseImageListParser {
private static final String IMAGE_PATH = "//cdn.pururin.to/assets/images/data/";
public static class PururinInfo {
String image_extension;
String id;
}
@Override
protected List<String> parseImages(@NonNull Content content) throws Exception {
List<String> result = new ArrayList<>();
List<Pair<String, String>> headers = new ArrayList<>();
ParseHelper.addSavedCookiesToHeader(content.getDownloadParams(), headers);
String url = content.getReaderUrl();
String protocol = url.substring(0, 5);
if ("https".equals(protocol)) protocol = "https:";
// The whole algorithm is in app.js
// 1- Get image extension from gallery data (JSON on HTML body)
// 2- Generate image URL from imagePath constant, gallery ID, page number and extension
// 1- Get image extension from gallery data (JSON on HTML body)
Document doc = getOnlineDocument(url, headers, Site.PURURIN.useHentoidAgent(), Site.PURURIN.useWebviewAgent());
if (doc != null) {
String json = doc.select("gallery-read").attr("encoded");
PururinInfo info = JsonHelper.jsonToObject(new String(StringHelper.decode64(json)), PururinInfo.class);
// 2- Get imagePath from app.js => it is constant anyway, and app.js is 3 MB long => put it there as a const
for (int i = 0; i < content.getQtyPages(); i++) {
result.add(protocol + IMAGE_PATH + info.id + File.separator + (i + 1) + "." + info.image_extension);
}
}
return result;
}
}
| app/src/main/java/me/devsaki/hentoid/parsers/images/PururinParser.java | package me.devsaki.hentoid.parsers.images;
import android.util.Pair;
import androidx.annotation.NonNull;
import org.jsoup.nodes.Document;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import me.devsaki.hentoid.database.domains.Content;
import me.devsaki.hentoid.enums.Site;
import me.devsaki.hentoid.parsers.ParseHelper;
import me.devsaki.hentoid.util.JsonHelper;
import static me.devsaki.hentoid.util.network.HttpHelper.getOnlineDocument;
/**
* Created by robb_w on 01/31/2018.
* Handles parsing of content from pururin.to
*/
public class PururinParser extends BaseImageListParser {
private static final String IMAGE_PATH = "//cdn.pururin.to/assets/images/data/";
public static class PururinInfo {
String image_extension;
String id;
}
@Override
protected List<String> parseImages(@NonNull Content content) throws Exception {
List<String> result = new ArrayList<>();
List<Pair<String, String>> headers = new ArrayList<>();
ParseHelper.addSavedCookiesToHeader(content.getDownloadParams(), headers);
String url = content.getReaderUrl();
String protocol = url.substring(0, 5);
if ("https".equals(protocol)) protocol = "https:";
// The whole algorithm is in app.js
// 1- Get image extension from gallery data (JSON on HTML body)
// 2- Generate image URL from imagePath constant, gallery ID, page number and extension
// 1- Get image extension from gallery data (JSON on HTML body)
Document doc = getOnlineDocument(url, headers, Site.PURURIN.useHentoidAgent(), Site.PURURIN.useWebviewAgent());
if (doc != null) {
String json = doc.select("gallery-read").attr(":gallery");
PururinInfo info = JsonHelper.jsonToObject(json, PururinInfo.class);
// 2- Get imagePath from app.js => it is constant anyway, and app.js is 3 MB long => put it there as a const
for (int i = 0; i < content.getQtyPages(); i++) {
result.add(protocol + IMAGE_PATH + info.id + File.separator + (i + 1) + "." + info.image_extension);
}
}
return result;
}
}
| Pururin : Decode gallery data
| app/src/main/java/me/devsaki/hentoid/parsers/images/PururinParser.java | Pururin : Decode gallery data |
|
Java | apache-2.0 | 064a54afd10f863671f82a678c03b5731de8a160 | 0 | Aeronica/mxTune | /*
* Aeronica's mxTune MOD
* Copyright 2019, Paul Boese a.k.a. Aeronica
*
* 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 net.aeronica.mods.mxtune.gui.mml;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import net.aeronica.mods.mxtune.Reference;
import net.aeronica.mods.mxtune.caches.FileHelper;
import net.aeronica.mods.mxtune.caches.MXTuneFile;
import net.aeronica.mods.mxtune.caches.MXTuneFileHelper;
import net.aeronica.mods.mxtune.gui.util.GuiScrollingListOf;
import net.aeronica.mods.mxtune.gui.util.GuiScrollingMultiListOf;
import net.aeronica.mods.mxtune.gui.util.ModGuiUtils;
import net.aeronica.mods.mxtune.managers.ClientFileManager;
import net.aeronica.mods.mxtune.managers.records.Area;
import net.aeronica.mods.mxtune.managers.records.Song;
import net.aeronica.mods.mxtune.managers.records.SongProxy;
import net.aeronica.mods.mxtune.network.PacketDispatcher;
import net.aeronica.mods.mxtune.network.bidirectional.GetAreasMessage;
import net.aeronica.mods.mxtune.network.bidirectional.SetServerSerializedDataMessage;
import net.aeronica.mods.mxtune.network.server.PlayerSelectedAreaMessage;
import net.aeronica.mods.mxtune.util.CallBackManager;
import net.aeronica.mods.mxtune.util.GUID;
import net.aeronica.mods.mxtune.util.MXTuneRuntimeException;
import net.aeronica.mods.mxtune.util.ModLogger;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiLabel;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiTextField;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.resources.I18n;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.fml.relauncher.Side;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static net.aeronica.mods.mxtune.gui.mml.SortHelper.PLAYLIST_ORDERING;
import static net.aeronica.mods.mxtune.gui.mml.SortHelper.SONG_PROXY_ORDERING;
public class GuiPlaylistManager extends GuiScreen
{
private static final String TITLE = I18n.format("mxtune.gui.guiAreaManager.title");
// Song Multi Selector
private GuiScrollingMultiListOf<Path> guiFileList;
private List<Path> cachedFileList = new ArrayList<>();
private Set<Integer> cachedSelectedSongs = new HashSet<>();
private int cachedSelectedFileDummy = -1;
// Playlist Selector
private GuiScrollingListOf<Area> guiPlayList;
private List<Area> cachedPlayListGuiList = new ArrayList<>();
private int cachedSelectedPlayListIndex = -1;
// PlayList Day
private GuiScrollingMultiListOf<SongProxy> guiDay;
private List<SongProxy> cachedDayList = new ArrayList<>();
private Set<Integer> cachedSelectedDaySongs = new HashSet<>();
private int cachedSelectedDaySongDummy = -1;
// PlayList Night
private GuiScrollingMultiListOf<SongProxy> guiNight;
private List<SongProxy> cachedNightList = new ArrayList<>();
private Set<Integer> cachedSelectedNightSongs = new HashSet<>();
private int cachedSelectedNightSongDummy = -1;
// Playlist Name Field
private GuiTextField playListName;
private String cachedPlayListName = "";
// Status
private GuiScrollingListOf<ITextComponent> guiStatusList;
private List<ITextComponent> cachedGuiStatusList = new ArrayList<>();
private final DateFormat timeInstance = SimpleDateFormat.getTimeInstance(DateFormat.MEDIUM);
// Misc
private GuiLabel titleLabel;
private boolean cacheKeyRepeatState;
private boolean isStateCached;
private GuiButton buttonToServer;
private Pattern patternPlaylistName = Pattern.compile("^\\s+|\\s+$|^\\[");
// Uploading
private boolean uploading = false;
// Mapping
private BiMap<Path, SongProxy> pathSongProxyBiMap = HashBiMap.create();
private BiMap<SongProxy, Path> songProxyPathBiMap;
private BiMap<Path, GUID> pathSongGuidBiMap = HashBiMap.create();
private BiMap<GUID, Path> songGuidPathBiMap;
// TODO: Finnish updating string to use the lang file.
public GuiPlaylistManager()
{
cacheKeyRepeatState = Keyboard.areRepeatEventsEnabled();
Keyboard.enableRepeatEvents(false);
initFileList();
}
@Override
public void onGuiClosed()
{
Keyboard.enableRepeatEvents(cacheKeyRepeatState);
}
@Override
public void initGui()
{
int guiPlayListListWidth = Math.min(Math.max((width - 15) / 3, 100), 400);
int guiFileListWidth = guiPlayListListWidth;
int singleLineHeight = mc.fontRenderer.FONT_HEIGHT + 2;
int entryPlayListHeight = singleLineHeight;
int padding = 4;
int titleTop = padding;
int left = padding;
int titleWidth = fontRenderer.getStringWidth(I18n.format("mxtune.gui.guiAreaManager.title"));
int titleX = (width / 2) - (titleWidth / 2);
int titleHeight = singleLineHeight + 2;
int statusHeight = singleLineHeight * 8;
int entryFileHeight = singleLineHeight;
int listTop = titleTop + titleHeight;
int fileListBottom = Math.max(height - statusHeight - listTop - titleHeight - padding, entryPlayListHeight * 9);
int fileListHeight = Math.max(fileListBottom - listTop, singleLineHeight);
int statusTop = fileListBottom + padding;
int thirdsHeight = ((statusTop - listTop) / 3) - padding;
int areaListHeight = Math.max(thirdsHeight, entryPlayListHeight);
int areaBottom = listTop + areaListHeight;
int dayTop = areaBottom + padding;
int dayBottom = dayTop + areaListHeight;
int nightTop = dayBottom + padding;
int nightBottom = nightTop + areaListHeight;
titleLabel = new GuiLabel(fontRenderer, 0, titleX, titleTop, titleWidth, singleLineHeight, 0xFFFFFF );
titleLabel.addLine(TITLE);
guiFileList = new GuiScrollingMultiListOf<Path>(this, entryFileHeight, guiFileListWidth, fileListHeight,listTop, fileListBottom, left)
{
@Override
protected void drawSlot(int slotIdx, int entryRight, int slotTop, int slotBuffer, float scrollDistance, Tessellator tess)
{
// get the filename and remove the '.mxt' extension
Path entry = get(slotIdx);
if (entry != null)
{
String name = entry.getFileName().toString().replaceAll("\\.[mM][xX][tT]$", "");
String trimmedName = fontRenderer.trimStringToWidth(name, listWidth - 10);
int color = selectedRowIndexes.contains(slotIdx) ? 0xFFFF00 : 0xADD8E6;
fontRenderer.drawStringWithShadow(trimmedName, (float) left + 3, slotTop, color);
} else
{
String name = "---NULL---";
String trimmedName = fontRenderer.trimStringToWidth(name, listWidth - 10);
int color = 0xFF0000;
fontRenderer.drawStringWithShadow(trimmedName, (float) left + 3, slotTop, color);
}
}
@Override
protected void selectedClickedCallback(int selectedIndex)
{
super.selectedClickedCallback(selectedIndex);
updateSongCountStatus();
}
};
guiPlayList = new GuiScrollingListOf<Area>(this, entryPlayListHeight, guiPlayListListWidth, areaListHeight, listTop, areaBottom, width - guiPlayListListWidth - padding)
{
@Override
protected void drawSlot(int slotIdx, int entryRight, int slotTop, int slotBuffer, Tessellator tess)
{
Area area = get(slotIdx);
if (area != null)
{
String playlistName = ModGuiUtils.getPlaylistName(area);
String trimmedName = fontRenderer.trimStringToWidth(playlistName, listWidth - 10);
int color = isSelected(slotIdx) ? 0xFFFF00 : 0xAADDEE;
fontRenderer.drawStringWithShadow(trimmedName, (float) left + 3, slotTop, color);
} else
{
String name = "---GUID Conflict---";
String trimmedName = fontRenderer.trimStringToWidth(name, listWidth - 10);
int color = 0xFF0000;
fontRenderer.drawStringWithShadow(trimmedName, (float) left + 3, slotTop, color);
}
}
@Override
protected void selectedClickedCallback(int selectedIndex)
{
showSelectedPlaylistsPlaylists(guiPlayList.get(selectedIndex));
}
@Override
protected void selectedDoubleClickedCallback(int selectedIndex)
{
updatePlayersSelectedAreaGuid(guiPlayList.get(selectedIndex));
}
};
guiDay = new GuiScrollingMultiListOf<SongProxy>(this, singleLineHeight, guiPlayListListWidth, areaListHeight ,dayTop, dayBottom, width - guiPlayListListWidth - padding)
{
@Override
protected void drawSlot(int slotIdx, int entryRight, int slotTop, int slotBuffer, float scrollDistance, Tessellator tess)
{
drawSlotCommon(this, slotIdx, slotTop, listWidth, left);
}
};
guiNight = new GuiScrollingMultiListOf<SongProxy>(this, singleLineHeight, guiPlayListListWidth, areaListHeight, nightTop, nightBottom, width - guiPlayListListWidth - padding)
{
@Override
protected void drawSlot(int slotIdx, int entryRight, int slotTop, int slotBuffer, float scrollDistance, Tessellator tess)
{
drawSlotCommon(this, slotIdx, slotTop, listWidth, left);
}
};
guiStatusList = new GuiScrollingListOf<ITextComponent>(this, singleLineHeight, width - padding *2, statusHeight, statusTop, height - 22 - padding * 2, left) {
@Override
protected void selectedClickedCallback(int selectedIndex) { /* NOP */ }
@Override
protected void selectedDoubleClickedCallback(int selectedIndex){ /* NOP */ }
@Override
protected void drawSlot(int slotIdx, int entryRight, int slotTop, int slotBuffer, Tessellator tess)
{
ITextComponent component = get(slotIdx);
if (component != null)
{
String statusEntry = component.getFormattedText();
String trimmedName = fontRenderer.trimStringToWidth(statusEntry, listWidth - 10);
fontRenderer.drawStringWithShadow(trimmedName, (float) left + 3, slotTop, -1);
}
}
};
int buttonWidth = 80;
int buttonTop = height - 22;
int xLibrary = (this.width /2) - buttonWidth;
int xDone = xLibrary + buttonWidth;
GuiButton buttonImport = new GuiButton(0, xLibrary, buttonTop, buttonWidth, 20, I18n.format("mxtune.gui.button.musicLibrary"));
GuiButton buttonDone = new GuiButton(1, xDone, buttonTop, buttonWidth, 20, I18n.format("gui.done"));
int selectButtonWidth = guiFileListWidth - 10;
int selectButtonLeft = guiFileList.getRight() + 8;
playListName = new GuiTextField(1, fontRenderer, selectButtonLeft, listTop, selectButtonWidth, singleLineHeight + 2);
buttonToServer = new GuiButton(6, selectButtonLeft, playListName.y + playListName.height + padding, selectButtonWidth, 20, "Send to Server");
GuiButton buttonToDay = new GuiButton(2, selectButtonLeft, dayTop + padding, selectButtonWidth, 20, "To Day List ->");
GuiButton buttonToNight = new GuiButton(3, selectButtonLeft, nightTop + padding, selectButtonWidth, 20, "To Night List ->");
GuiButton buttonDDeleteDay = new GuiButton(4, selectButtonLeft, buttonToDay.y + buttonToDay.height, selectButtonWidth, 20, "Delete");
GuiButton buttonDDeleteNight = new GuiButton(5, selectButtonLeft, buttonToNight.y + buttonToNight.height, selectButtonWidth, 20, "Delete");
buttonList.add(buttonImport);
buttonList.add(buttonDone);
buttonList.add(buttonToDay);
buttonList.add(buttonToNight);
buttonList.add(buttonDDeleteDay);
buttonList.add(buttonDDeleteNight);
buttonList.add(buttonToServer);
initAreas();
reloadState();
}
private <T extends GuiScrollingMultiListOf<SongProxy>> void drawSlotCommon(T parent, int slotIdx, int slotTop, int listWidth, int left)
{
SongProxy entry = parent.get(slotIdx);
if (entry != null)
{
String name = entry.getTitle();
String trimmedName = fontRenderer.trimStringToWidth(name, listWidth - 10);
int color = parent.getSelectedRowIndexes().contains(slotIdx) ? 0xFFFF00 : 0xADD8E6;
fontRenderer.drawStringWithShadow(trimmedName, (float) left + 3, slotTop, color);
} else
{
String name = "---GUID Conflict---";
String trimmedName = fontRenderer.trimStringToWidth(name, listWidth - 10);
int color = 0xFF0000;
fontRenderer.drawStringWithShadow(trimmedName, (float) left + 3, slotTop, color);
}
}
private void reloadState()
{
if (!isStateCached) return;
guiPlayList.addAll(cachedPlayListGuiList);
guiPlayList.setSelectedIndex(cachedSelectedPlayListIndex);
guiFileList.addAll(cachedFileList);
guiFileList.setSelectedRowIndexes(cachedSelectedSongs);
guiFileList.setSelectedIndex(cachedSelectedFileDummy);
guiDay.addAll(cachedDayList);
guiDay.setSelectedRowIndexes(cachedSelectedDaySongs);
guiDay.setSelectedIndex(cachedSelectedDaySongDummy);
guiNight.addAll(cachedNightList);
guiNight.setSelectedRowIndexes(cachedSelectedNightSongs);
guiNight.setSelectedIndex(cachedSelectedNightSongDummy);
playListName.setText(cachedPlayListName);
guiStatusList.addAll(cachedGuiStatusList);
guiStatusList.scrollToEnd();
updateSongCountStatus();
guiPlayList.resetScroll();
guiFileList.resetScroll();
}
private void updateState()
{
cachedPlayListGuiList.clear();
cachedPlayListGuiList.addAll(guiPlayList.getList());
cachedSelectedPlayListIndex = guiPlayList.getSelectedIndex();
cachedSelectedSongs.clear();
cachedSelectedSongs.addAll(guiFileList.getSelectedRowIndexes());
cachedSelectedFileDummy = guiFileList.getSelectedIndex();
cachedSelectedDaySongs.clear();
cachedSelectedDaySongs.addAll(guiDay.getSelectedRowIndexes());
cachedDayList.clear();
cachedDayList.addAll(guiDay.getList());
cachedSelectedDaySongDummy = guiDay.getSelectedIndex();
cachedSelectedNightSongs.clear();
cachedSelectedNightSongs.addAll(guiNight.getSelectedRowIndexes());
cachedNightList.clear();
cachedNightList.addAll(guiNight.getList());
cachedSelectedNightSongDummy = guiNight.getSelectedIndex();
cachedPlayListName = playListName.getText();
cachedGuiStatusList.clear();
cachedGuiStatusList.addAll(guiStatusList.getList());
buttonToServer.enabled = !(playListName.getText().equals("") ||
!globalMatcher(patternPlaylistName, playListName.getText()) ||
(guiDay.isEmpty() && guiNight.isEmpty() || uploading));
//updateSongCountStatus();
isStateCached = true;
}
private boolean globalMatcher(Pattern pattern, String string)
{
int result = 0;
Matcher matcher = pattern.matcher(string);
while(matcher.find())
result++;
return result == 0;
}
private void updateSongCountStatus()
{
//updateStatus(String.format("Selected Song Count: %s", guiFileList.getSelectedRowsCount()));
}
private void updateStatus(String message)
{
Date dateNow = new Date();
String now = timeInstance.format(dateNow);
guiStatusList.add(new TextComponentString(TextFormatting.GRAY + now + "> " + TextFormatting.RESET + message));
guiStatusList.scrollToEnd();
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks)
{
drawDefaultBackground();
titleLabel.drawLabel(mc, mouseX, mouseY);
guiFileList.drawScreen(mouseX, mouseY, partialTicks);
guiPlayList.drawScreen(mouseX, mouseY, partialTicks);
guiDay.drawScreen(mouseX, mouseY, partialTicks);
guiNight.drawScreen(mouseX, mouseY, partialTicks);
playListName.drawTextBox();
guiStatusList.drawScreen(mouseX, mouseY, partialTicks);
super.drawScreen(mouseX, mouseY, partialTicks);
}
@Override
public void updateScreen()
{
Keyboard.enableRepeatEvents(playListName.isFocused());
}
@Override
public boolean doesGuiPauseGame()
{
return false;
}
@Override
protected void actionPerformed(GuiButton button) throws IOException
{
if (!button.enabled) return;
switch (button.id)
{
case 0:
// Open Music Library
mc.displayGuiScreen(new GuiMusicLibrary(this));
break;
case 1:
// Done
for (SongProxy songProxy : guiDay)
if (songProxy != null)
ModLogger.debug("Day Song guid: %s, Title: %s", songProxy.getGUID().toString(), songProxy.getTitle());
for (SongProxy songProxy : guiNight)
if (songProxy != null)
ModLogger.debug("Night Song guid: %s, Title: %s", songProxy.getGUID().toString(), songProxy.getTitle());
mc.displayGuiScreen(null);
break;
case 2:
// to Day
guiDay.addAll(pathsToSongProxies(guiFileList.getSelectedRows(), guiDay.getList()));
break;
case 3:
// to Night
guiNight.addAll(pathsToSongProxies(guiFileList.getSelectedRows(), guiNight.getList()));
break;
case 4:
// delete Day
guiDay.deleteSelectedRows();
break;
case 5:
// delete Night
guiNight.deleteSelectedRows();
break;
case 6:
// send to Server
shipIt();
break;
default:
}
updateState();
super.actionPerformed(button);
}
@Override
protected void keyTyped(char typedChar, int keyCode) throws IOException
{
if (keyCode != Keyboard.KEY_TAB)
playListName.textboxKeyTyped(typedChar, keyCode);
updateState();
super.keyTyped(typedChar, keyCode);
}
@Override
public void onResize(@Nonnull Minecraft mcIn, int w, int h)
{
super.onResize(mcIn, w, h);
updateState();
}
@Override
protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException
{
playListName.mouseClicked(mouseX, mouseY, mouseButton);
super.mouseClicked(mouseX, mouseY, mouseButton);
}
@Override
public void handleMouseInput() throws IOException
{
int mouseX = Mouse.getEventX() * width / mc.displayWidth;
int mouseY = height - Mouse.getEventY() * height / mc.displayHeight - 1;
guiPlayList.handleMouseInput(mouseX, mouseY);
guiFileList.handleMouseInput(mouseX, mouseY);
guiStatusList.handleMouseInput(mouseX, mouseY);
guiDay.handleMouseInput(mouseX, mouseY);
guiNight.handleMouseInput(mouseX, mouseY);
super.handleMouseInput();
}
// This is experimental and inefficient
private void initFileList()
{
new Thread(
() ->
{
pathSongProxyBiMap.clear();
pathSongGuidBiMap.clear();
Path pathDir = FileHelper.getDirectory(FileHelper.CLIENT_LIB_FOLDER, Side.CLIENT);
PathMatcher filter = FileHelper.getMxtMatcher(pathDir);
try (Stream<Path> paths = Files.list(pathDir))
{
cachedFileList = paths
.filter(filter::matches)
.collect(Collectors.toList());
} catch (NullPointerException | IOException e)
{
ModLogger.error(e);
}
List<Path> files = new ArrayList<>();
for (Path file : cachedFileList)
{
files.add(file);
SongProxy songProxy = pathToSongProxy(file);
if (songProxy != null)
{
pathSongProxyBiMap.forcePut(file, songProxy);
pathSongGuidBiMap.forcePut(file, songProxy.getGUID());
}
else
throw new MXTuneRuntimeException("soundProxy Unexpected NULL in initFileList");
}
cachedFileList = files;
guiFileList.clear();
guiFileList.addAll(files);
songProxyPathBiMap = pathSongProxyBiMap.inverse();
songGuidPathBiMap = pathSongGuidBiMap.inverse();
}).start();
}
@Nullable
private SongProxy pathToSongProxy(Path path)
{
MXTuneFile mxTuneFile = MXTuneFileHelper.getMXTuneFile(path);
if (mxTuneFile != null)
return MXTuneFileHelper.getSongProxy(mxTuneFile);
else
ModLogger.warn("mxt file is missing or corrupt");
return null;
}
@Nullable
private Song pathToSong(Path path)
{
MXTuneFile mxTuneFile = MXTuneFileHelper.getMXTuneFile(path);
if (mxTuneFile != null)
return MXTuneFileHelper.getSong(mxTuneFile);
else
ModLogger.warn("mxt file is missing or corrupt");
return null;
}
// So crude: add unique songs only
private List<SongProxy> pathsToSongProxies(List<Path> paths, List<SongProxy> current)
{
List<SongProxy> songList = new ArrayList<>(current);
for (Path path : paths)
{
SongProxy songProxyPath = pathSongProxyBiMap.get(path);
if (!songList.contains(songProxyPath))
songList.add(songProxyPath);
}
current.clear();
return SONG_PROXY_ORDERING.sortedCopy(songList);
}
private void shipIt()
{
// TODO: push <-> status need to be created
uploading = true;
playListName.setText(playListName.getText().trim());
Area area = new Area(playListName.getText(), guiDay.getList(), guiNight.getList());
updateStatus(TextFormatting.GOLD + String.format("Upload Playlist: %s", TextFormatting.RESET + playListName.getText().trim()));
PacketDispatcher.sendToServer(new SetServerSerializedDataMessage(area.getGUID(), SetServerSerializedDataMessage.SetType.AREA, area));
// Build one list of songs to send from both lists to remove duplicates!
List<SongProxy> proxyMap = new ArrayList<>(guiDay.getList());
for (SongProxy songProxy : guiNight.getList())
{
if (!proxyMap.contains(songProxy))
proxyMap.add(songProxy);
}
new Thread ( () ->
{
int count = 0;
for (SongProxy songProxy : proxyMap)
{
count++;
if (songProxy != null)
{
Song song = pathToSong(songGuidPathBiMap.get(songProxy.getGUID()));
if (song != null)
{
PacketDispatcher.sendToServer(new SetServerSerializedDataMessage(songProxy.getGUID(), SetServerSerializedDataMessage.SetType.MUSIC, song));
updateStatus(TextFormatting.DARK_GREEN + String.format("Uploading %s of %s: %s", String.format("%03d", count), String.format("%03d", proxyMap.size()), TextFormatting.RESET + song.getTitle()));
} else
{
updateStatus(String.format(TextFormatting.DARK_RED + "Song not found in library! %s of %s: %s", String.format("%03d", count), String.format("%03d", proxyMap.size()), TextFormatting.RESET + songProxy.getTitle()));
}
try
{
Thread.sleep(1000);
} catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
}
}
uploading = false;
updateState();
}).start();
// done
initAreas();
updateState();
}
private void initAreas()
{
PacketDispatcher.sendToServer(new GetAreasMessage(CallBackManager.register(ClientFileManager.INSTANCE)));
new Thread(() ->
{
try
{
Thread.sleep(1000);
} catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
guiPlayList.clear();
guiPlayList.addAll(PLAYLIST_ORDERING.sortedCopy(ClientFileManager.getAreas()));
updateState();
}).start();
}
private void showSelectedPlaylistsPlaylists(Area selectedArea)
{
if (selectedArea != null)
{
if (!Reference.NO_MUSIC_GUID.equals(selectedArea.getGUID()) && !Reference.EMPTY_GUID.equals(selectedArea.getGUID()))
playListName.setText(ModGuiUtils.getPlaylistName(selectedArea));
else
playListName.setText("");
guiDay.clear();
guiNight.clear();
guiDay.addAll(SONG_PROXY_ORDERING.sortedCopy(selectedArea.getPlayListDay()));
guiNight.addAll(SONG_PROXY_ORDERING.sortedCopy(selectedArea.getPlayListNight()));
cachedSelectedDaySongs.clear();
cachedSelectedNightSongs.clear();
updateState();
}
}
private void updatePlayersSelectedAreaGuid(Area selectedArea)
{
ModLogger.debug("GuiTest: guidSelectedArea: %s", selectedArea != null ? selectedArea.getName() : "[null]");
ModLogger.debug("GuiTest: selected Name : %s", selectedArea != null ? selectedArea.getName() : "[null]");
if (selectedArea != null)
{
PacketDispatcher.sendToServer(new PlayerSelectedAreaMessage(selectedArea.getGUID()));
String areaNameOrUndefined = selectedArea.getName().trim().equals("") ? I18n.format("mxtune.info.playlist.null_playlist") : selectedArea.getName();
updateStatus(String.format(TextFormatting.GOLD + "Updated StaffOfMusic Playlist to: %s", TextFormatting.RESET + areaNameOrUndefined));
}
else
{
updateStatus(TextFormatting.DARK_RED + "Failed to Update StaffOfMusic Playlist!");
}
}
} | src/main/java/net/aeronica/mods/mxtune/gui/mml/GuiPlaylistManager.java | /*
* Aeronica's mxTune MOD
* Copyright 2019, Paul Boese a.k.a. Aeronica
*
* 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 net.aeronica.mods.mxtune.gui.mml;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import net.aeronica.mods.mxtune.Reference;
import net.aeronica.mods.mxtune.caches.FileHelper;
import net.aeronica.mods.mxtune.caches.MXTuneFile;
import net.aeronica.mods.mxtune.caches.MXTuneFileHelper;
import net.aeronica.mods.mxtune.gui.util.GuiScrollingListOf;
import net.aeronica.mods.mxtune.gui.util.GuiScrollingMultiListOf;
import net.aeronica.mods.mxtune.gui.util.ModGuiUtils;
import net.aeronica.mods.mxtune.managers.ClientFileManager;
import net.aeronica.mods.mxtune.managers.records.Area;
import net.aeronica.mods.mxtune.managers.records.Song;
import net.aeronica.mods.mxtune.managers.records.SongProxy;
import net.aeronica.mods.mxtune.network.PacketDispatcher;
import net.aeronica.mods.mxtune.network.bidirectional.GetAreasMessage;
import net.aeronica.mods.mxtune.network.bidirectional.SetServerSerializedDataMessage;
import net.aeronica.mods.mxtune.network.server.PlayerSelectedAreaMessage;
import net.aeronica.mods.mxtune.util.CallBackManager;
import net.aeronica.mods.mxtune.util.MXTuneRuntimeException;
import net.aeronica.mods.mxtune.util.ModLogger;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiLabel;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiTextField;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.resources.I18n;
import net.minecraftforge.fml.relauncher.Side;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static net.aeronica.mods.mxtune.gui.mml.SortHelper.PLAYLIST_ORDERING;
import static net.aeronica.mods.mxtune.gui.mml.SortHelper.SONG_PROXY_ORDERING;
public class GuiPlaylistManager extends GuiScreen
{
private static final String TITLE = I18n.format("mxtune.gui.guiAreaManager.title");
// Song Multi Selector
private GuiScrollingMultiListOf<Path> guiFileList;
private List<Path> cachedFileList = new ArrayList<>();
private Set<Integer> cachedSelectedSongs = new HashSet<>();
private int cachedSelectedFileDummy = -1;
// Playlist Selector
private GuiScrollingListOf<Area> guiAreaList;
private List<Area> cachedAreaGuiList = new ArrayList<>();
private int cachedSelectedAreaIndex = -1;
// PlayList Day
private GuiScrollingMultiListOf<SongProxy> guiDay;
private List<SongProxy> cachedDayList = new ArrayList<>();
private Set<Integer> cachedSelectedDaySongs = new HashSet<>();
private int cachedSelectedDaySongDummy = -1;
// PlayList Night
private GuiScrollingMultiListOf<SongProxy> guiNight;
private List<SongProxy> cachedNightList = new ArrayList<>();
private Set<Integer> cachedSelectedNightSongs = new HashSet<>();
private int cachedSelectedNightSongDummy = -1;
// Area
private GuiTextField areaName;
private String cachedAreaName = "";
// Status
private GuiTextField status;
// Misc
private GuiLabel titleLabel;
private boolean cacheKeyRepeatState;
private boolean isStateCached;
private GuiButton buttonToServer;
private Pattern patternPlaylistName = Pattern.compile("^\\s+|\\s+$|^\\[");
// Uploading
private boolean uploading = false;
// Mapping
private BiMap<Path, SongProxy> pathSongProxyBiMap = HashBiMap.create();
private BiMap<SongProxy, Path> songProxyPathBiMap;
// TODO: Finnish updating string to use the lang file.
public GuiPlaylistManager()
{
cacheKeyRepeatState = Keyboard.areRepeatEventsEnabled();
Keyboard.enableRepeatEvents(false);
initFileList();
}
@Override
public void onGuiClosed()
{
Keyboard.enableRepeatEvents(cacheKeyRepeatState);
}
@Override
public void initGui()
{
int guiAreaListWidth = Math.min(Math.max((width - 15) / 3, 100), 400);
int guiFileListWidth = guiAreaListWidth;
int singleLineHeight = mc.fontRenderer.FONT_HEIGHT + 2;
int entryAreaHeight = singleLineHeight;
int padding = 5;
int titleTop = padding;
int left = padding;
int titleWidth = fontRenderer.getStringWidth(I18n.format("mxtune.gui.guiAreaManager.title"));
int titleX = (width / 2) - (titleWidth / 2);
int titleHeight = singleLineHeight + 2;
int statusHeight = singleLineHeight + 2;
int entryFileHeight = singleLineHeight;
int listTop = titleTop + titleHeight;
int fileListBottom = Math.max(height - statusHeight - listTop - titleHeight - padding, entryAreaHeight * 9);
int fileListHeight = Math.max(fileListBottom - listTop, singleLineHeight);
int statusTop = fileListBottom + padding;
int thirdsHeight = ((statusTop - listTop) / 3) - padding;
int areaListHeight = Math.max(thirdsHeight, entryAreaHeight);
int areaBottom = listTop + areaListHeight;
int dayTop = areaBottom + padding;
int dayBottom = dayTop + areaListHeight;
int nightTop = dayBottom + padding;
int nightBottom = nightTop + areaListHeight;
titleLabel = new GuiLabel(fontRenderer, 0, titleX, titleTop, titleWidth, singleLineHeight, 0xFFFFFF );
titleLabel.addLine(TITLE);
guiFileList = new GuiScrollingMultiListOf<Path>(this, entryFileHeight, guiFileListWidth, fileListHeight,listTop, fileListBottom, left)
{
@Override
protected void drawSlot(int slotIdx, int entryRight, int slotTop, int slotBuffer, float scrollDistance, Tessellator tess)
{
// get the filename and remove the '.mxt' extension
Path entry = get(slotIdx);
if (entry != null)
{
String name = entry.getFileName().toString().replaceAll("\\.[mM][xX][tT]$", "");
String trimmedName = fontRenderer.trimStringToWidth(name, listWidth - 10);
int color = selectedRowIndexes.contains(slotIdx) ? 0xFFFF00 : 0xADD8E6;
fontRenderer.drawStringWithShadow(trimmedName, (float) left + 3, slotTop, color);
} else
{
String name = "---NULL---";
String trimmedName = fontRenderer.trimStringToWidth(name, listWidth - 10);
int color = 0xFF0000;
fontRenderer.drawStringWithShadow(trimmedName, (float) left + 3, slotTop, color);
}
}
@Override
protected void selectedClickedCallback(int selectedIndex)
{
super.selectedClickedCallback(selectedIndex);
updateSongCountStatus();
}
};
guiAreaList = new GuiScrollingListOf<Area>(this, entryAreaHeight, guiAreaListWidth, areaListHeight, listTop, areaBottom, width - guiAreaListWidth - padding)
{
@Override
protected void drawSlot(int slotIdx, int entryRight, int slotTop, int slotBuffer, Tessellator tess)
{
Area area = get(slotIdx);
if (area != null)
{
String playlistName = ModGuiUtils.getPlaylistName(area);
String trimmedName = fontRenderer.trimStringToWidth(playlistName, listWidth - 10);
int color = isSelected(slotIdx) ? 0xFFFF00 : 0xAADDEE;
fontRenderer.drawStringWithShadow(trimmedName, (float) left + 3, slotTop, color);
} else
{
String name = "---GUID Conflict---";
String trimmedName = fontRenderer.trimStringToWidth(name, listWidth - 10);
int color = 0xFF0000;
fontRenderer.drawStringWithShadow(trimmedName, (float) left + 3, slotTop, color);
}
}
@Override
protected void selectedClickedCallback(int selectedIndex)
{
showSelectedPlaylistsPlaylists(guiAreaList.get(selectedIndex));
}
@Override
protected void selectedDoubleClickedCallback(int selectedIndex)
{
updatePlayersSelectedAreaGuid(guiAreaList.get(selectedIndex));
}
};
guiDay = new GuiScrollingMultiListOf<SongProxy>(this, singleLineHeight, guiAreaListWidth, areaListHeight ,dayTop, dayBottom, width - guiAreaListWidth - padding)
{
@Override
protected void drawSlot(int slotIdx, int entryRight, int slotTop, int slotBuffer, float scrollDistance, Tessellator tess)
{
drawSlotCommon(this, slotIdx, slotTop, listWidth, left);
}
};
guiNight = new GuiScrollingMultiListOf<SongProxy>(this, singleLineHeight, guiAreaListWidth, areaListHeight, nightTop, nightBottom, width - guiAreaListWidth - padding)
{
@Override
protected void drawSlot(int slotIdx, int entryRight, int slotTop, int slotBuffer, float scrollDistance, Tessellator tess)
{
drawSlotCommon(this, slotIdx, slotTop, listWidth, left);
}
};
status = new GuiTextField(0, fontRenderer, left, statusTop, width - padding * 2, singleLineHeight + 2);
status.setMaxStringLength(256);
int buttonWidth = 80;
int buttonTop = height - 22;
int xLibrary = (this.width /2) - buttonWidth;
int xDone = xLibrary + buttonWidth;
GuiButton buttonImport = new GuiButton(0, xLibrary, buttonTop, buttonWidth, 20, I18n.format("mxtune.gui.button.musicLibrary"));
GuiButton buttonDone = new GuiButton(1, xDone, buttonTop, buttonWidth, 20, I18n.format("gui.done"));
int selectButtonWidth = guiFileListWidth - 10;
int selectButtonLeft = guiFileList.getRight() + 8;
areaName = new GuiTextField(1, fontRenderer, selectButtonLeft, listTop, selectButtonWidth, singleLineHeight + 2);
buttonToServer = new GuiButton(6, selectButtonLeft, areaName.y + areaName.height + padding, selectButtonWidth, 20, "Send to Server");
GuiButton buttonToDay = new GuiButton(2, selectButtonLeft, dayTop + padding, selectButtonWidth, 20, "To Day List ->");
GuiButton buttonToNight = new GuiButton(3, selectButtonLeft, nightTop + padding, selectButtonWidth, 20, "To Night List ->");
GuiButton buttonDDeleteDay = new GuiButton(4, selectButtonLeft, buttonToDay.y + buttonToDay.height + padding, selectButtonWidth, 20, "Delete");
GuiButton buttonDDeleteNight = new GuiButton(5, selectButtonLeft, buttonToNight.y + buttonToNight.height + padding, selectButtonWidth, 20, "Delete");
buttonList.add(buttonImport);
buttonList.add(buttonDone);
buttonList.add(buttonToDay);
buttonList.add(buttonToNight);
buttonList.add(buttonDDeleteDay);
buttonList.add(buttonDDeleteNight);
buttonList.add(buttonToServer);
initAreas();
reloadState();
}
private <T extends GuiScrollingMultiListOf<SongProxy>> void drawSlotCommon(T parent, int slotIdx, int slotTop, int listWidth, int left)
{
SongProxy entry = parent.get(slotIdx);
if (entry != null)
{
String name = entry.getTitle();
String trimmedName = fontRenderer.trimStringToWidth(name, listWidth - 10);
int color = parent.getSelectedRowIndexes().contains(slotIdx) ? 0xFFFF00 : 0xADD8E6;
fontRenderer.drawStringWithShadow(trimmedName, (float) left + 3, slotTop, color);
} else
{
String name = "---GUID Conflict---";
String trimmedName = fontRenderer.trimStringToWidth(name, listWidth - 10);
int color = 0xFF0000;
fontRenderer.drawStringWithShadow(trimmedName, (float) left + 3, slotTop, color);
}
}
private void reloadState()
{
if (!isStateCached) return;
guiAreaList.addAll(cachedAreaGuiList);
guiAreaList.setSelectedIndex(cachedSelectedAreaIndex);
guiFileList.addAll(cachedFileList);
guiFileList.setSelectedRowIndexes(cachedSelectedSongs);
guiFileList.setSelectedIndex(cachedSelectedFileDummy);
guiDay.addAll(cachedDayList);
guiDay.setSelectedRowIndexes(cachedSelectedDaySongs);
guiDay.setSelectedIndex(cachedSelectedDaySongDummy);
guiNight.addAll(cachedNightList);
guiNight.setSelectedRowIndexes(cachedSelectedNightSongs);
guiNight.setSelectedIndex(cachedSelectedNightSongDummy);
areaName.setText(cachedAreaName);
updateSongCountStatus();
guiAreaList.resetScroll();
guiFileList.resetScroll();
}
private void updateState()
{
cachedAreaGuiList.clear();
cachedAreaGuiList.addAll(guiAreaList.getList());
cachedSelectedAreaIndex = guiAreaList.getSelectedIndex();
cachedSelectedSongs.clear();
cachedSelectedSongs.addAll(guiFileList.getSelectedRowIndexes());
cachedSelectedFileDummy = guiFileList.getSelectedIndex();
cachedSelectedDaySongs.clear();
cachedSelectedDaySongs.addAll(guiDay.getSelectedRowIndexes());
cachedDayList.clear();
cachedDayList.addAll(guiDay.getList());
cachedSelectedDaySongDummy = guiDay.getSelectedIndex();
cachedSelectedNightSongs.clear();
cachedSelectedNightSongs.addAll(guiNight.getSelectedRowIndexes());
cachedNightList.clear();
cachedNightList.addAll(guiNight.getList());
cachedSelectedNightSongDummy = guiNight.getSelectedIndex();
cachedAreaName = areaName.getText();
buttonToServer.enabled = !(areaName.getText().equals("") ||
!globalMatcher(patternPlaylistName, areaName.getText()) ||
(guiDay.isEmpty() && guiNight.isEmpty() || uploading));
//updateSongCountStatus();
isStateCached = true;
}
private boolean globalMatcher(Pattern pattern, String string)
{
int result = 0;
Matcher matcher = pattern.matcher(string);
while(matcher.find())
result++;
return result == 0;
}
private void updateSongCountStatus()
{
status.setText(String.format("Selected Song Count: %s", guiFileList.getSelectedRowsCount()));
}
private void updateStatus(String message)
{
status.setText(message);
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks)
{
drawDefaultBackground();
titleLabel.drawLabel(mc, mouseX, mouseY);
guiFileList.drawScreen(mouseX, mouseY, partialTicks);
guiAreaList.drawScreen(mouseX, mouseY, partialTicks);
guiDay.drawScreen(mouseX, mouseY, partialTicks);
guiNight.drawScreen(mouseX, mouseY, partialTicks);
areaName.drawTextBox();
status.drawTextBox();
super.drawScreen(mouseX, mouseY, partialTicks);
}
@Override
public void updateScreen()
{
Keyboard.enableRepeatEvents(areaName.isFocused());
}
@Override
public boolean doesGuiPauseGame()
{
return false;
}
@Override
protected void actionPerformed(GuiButton button) throws IOException
{
if (!button.enabled) return;
switch (button.id)
{
case 0:
mc.displayGuiScreen(new GuiMusicLibrary(this));
break;
case 1:
for (SongProxy songProxy : guiDay)
if (songProxy != null)
ModLogger.debug("Day Song guid: %s, Title: %s", songProxy.getGUID().toString(), songProxy.getTitle());
for (SongProxy songProxy : guiNight)
if (songProxy != null)
ModLogger.debug("Night Song guid: %s, Title: %s", songProxy.getGUID().toString(), songProxy.getTitle());
mc.displayGuiScreen(null);
break;
case 2:
// to Day
guiDay.addAll(pathsToSongProxies(guiFileList.getSelectedRows(), guiDay.getList()));
break;
case 3:
// to Night
guiNight.addAll(pathsToSongProxies(guiFileList.getSelectedRows(), guiNight.getList()));
break;
case 4:
// delete Day
guiDay.deleteSelectedRows();
break;
case 5:
// delete Night
guiNight.deleteSelectedRows();
break;
case 6:
// send to Server
shipIt();
break;
default:
}
updateState();
super.actionPerformed(button);
}
@Override
protected void keyTyped(char typedChar, int keyCode) throws IOException
{
if (!(keyCode == Keyboard.KEY_TAB))
areaName.textboxKeyTyped(typedChar, keyCode);
updateState();
super.keyTyped(typedChar, keyCode);
}
@Override
public void onResize(@Nonnull Minecraft mcIn, int w, int h)
{
super.onResize(mcIn, w, h);
updateState();
}
@Override
protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException
{
areaName.mouseClicked(mouseX, mouseY, mouseButton);
super.mouseClicked(mouseX, mouseY, mouseButton);
}
@Override
public void handleMouseInput() throws IOException
{
int mouseX = Mouse.getEventX() * width / mc.displayWidth;
int mouseY = height - Mouse.getEventY() * height / mc.displayHeight - 1;
guiAreaList.handleMouseInput(mouseX, mouseY);
guiFileList.handleMouseInput(mouseX, mouseY);
guiDay.handleMouseInput(mouseX, mouseY);
guiNight.handleMouseInput(mouseX, mouseY);
super.handleMouseInput();
}
// This is experimental and inefficient
private void initFileList()
{
new Thread(
() ->
{
pathSongProxyBiMap.clear();
Path pathDir = FileHelper.getDirectory(FileHelper.CLIENT_LIB_FOLDER, Side.CLIENT);
PathMatcher filter = FileHelper.getMxtMatcher(pathDir);
try (Stream<Path> paths = Files.list(pathDir))
{
cachedFileList = paths
.filter(filter::matches)
.collect(Collectors.toList());
} catch (NullPointerException | IOException e)
{
ModLogger.error(e);
}
List<Path> files = new ArrayList<>();
for (Path file : cachedFileList)
{
files.add(file);
SongProxy songProxy = pathToSongProxy(file);
if (songProxy != null)
pathSongProxyBiMap.forcePut(file, songProxy);
else
throw new MXTuneRuntimeException("soundProxy Unexpected NULL in initFileList");
}
cachedFileList = files;
guiFileList.clear();
guiFileList.addAll(files);
songProxyPathBiMap = pathSongProxyBiMap.inverse();
}).start();
}
@Nullable
private SongProxy pathToSongProxy(Path path)
{
MXTuneFile mxTuneFile = MXTuneFileHelper.getMXTuneFile(path);
if (mxTuneFile != null)
return MXTuneFileHelper.getSongProxy(mxTuneFile);
else
ModLogger.warn("mxt file is missing or corrupt");
return null;
}
private Song pathToSong(Path path)
{
MXTuneFile mxTuneFile = MXTuneFileHelper.getMXTuneFile(path);
if (mxTuneFile != null)
return MXTuneFileHelper.getSong(mxTuneFile);
else
ModLogger.warn("mxt file is missing or corrupt");
// The EMPTY SongProxy
return new Song();
}
// So crude: add unique songs only
private List<SongProxy> pathsToSongProxies(List<Path> paths, List<SongProxy> current)
{
List<SongProxy> songList = new ArrayList<>(current);
for (Path path : paths)
{
SongProxy songProxyPath = pathSongProxyBiMap.get(path);
if (!songList.contains(songProxyPath))
songList.add(songProxyPath);
}
current.clear();
return SONG_PROXY_ORDERING.sortedCopy(songList);
}
private void shipIt()
{
// TODO: push <-> status need to be created
uploading = true;
areaName.setText(areaName.getText().trim());
Area area = new Area(areaName.getText(), guiDay.getList(), guiNight.getList());
PacketDispatcher.sendToServer(new SetServerSerializedDataMessage(area.getGUID(), SetServerSerializedDataMessage.SetType.AREA, area));
// Build one list of songs to send from both lists to remove duplicates!
List<SongProxy> proxyMap = new ArrayList<>(guiDay.getList());
for (SongProxy songProxy : guiNight.getList())
{
if (!proxyMap.contains(songProxy))
proxyMap.add(songProxy);
}
new Thread ( () ->
{
int count = 0;
for (SongProxy songProxy : proxyMap)
{
count++;
if (songProxy != null)
{
Song song = pathToSong(songProxyPathBiMap.get(songProxy));
PacketDispatcher.sendToServer(new SetServerSerializedDataMessage(songProxy.getGUID(), SetServerSerializedDataMessage.SetType.MUSIC, song));
updateStatus(String.format("Uploading %s of %s: %s", String.format("%03d", count), String.format("%03d",proxyMap.size()), song.getTitle()));
try
{
Thread.sleep(1000);
} catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
}
}
uploading = false;
updateState();
}).start();
// done
initAreas();
updateState();
}
private void initAreas()
{
PacketDispatcher.sendToServer(new GetAreasMessage(CallBackManager.register(ClientFileManager.INSTANCE)));
new Thread(() ->
{
try
{
Thread.sleep(1000);
} catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
guiAreaList.clear();
guiAreaList.addAll(PLAYLIST_ORDERING.sortedCopy(ClientFileManager.getAreas()));
updateState();
}).start();
}
private void showSelectedPlaylistsPlaylists(Area selectedArea)
{
if (selectedArea != null)
{
if (!Reference.NO_MUSIC_GUID.equals(selectedArea.getGUID()) && !Reference.EMPTY_GUID.equals(selectedArea.getGUID()))
areaName.setText(ModGuiUtils.getPlaylistName(selectedArea));
else
areaName.setText("");
guiDay.clear();
guiNight.clear();
guiDay.addAll(SONG_PROXY_ORDERING.sortedCopy(selectedArea.getPlayListDay()));
guiNight.addAll(SONG_PROXY_ORDERING.sortedCopy(selectedArea.getPlayListNight()));
cachedSelectedDaySongs.clear();
cachedSelectedNightSongs.clear();
updateState();
}
}
private void updatePlayersSelectedAreaGuid(Area selectedArea)
{
ModLogger.debug("GuiTest: guidSelectedArea: %s", selectedArea != null ? selectedArea.getName() : "[null]");
ModLogger.debug("GuiTest: selected Name : %s", selectedArea != null ? selectedArea.getName() : "[null]");
if (selectedArea != null)
{
PacketDispatcher.sendToServer(new PlayerSelectedAreaMessage(selectedArea.getGUID()));
String areaNameOrUndefined = selectedArea.getName().trim().equals("") ? I18n.format("mxtune.info.playlist.null_playlist") : selectedArea.getName();
updateStatus(String.format("Updated StaffOfMusic Area to: %s", areaNameOrUndefined));
}
else
{
updateStatus("Failed to Update StaffOfMusic Area!");
}
}
} | Status logging improvements, comments, and a lax attempt at mapping
mxt path to song guid to keep things straight.
| src/main/java/net/aeronica/mods/mxtune/gui/mml/GuiPlaylistManager.java | Status logging improvements, comments, and a lax attempt at mapping mxt path to song guid to keep things straight. |
|
Java | apache-2.0 | 7772b753fdd2083bc9075d9d18418ac7a50e8368 | 0 | nogalavi/Bikeable,nogalavi/Bikeable | package com.nnys.bikeable;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.StrictMode;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageButton;
import android.widget.ImageView;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
// Activity was brought to front and not created,
// Thus finishing this will get us to the last viewed activity
finish();
return;
}
setContentView(R.layout.activity_main);
ImageView img = (ImageView)findViewById(R.id.bike_animation_image);
img.setBackgroundResource(R.drawable.bike_anim);
AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground();
frameAnimation.start();
// to enable getting data from Tel Aviv muni website
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// get iria data
try {
IriaData.getIriaData();
IriaData.isDataReceived = true;
} catch (IOException e) {
IriaData.isDataReceived = false;
e.printStackTrace();
} catch (XmlPullParserException e) {
IriaData.isDataReceived = false;
e.printStackTrace();
}
Log.i("INFO:", "Data from iria is OK");
// button.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// Execute some code after 2 seconds have passed
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Intent intent = new Intent(MainActivity.this, CentralActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
return;
}
}, 2000);
}
}
| app/src/main/java/com/nnys/bikeable/MainActivity.java | package com.nnys.bikeable;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.StrictMode;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageButton;
import android.widget.ImageView;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
// Activity was brought to front and not created,
// Thus finishing this will get us to the last viewed activity
finish();
return;
}
setContentView(R.layout.activity_main);
//ImageView img = (ImageView)findViewById(R.id.bike_animation_image);
//img.setBackgroundResource(R.drawable.bike_anim);
//AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground();
//frameAnimation.start();
// to enable getting data from Tel Aviv muni website
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// get iria data
try {
IriaData.getIriaData();
IriaData.isDataReceived = true;
} catch (IOException e) {
IriaData.isDataReceived = false;
e.printStackTrace();
} catch (XmlPullParserException e) {
IriaData.isDataReceived = false;
e.printStackTrace();
}
Log.i("INFO:", "Data from iria is OK");
// button.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// Execute some code after 2 seconds have passed
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Intent intent = new Intent(MainActivity.this, CentralActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
return;
}
}, 2000);
}
}
| restored frame animation
| app/src/main/java/com/nnys/bikeable/MainActivity.java | restored frame animation |
|
Java | apache-2.0 | 584a024f93160717c407502123eed2a2e671f577 | 0 | MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim | package graph;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import org.apache.batik.dom.*;
import org.apache.batik.svggen.*;
import org.jfree.chart.*;
import org.jfree.chart.axis.*;
import org.jfree.chart.event.*;
import org.jfree.chart.plot.*;
import org.jfree.chart.renderer.category.*;
import org.jfree.chart.renderer.xy.*;
import org.jfree.data.category.*;
import org.jfree.data.xy.*;
import org.jibble.epsgraphics.EpsGraphics2D;
import org.w3c.dom.*;
import com.lowagie.text.Document;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.*;
import biomodelsim.*;
import buttons.*;
/**
* This is the Graph class. It takes in data and draws a graph of that data. The
* Graph class implements the ActionListener class, the ChartProgressListener
* class, and the MouseListener class. This allows the Graph class to perform
* actions when buttons are pressed, when the chart is drawn, or when the chart
* is clicked.
*
* @author Curtis Madsen
*/
public class Graph extends JPanel implements ActionListener, MouseListener, ChartProgressListener {
private static final long serialVersionUID = 4350596002373546900L;
private JFreeChart chart; // Graph of the output data
private XYSeriesCollection curData; // Data in the current graph
private String outDir; // output directory
private String printer_id; // printer id
/*
* Text fields used to change the graph window
*/
private JTextField XMin, XMax, XScale, YMin, YMax, YScale;
private ArrayList<String> graphSpecies; // names of species in the graph
private String savedPics; // directory for saved pictures
private BioSim biomodelsim; // tstubd gui
private JButton save;
private JButton export; // buttons
// private JButton exportJPeg, exportPng, exportPdf, exportEps, exportSvg,
// exportCsv; // buttons
private HashMap<String, Paint> colors;
private HashMap<String, Shape> shapes;
private String selected, lastSelected;
private LinkedList<GraphSpecies> graphed;
private LinkedList<GraphProbs> probGraphed;
private JCheckBox resize;
private Log log;
private ArrayList<JCheckBox> boxes;
private ArrayList<JTextField> series;
private ArrayList<JComboBox> colorsCombo;
private ArrayList<JComboBox> shapesCombo;
private ArrayList<JCheckBox> connected;
private ArrayList<JCheckBox> visible;
private ArrayList<JCheckBox> filled;
private JCheckBox use;
private JCheckBox connectedLabel;
private JCheckBox visibleLabel;
private JCheckBox filledLabel;
private String graphName;
private String separator;
private boolean change;
private boolean timeSeries;
private ArrayList<String> graphProbs;
/**
* Creates a Graph Object from the data given and calls the private graph
* helper method.
*/
public Graph(String printer_track_quantity, String label, String printer_id, String outDir,
String time, BioSim biomodelsim, String open, Log log, String graphName, boolean timeSeries) {
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
// initializes member variables
this.log = log;
this.timeSeries = timeSeries;
if (timeSeries) {
if (graphName != null) {
this.graphName = graphName;
}
else {
this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".grf";
}
}
else {
if (graphName != null) {
this.graphName = graphName;
}
else {
this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".prb";
}
}
this.outDir = outDir;
this.printer_id = printer_id;
this.biomodelsim = biomodelsim;
XYSeriesCollection data = new XYSeriesCollection();
// graph the output data
if (timeSeries) {
setUpShapesAndColors();
graphed = new LinkedList<GraphSpecies>();
selected = "";
lastSelected = "";
graph(printer_track_quantity, label, data, time);
if (open != null) {
open(open);
}
}
else {
setUpShapesAndColors();
probGraphed = new LinkedList<GraphProbs>();
selected = "";
lastSelected = "";
probGraph(label);
if (open != null) {
open(open);
}
}
}
/**
* This private helper method calls the private readData method, sets up a
* graph frame, and graphs the data.
*
* @param dataset
* @param time
*/
private void graph(String printer_track_quantity, String label, XYSeriesCollection dataset,
String time) {
chart = ChartFactory.createXYLineChart(label, time, printer_track_quantity, dataset,
PlotOrientation.VERTICAL, true, true, false);
chart.addProgressListener(this);
ChartPanel graph = new ChartPanel(chart);
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Click here to create graph");
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
graph.addMouseListener(this);
change = false;
// creates text fields for changing the graph's dimensions
resize = new JCheckBox("Auto Resize");
resize.setSelected(true);
XMin = new JTextField();
XMax = new JTextField();
XScale = new JTextField();
YMin = new JTextField();
YMax = new JTextField();
YScale = new JTextField();
// creates the buttons for the graph frame
JPanel ButtonHolder = new JPanel();
save = new JButton("Save Graph");
export = new JButton("Export");
// exportJPeg = new JButton("Export As JPEG");
// exportPng = new JButton("Export As PNG");
// exportPdf = new JButton("Export As PDF");
// exportEps = new JButton("Export As EPS");
// exportSvg = new JButton("Export As SVG");
// exportCsv = new JButton("Export As CSV");
save.addActionListener(this);
export.addActionListener(this);
// exportJPeg.addActionListener(this);
// exportPng.addActionListener(this);
// exportPdf.addActionListener(this);
// exportEps.addActionListener(this);
// exportSvg.addActionListener(this);
// exportCsv.addActionListener(this);
ButtonHolder.add(save);
ButtonHolder.add(export);
// ButtonHolder.add(exportJPeg);
// ButtonHolder.add(exportPng);
// ButtonHolder.add(exportPdf);
// ButtonHolder.add(exportEps);
// ButtonHolder.add(exportSvg);
// ButtonHolder.add(exportCsv);
// puts all the components of the graph gui into a display panel
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, ButtonHolder, null);
splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
this.add(splitPane, "South");
// determines maximum and minimum values and resizes
resize(dataset);
this.revalidate();
}
private void readGraphSpecies(String file, Component component) {
component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
FileInputStream fileInput = new FileInputStream(new File(file));
ProgressMonitorInputStream prog = new ProgressMonitorInputStream(component,
"Reading Reb2sac Output Data From " + new File(file).getName(), fileInput);
InputStream input = new BufferedInputStream(prog);
graphSpecies = new ArrayList<String>();
boolean reading = true;
char cha;
int readCount = 0;
while (reading) {
String word = "";
boolean readWord = true;
while (readWord) {
int read = input.read();
readCount++;
if (read == -1) {
reading = false;
readWord = false;
}
cha = (char) read;
if (Character.isWhitespace(cha)) {
input.mark(3);
char next = (char) input.read();
char after = (char) input.read();
String check = "" + next + after;
if (word.equals("") || word.equals("0") || check.equals("0,")) {
readWord = false;
}
else {
word += cha;
}
input.reset();
}
else if (cha == ',' || cha == ':' || cha == ';' || cha == '\"' || cha == '\''
|| cha == '(' || cha == ')' || cha == '[' || cha == ']') {
readWord = false;
}
else if (read != -1) {
word += cha;
}
}
int getNum;
try {
getNum = Integer.parseInt(word);
if (getNum == 0) {
int read = 0;
while (read != -1) {
read = input.read();
}
}
}
catch (Exception e1) {
if (word.equals("")) {
}
else {
graphSpecies.add(word);
}
}
}
input.close();
prog.close();
fileInput.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(component, "Error Reading Data!"
+ "\nThere was an error reading the simulation output data.", "Error Reading Data",
JOptionPane.ERROR_MESSAGE);
}
component.setCursor(null);
}
/**
* This private helper method parses the output file of ODE, monte carlo, and
* markov abstractions.
*/
private ArrayList<ArrayList<Double>> readData(String file, Component component,
String printer_track_quantity, String label, String directory) {
String[] s = file.split(separator);
String getLast = s[s.length - 1];
String stem = "";
int t = 0;
try {
while (!Character.isDigit(getLast.charAt(t))) {
stem += getLast.charAt(t);
t++;
}
}
catch (Exception e) {
}
if (label.contains("variance")) {
return calculateAverageVarianceDeviation(file, stem, 1, directory);
}
else if (label.contains("deviation")) {
return calculateAverageVarianceDeviation(file, stem, 2, directory);
}
else if (label.contains("average")) {
return calculateAverageVarianceDeviation(file, stem, 0, directory);
}
else {
ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>();
component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
FileInputStream fileInput = new FileInputStream(new File(file));
ProgressMonitorInputStream prog = new ProgressMonitorInputStream(component,
"Reading Reb2sac Output Data From " + new File(file).getName(), fileInput);
InputStream input = new BufferedInputStream(prog);
boolean reading = true;
char cha;
int readCount = 0;
while (reading) {
String word = "";
boolean readWord = true;
while (readWord) {
int read = input.read();
readCount++;
if (read == -1) {
reading = false;
readWord = false;
}
cha = (char) read;
if (Character.isWhitespace(cha)) {
input.mark(3);
char next = (char) input.read();
char after = (char) input.read();
String check = "" + next + after;
if (word.equals("") || word.equals("0") || check.equals("0,")) {
readWord = false;
}
else {
word += cha;
}
input.reset();
}
else if (cha == ',' || cha == ':' || cha == ';' || cha == '!' || cha == '?'
|| cha == '\"' || cha == '\'' || cha == '(' || cha == ')' || cha == '{'
|| cha == '}' || cha == '[' || cha == ']' || cha == '<' || cha == '>' || cha == '*'
|| cha == '=' || cha == '#') {
readWord = false;
}
else if (read != -1) {
word += cha;
}
}
int getNum;
try {
getNum = Integer.parseInt(word);
if (getNum == 0) {
for (int i = 0; i < graphSpecies.size(); i++) {
data.add(new ArrayList<Double>());
}
(data.get(0)).add(0.0);
int counter = 1;
reading = true;
while (reading) {
word = "";
readWord = true;
int read;
while (readWord) {
read = input.read();
cha = (char) read;
while (!Character.isWhitespace(cha) && cha != ',' && cha != ':' && cha != ';'
&& cha != '!' && cha != '?' && cha != '\"' && cha != '\'' && cha != '('
&& cha != ')' && cha != '{' && cha != '}' && cha != '[' && cha != ']'
&& cha != '<' && cha != '>' && cha != '_' && cha != '*' && cha != '='
&& read != -1) {
word += cha;
read = input.read();
cha = (char) read;
}
if (read == -1) {
reading = false;
}
readWord = false;
}
int insert;
if (!word.equals("")) {
if (counter < graphSpecies.size()) {
insert = counter;
}
else {
insert = counter % graphSpecies.size();
}
(data.get(insert)).add(Double.parseDouble(word));
counter++;
}
}
}
}
catch (Exception e1) {
}
}
input.close();
prog.close();
fileInput.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(component, "Error Reading Data!"
+ "\nThere was an error reading the simulation output data.", "Error Reading Data",
JOptionPane.ERROR_MESSAGE);
}
component.setCursor(null);
return data;
}
}
/**
* This method adds and removes plots from the graph depending on what check
* boxes are selected.
*/
public void actionPerformed(ActionEvent e) {
// if the save button is clicked
if (e.getSource() == save) {
save();
}
// if the export button is clicked
else if (e.getSource() == export) {
export();
}
// // if the export as jpeg button is clicked
// else if (e.getSource() == exportJPeg) {
// export(0);
// }
// // if the export as png button is clicked
// else if (e.getSource() == exportPng) {
// export(1);
// }
// // if the export as pdf button is clicked
// else if (e.getSource() == exportPdf) {
// export(2);
// }
// // if the export as eps button is clicked
// else if (e.getSource() == exportEps) {
// export(3);
// }
// // if the export as svg button is clicked
// else if (e.getSource() == exportSvg) {
// export(4);
// } else if (e.getSource() == exportCsv) {
// export(5);
// }
}
/**
* Private method used to auto resize the graph.
*/
private void resize(XYSeriesCollection dataset) {
NumberFormat num = NumberFormat.getInstance();
num.setMaximumFractionDigits(4);
num.setGroupingUsed(false);
XYPlot plot = chart.getXYPlot();
XYItemRenderer rend = plot.getRenderer();
double minY = Double.MAX_VALUE;
double maxY = Double.MIN_VALUE;
double minX = Double.MAX_VALUE;
double maxX = Double.MIN_VALUE;
for (int j = 0; j < dataset.getSeriesCount(); j++) {
XYSeries series = dataset.getSeries(j);
Boolean visible = rend.getSeriesVisible(j);
if (visible == null || visible.equals(true)) {
for (int k = 0; k < series.getItemCount(); k++) {
maxY = Math.max(series.getY(k).doubleValue(), maxY);
minY = Math.min(series.getY(k).doubleValue(), minY);
maxX = Math.max(series.getX(k).doubleValue(), maxX);
minX = Math.min(series.getX(k).doubleValue(), minX);
}
}
}
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
if (minY == Double.MAX_VALUE || maxY == Double.MIN_VALUE) {
axis.setRange(-1, 1);
}
else if ((maxY - minY) < .001) {
axis.setRange(minY - 1, maxY + 1);
}
else {
axis.setRange(Double.parseDouble(num.format(minY - (Math.abs(minY) * .1))), Double
.parseDouble(num.format(maxY + (Math.abs(maxY) * .1))));
}
axis.setAutoTickUnitSelection(true);
axis = (NumberAxis) plot.getDomainAxis();
if (minX == Double.MAX_VALUE || maxX == Double.MIN_VALUE) {
axis.setRange(-1, 1);
}
else if ((maxX - minX) < .001) {
axis.setRange(minX - 1, maxX + 1);
}
else {
axis.setRange(Double.parseDouble(num.format(minX)), Double.parseDouble(num.format(maxX)));
}
axis.setAutoTickUnitSelection(true);
}
/**
* After the chart is redrawn, this method calculates the x and y scale and
* updates those text fields.
*/
public void chartProgress(ChartProgressEvent e) {
// if the chart drawing is started
if (e.getType() == ChartProgressEvent.DRAWING_STARTED) {
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
// if the chart drawing is finished
else if (e.getType() == ChartProgressEvent.DRAWING_FINISHED) {
this.setCursor(null);
JFreeChart chart = e.getChart();
XYPlot plot = (XYPlot) chart.getPlot();
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
YMin.setText("" + axis.getLowerBound());
YMax.setText("" + axis.getUpperBound());
YScale.setText("" + axis.getTickUnit().getSize());
axis = (NumberAxis) plot.getDomainAxis();
XMin.setText("" + axis.getLowerBound());
XMax.setText("" + axis.getUpperBound());
XScale.setText("" + axis.getTickUnit().getSize());
}
}
/**
* Invoked when the mouse is clicked on the chart. Allows the user to edit the
* title and labels of the chart.
*/
public void mouseClicked(MouseEvent e) {
if (timeSeries) {
editGraph();
}
else {
editProbGraph();
}
}
/**
* This method currently does nothing.
*/
public void mousePressed(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseReleased(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseEntered(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseExited(MouseEvent e) {
}
private void setUpShapesAndColors() {
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
colors = new HashMap<String, Paint>();
shapes = new HashMap<String, Shape>();
colors.put("Red", draw.getNextPaint());
colors.put("Blue", draw.getNextPaint());
colors.put("Green", draw.getNextPaint());
colors.put("Yellow", draw.getNextPaint());
colors.put("Magenta", draw.getNextPaint());
colors.put("Cyan", draw.getNextPaint());
colors.put("Tan", draw.getNextPaint());
colors.put("Gray (Dark)", draw.getNextPaint());
colors.put("Red (Dark)", draw.getNextPaint());
colors.put("Blue (Dark)", draw.getNextPaint());
colors.put("Green (Dark)", draw.getNextPaint());
colors.put("Yellow (Dark)", draw.getNextPaint());
colors.put("Magenta (Dark)", draw.getNextPaint());
colors.put("Cyan (Dark)", draw.getNextPaint());
colors.put("Black", draw.getNextPaint());
colors.put("Red ", draw.getNextPaint());
colors.put("Blue ", draw.getNextPaint());
colors.put("Green ", draw.getNextPaint());
colors.put("Yellow ", draw.getNextPaint());
colors.put("Magenta ", draw.getNextPaint());
colors.put("Cyan ", draw.getNextPaint());
colors.put("Gray (Light)", draw.getNextPaint());
colors.put("Red (Extra Dark)", draw.getNextPaint());
colors.put("Blue (Extra Dark)", draw.getNextPaint());
colors.put("Green (Extra Dark)", draw.getNextPaint());
colors.put("Yellow (Extra Dark)", draw.getNextPaint());
colors.put("Magenta (Extra Dark)", draw.getNextPaint());
colors.put("Cyan (Extra Dark)", draw.getNextPaint());
colors.put("Red (Light)", draw.getNextPaint());
colors.put("Blue (Light)", draw.getNextPaint());
colors.put("Green (Light)", draw.getNextPaint());
colors.put("Yellow (Light)", draw.getNextPaint());
colors.put("Magenta (Light)", draw.getNextPaint());
colors.put("Cyan (Light)", draw.getNextPaint());
shapes.put("Square", draw.getNextShape());
shapes.put("Circle", draw.getNextShape());
shapes.put("Triangle", draw.getNextShape());
shapes.put("Diamond", draw.getNextShape());
shapes.put("Rectangle (Horizontal)", draw.getNextShape());
shapes.put("Triangle (Upside Down)", draw.getNextShape());
shapes.put("Circle (Half)", draw.getNextShape());
shapes.put("Arrow", draw.getNextShape());
shapes.put("Rectangle (Vertical)", draw.getNextShape());
shapes.put("Arrow (Backwards)", draw.getNextShape());
}
private void editGraph() {
final ArrayList<GraphSpecies> old = new ArrayList<GraphSpecies>();
for (GraphSpecies g : graphed) {
old.add(g);
}
JPanel titlePanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Title:");
JLabel xLabel = new JLabel("X-Axis Label:");
JLabel yLabel = new JLabel("Y-Axis Label:");
final JTextField title = new JTextField(chart.getTitle().getText(), 5);
final JTextField x = new JTextField(chart.getXYPlot().getDomainAxis().getLabel(), 5);
final JTextField y = new JTextField(chart.getXYPlot().getRangeAxis().getLabel(), 5);
final JLabel xMin = new JLabel("X-Min:");
final JLabel xMax = new JLabel("X-Max:");
final JLabel xScale = new JLabel("X-Step:");
final JLabel yMin = new JLabel("Y-Min:");
final JLabel yMax = new JLabel("Y-Max:");
final JLabel yScale = new JLabel("Y-Step:");
resize.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
xMin.setEnabled(false);
XMin.setEnabled(false);
xMax.setEnabled(false);
XMax.setEnabled(false);
xScale.setEnabled(false);
XScale.setEnabled(false);
yMin.setEnabled(false);
YMin.setEnabled(false);
yMax.setEnabled(false);
YMax.setEnabled(false);
yScale.setEnabled(false);
YScale.setEnabled(false);
}
else {
xMin.setEnabled(true);
XMin.setEnabled(true);
xMax.setEnabled(true);
XMax.setEnabled(true);
xScale.setEnabled(true);
XScale.setEnabled(true);
yMin.setEnabled(true);
YMin.setEnabled(true);
yMax.setEnabled(true);
YMax.setEnabled(true);
yScale.setEnabled(true);
YScale.setEnabled(true);
}
}
});
if (resize.isSelected()) {
xMin.setEnabled(false);
XMin.setEnabled(false);
xMax.setEnabled(false);
XMax.setEnabled(false);
xScale.setEnabled(false);
XScale.setEnabled(false);
yMin.setEnabled(false);
YMin.setEnabled(false);
yMax.setEnabled(false);
YMax.setEnabled(false);
yScale.setEnabled(false);
YScale.setEnabled(false);
}
else {
xMin.setEnabled(true);
XMin.setEnabled(true);
xMax.setEnabled(true);
XMax.setEnabled(true);
xScale.setEnabled(true);
XScale.setEnabled(true);
yMin.setEnabled(true);
YMin.setEnabled(true);
yMax.setEnabled(true);
YMax.setEnabled(true);
yScale.setEnabled(true);
YScale.setEnabled(true);
}
String simDirString = outDir.split(separator)[outDir.split(separator).length - 1];
final DefaultMutableTreeNode simDir = new DefaultMutableTreeNode(simDirString);
String[] files = new File(outDir).list();
for (int i = 1; i < files.length; i++) {
String index = files[i];
int j = i;
while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) {
files[j] = files[j - 1];
j = j - 1;
}
files[j] = index;
}
boolean add = false;
final ArrayList<String> directories = new ArrayList<String>();
for (String file : files) {
if (file.length() > 3
&& file.substring(file.length() - 4).equals(
"." + printer_id.substring(0, printer_id.length() - 8))) {
if (file.contains("run-")) {
add = true;
}
else {
simDir.add(new DefaultMutableTreeNode(file.substring(0, file.length() - 4)));
}
}
else if (new File(outDir + separator + file).isDirectory()) {
boolean addIt = false;
for (String getFile : new File(outDir + separator + file).list()) {
if (getFile.length() > 3
&& getFile.substring(getFile.length() - 4).equals(
"." + printer_id.substring(0, printer_id.length() - 8))) {
addIt = true;
}
}
if (addIt) {
directories.add(file);
DefaultMutableTreeNode d = new DefaultMutableTreeNode(file);
boolean add2 = false;
for (String f : new File(outDir + separator + file).list()) {
if (f.contains(printer_id.substring(0, printer_id.length() - 8))) {
if (f.contains("run-")) {
add2 = true;
}
else {
d.add(new DefaultMutableTreeNode(f.substring(0, f.length() - 4)));
}
}
}
if (add2) {
d.add(new DefaultMutableTreeNode("Average"));
d.add(new DefaultMutableTreeNode("Variance"));
d.add(new DefaultMutableTreeNode("Standard Deviation"));
}
int run = 1;
for (String s : new File(outDir + separator + file).list()) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + file + separator + "run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
d.add(new DefaultMutableTreeNode("run-" + (i + 1)));
}
}
simDir.add(d);
}
}
}
if (add) {
simDir.add(new DefaultMutableTreeNode("Average"));
simDir.add(new DefaultMutableTreeNode("Variance"));
simDir.add(new DefaultMutableTreeNode("Standard Deviation"));
}
int run = 1;
for (String s : new File(outDir).list()) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + "run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
simDir.add(new DefaultMutableTreeNode("run-" + (i + 1)));
}
}
if (simDir.getChildCount() == 0) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "No data to graph."
+ "\nPerform some simutations to create some data first.", "No Data",
JOptionPane.PLAIN_MESSAGE);
}
else {
final JTree tree = new JTree(simDir);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.expandRow(i);
}
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
final JPanel specPanel = new JPanel();
// final JFrame f = new JFrame("Edit Graph");
boolean stop = false;
int selectionRow = 1;
for (int i = 1; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (selected.equals(lastSelected)) {
stop = true;
selectionRow = i;
break;
}
}
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
if (!directories.contains(node.toString())) {
selected = node.toString();
int select;
if (selected.equals("Average")) {
select = 0;
}
else if (selected.equals("Variance")) {
select = 1;
}
else if (selected.equals("Standard Deviation")) {
select = 2;
}
else if (selected.contains("-run")) {
select = 0;
}
else {
try {
if (selected.contains("run-")) {
select = Integer.parseInt(selected.substring(4)) + 2;
}
else {
select = -1;
}
}
catch (Exception e1) {
select = -1;
}
}
if (select != -1) {
specPanel.removeAll();
if (directories.contains(node.getParent().toString())) {
specPanel.add(fixGraphChoices(node.getParent().toString()));
}
else {
specPanel.add(fixGraphChoices(""));
}
specPanel.revalidate();
specPanel.repaint();
for (int i = 0; i < series.size(); i++) {
series.get(i).setText(graphSpecies.get(i + 1));
}
for (int i = 0; i < boxes.size(); i++) {
boxes.get(i).setSelected(false);
}
if (directories.contains(node.getParent().toString())) {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected)
&& g.getDirectory().equals(node.getParent().toString())) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
colorsCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getPaintName());
shapesCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
else {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getDirectory().equals("")) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
colorsCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getPaintName());
shapesCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
boolean allChecked = true;
boolean allCheckedVisible = true;
boolean allCheckedFilled = true;
boolean allCheckedConnected = true;
for (int i = 0; i < boxes.size(); i++) {
if (!boxes.get(i).isSelected()) {
allChecked = false;
String s = "";
s = e.getPath().getLastPathComponent().toString();
if (directories.contains(node.getParent().toString())) {
if (s.equals("Average")) {
s = "(" + node.getParent().toString() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + node.getParent().toString() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + node.getParent().toString() + ", " + (char) 948 + ")";
}
else {
if (s.contains("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.contains("run-")) {
s = s.substring(4);
}
s = "(" + node.getParent().toString() + ", " + s + ")";
}
}
else {
if (s.equals("Average")) {
s = "(" + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + (char) 948 + ")";
}
else {
if (s.contains("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.contains("run-")) {
s = s.substring(4);
}
s = "(" + s + ")";
}
}
String text = graphSpecies.get(i + 1);
String end = "";
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
boxes.get(i).setName(text);
series.get(i).setText(text);
colorsCombo.get(i).setSelectedIndex(0);
shapesCombo.get(i).setSelectedIndex(0);
}
else {
String s = "";
s = e.getPath().getLastPathComponent().toString();
if (directories.contains(node.getParent().toString())) {
if (s.equals("Average")) {
s = "(" + node.getParent().toString() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + node.getParent().toString() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + node.getParent().toString() + ", " + (char) 948 + ")";
}
else {
if (s.contains("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.contains("run-")) {
s = s.substring(4);
}
s = "(" + node.getParent().toString() + ", " + s + ")";
}
}
else {
if (s.equals("Average")) {
s = "(" + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + (char) 948 + ")";
}
else {
if (s.contains("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.contains("run-")) {
s = s.substring(4);
}
s = "(" + s + ")";
}
}
String text = series.get(i).getText();
String end = "";
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
boxes.get(i).setName(text);
}
if (!visible.get(i).isSelected()) {
allCheckedVisible = false;
}
if (!connected.get(i).isSelected()) {
allCheckedConnected = false;
}
if (!filled.get(i).isSelected()) {
allCheckedFilled = false;
}
}
if (allChecked) {
use.setSelected(true);
}
else {
use.setSelected(false);
}
if (allCheckedVisible) {
visibleLabel.setSelected(true);
}
else {
visibleLabel.setSelected(false);
}
if (allCheckedFilled) {
filledLabel.setSelected(true);
}
else {
filledLabel.setSelected(false);
}
if (allCheckedConnected) {
connectedLabel.setSelected(true);
}
else {
connectedLabel.setSelected(false);
}
}
}
else {
specPanel.removeAll();
specPanel.revalidate();
specPanel.repaint();
}
}
});
if (!stop) {
tree.setSelectionRow(0);
tree.setSelectionRow(1);
}
else {
tree.setSelectionRow(0);
tree.setSelectionRow(selectionRow);
}
JScrollPane scroll = new JScrollPane();
scroll.setPreferredSize(new Dimension(1050, 500));
JPanel editPanel = new JPanel(new BorderLayout());
editPanel.add(specPanel, "Center");
editPanel.add(scrollpane, "West");
scroll.setViewportView(editPanel);
// JButton ok = new JButton("Ok");
/*
* ok.addActionListener(new ActionListener() { public void
* actionPerformed(ActionEvent e) { double minY; double maxY; double
* scaleY; double minX; double maxX; double scaleX; change = true; try {
* minY = Double.parseDouble(YMin.getText().trim()); maxY =
* Double.parseDouble(YMax.getText().trim()); scaleY =
* Double.parseDouble(YScale.getText().trim()); minX =
* Double.parseDouble(XMin.getText().trim()); maxX =
* Double.parseDouble(XMax.getText().trim()); scaleX =
* Double.parseDouble(XScale.getText().trim()); NumberFormat num =
* NumberFormat.getInstance(); num.setMaximumFractionDigits(4);
* num.setGroupingUsed(false); minY =
* Double.parseDouble(num.format(minY)); maxY =
* Double.parseDouble(num.format(maxY)); scaleY =
* Double.parseDouble(num.format(scaleY)); minX =
* Double.parseDouble(num.format(minX)); maxX =
* Double.parseDouble(num.format(maxX)); scaleX =
* Double.parseDouble(num.format(scaleX)); } catch (Exception e1) {
* JOptionPane.showMessageDialog(biomodelsim.frame(), "Must enter doubles
* into the inputs " + "to change the graph's dimensions!", "Error",
* JOptionPane.ERROR_MESSAGE); return; } lastSelected = selected; selected =
* ""; ArrayList<XYSeries> graphData = new ArrayList<XYSeries>();
* XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer)
* chart.getXYPlot().getRenderer(); int thisOne = -1; for (int i = 1; i <
* graphed.size(); i++) { GraphSpecies index = graphed.get(i); int j = i;
* while ((j > 0) && (graphed.get(j -
* 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
* graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j, index); }
* ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>();
* HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String,
* ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) { if
* (g.getDirectory().equals("")) { thisOne++;
* rend.setSeriesVisible(thisOne, true);
* rend.setSeriesLinesVisible(thisOne, g.getConnected());
* rend.setSeriesShapesFilled(thisOne, g.getFilled());
* rend.setSeriesShapesVisible(thisOne, g.getVisible());
* rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
* rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if
* (!g.getRunNumber().equals("Average") &&
* !g.getRunNumber().equals("Variance") &&
* !g.getRunNumber().equals("Standard Deviation")) { if (new File(outDir +
* separator + g.getRunNumber() + "." + printer_id.substring(0,
* printer_id.length() - 8)).exists()) { readGraphSpecies(outDir +
* separator + g.getRunNumber() + "." + printer_id.substring(0,
* printer_id.length() - 8), biomodelsim.frame()); ArrayList<ArrayList<Double>>
* data; if (allData.containsKey(g.getRunNumber() + " " +
* g.getDirectory())) { data = allData.get(g.getRunNumber() + " " +
* g.getDirectory()); } else { data = readData(outDir + separator +
* g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() -
* 8), biomodelsim.frame(), y.getText().trim(), g.getRunNumber(), null);
* for (int i = 2; i < graphSpecies.size(); i++) { String index =
* graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j =
* i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) >
* 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j,
* data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j,
* index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(),
* data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() !=
* 0) { for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph =
* false; try { for (String s : new File(outDir).list()) { if (s.length() >
* 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } }
* catch (Exception e1) { ableToGraph = false; } if (ableToGraph) { int
* next = 1; while (!new File(outDir + separator + "run-" + next + "." +
* printer_id.substring(0, printer_id.length() - 8)).exists()) { next++; }
* readGraphSpecies(outDir + separator + "run-" + next + "." +
* printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
* ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data =
* allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data =
* readData(outDir + separator + "run-1." + printer_id.substring(0,
* printer_id.length() - 8), biomodelsim.frame(), y.getText().trim(),
* g.getRunNumber().toLowerCase(), null); for (int i = 2; i <
* graphSpecies.size(); i++) { String index = graphSpecies.get(i);
* ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) &&
* graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
* graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j -
* 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) {
* for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } } else { thisOne++;
* rend.setSeriesVisible(thisOne, true);
* rend.setSeriesLinesVisible(thisOne, g.getConnected());
* rend.setSeriesShapesFilled(thisOne, g.getFilled());
* rend.setSeriesShapesVisible(thisOne, g.getVisible());
* rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
* rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if
* (!g.getRunNumber().equals("Average") &&
* !g.getRunNumber().equals("Variance") &&
* !g.getRunNumber().equals("Standard Deviation")) { if (new File(outDir +
* separator + g.getDirectory() + separator + g.getRunNumber() + "." +
* printer_id.substring(0, printer_id.length() - 8)).exists()) {
* readGraphSpecies( outDir + separator + g.getDirectory() + separator +
* g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() -
* 8), biomodelsim.frame()); ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data =
* allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data =
* readData(outDir + separator + g.getDirectory() + separator +
* g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() -
* 8), biomodelsim.frame(), y.getText().trim(), g.getRunNumber(),
* g.getDirectory()); for (int i = 2; i < graphSpecies.size(); i++) {
* String index = graphSpecies.get(i); ArrayList<Double> index2 =
* data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j -
* 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j,
* graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; }
* graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) {
* for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph =
* false; try { for (String s : new File(outDir + separator +
* g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0,
* 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e1) {
* ableToGraph = false; } if (ableToGraph) { int next = 1; while (!new
* File(outDir + separator + g.getDirectory() + separator + "run-" + next +
* "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
* next++; } readGraphSpecies(outDir + separator + g.getDirectory() +
* separator + "run-" + next + "." + printer_id.substring(0,
* printer_id.length() - 8), biomodelsim.frame()); ArrayList<ArrayList<Double>>
* data; if (allData.containsKey(g.getRunNumber() + " " +
* g.getDirectory())) { data = allData.get(g.getRunNumber() + " " +
* g.getDirectory()); } else { data = readData(outDir + separator +
* g.getDirectory() + separator + "run-1." + printer_id.substring(0,
* printer_id.length() - 8), biomodelsim.frame(), y.getText().trim(),
* g.getRunNumber().toLowerCase(), g.getDirectory()); for (int i = 2; i <
* graphSpecies.size(); i++) { String index = graphSpecies.get(i);
* ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) &&
* graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
* graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j -
* 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) {
* for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } } } for (GraphSpecies g :
* unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset = new
* XYSeriesCollection(); for (int i = 0; i < graphData.size(); i++) {
* dataset.addSeries(graphData.get(i)); } fixGraph(title.getText().trim(),
* x.getText().trim(), y.getText().trim(), dataset);
* chart.getXYPlot().setRenderer(rend); XYPlot plot = chart.getXYPlot();
* if (resize.isSelected()) { resize(dataset); } else { NumberAxis axis =
* (NumberAxis) plot.getRangeAxis(); axis.setAutoTickUnitSelection(false);
* axis.setRange(minY, maxY); axis.setTickUnit(new
* NumberTickUnit(scaleY)); axis = (NumberAxis) plot.getDomainAxis();
* axis.setAutoTickUnitSelection(false); axis.setRange(minX, maxX);
* axis.setTickUnit(new NumberTickUnit(scaleX)); } //f.dispose(); } });
*/
// final JButton cancel = new JButton("Cancel");
// cancel.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// selected = "";
// int size = graphed.size();
// for (int i = 0; i < size; i++) {
// graphed.remove();
// }
// for (GraphSpecies g : old) {
// graphed.add(g);
// }
// f.dispose();
// }
// });
final JButton deselect = new JButton("Deselect All");
deselect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// selected = "";
int size = graphed.size();
for (int i = 0; i < size; i++) {
graphed.remove();
}
if (tree.getSelectionCount() > 0) {
int selectedRow = tree.getSelectionRows()[0];
tree.setSelectionRow(0);
tree.setSelectionRow(selectedRow);
}
}
});
JPanel titlePanel1 = new JPanel(new GridLayout(3, 6));
JPanel titlePanel2 = new JPanel(new GridLayout(1, 6));
titlePanel1.add(titleLabel);
titlePanel1.add(title);
titlePanel1.add(xMin);
titlePanel1.add(XMin);
titlePanel1.add(yMin);
titlePanel1.add(YMin);
titlePanel1.add(xLabel);
titlePanel1.add(x);
titlePanel1.add(xMax);
titlePanel1.add(XMax);
titlePanel1.add(yMax);
titlePanel1.add(YMax);
titlePanel1.add(yLabel);
titlePanel1.add(y);
titlePanel1.add(xScale);
titlePanel1.add(XScale);
titlePanel1.add(yScale);
titlePanel1.add(YScale);
titlePanel2.add(new JPanel());
JPanel deselectPanel = new JPanel();
deselectPanel.add(deselect);
titlePanel2.add(deselectPanel);
titlePanel2.add(new JPanel());
titlePanel2.add(new JPanel());
titlePanel2.add(new JPanel());
titlePanel2.add(resize);
titlePanel.add(titlePanel1, "Center");
titlePanel.add(titlePanel2, "South");
// JPanel buttonPanel = new JPanel();
// buttonPanel.add(ok);
// buttonPanel.add(deselect);
// buttonPanel.add(cancel);
JPanel all = new JPanel(new BorderLayout());
all.add(titlePanel, "North");
all.add(scroll, "Center");
// all.add(buttonPanel, "South");
Object[] options = { "Ok", "Cancel" };
int value = JOptionPane.showOptionDialog(biomodelsim.frame(), all, "Edit Graph",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
double minY;
double maxY;
double scaleY;
double minX;
double maxX;
double scaleX;
change = true;
try {
minY = Double.parseDouble(YMin.getText().trim());
maxY = Double.parseDouble(YMax.getText().trim());
scaleY = Double.parseDouble(YScale.getText().trim());
minX = Double.parseDouble(XMin.getText().trim());
maxX = Double.parseDouble(XMax.getText().trim());
scaleX = Double.parseDouble(XScale.getText().trim());
NumberFormat num = NumberFormat.getInstance();
num.setMaximumFractionDigits(4);
num.setGroupingUsed(false);
minY = Double.parseDouble(num.format(minY));
maxY = Double.parseDouble(num.format(maxY));
scaleY = Double.parseDouble(num.format(scaleY));
minX = Double.parseDouble(num.format(minX));
maxX = Double.parseDouble(num.format(maxX));
scaleX = Double.parseDouble(num.format(scaleX));
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Must enter doubles into the inputs "
+ "to change the graph's dimensions!", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
lastSelected = selected;
selected = "";
ArrayList<XYSeries> graphData = new ArrayList<XYSeries>();
XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < graphed.size(); i++) {
GraphSpecies index = graphed.get(i);
int j = i;
while ((j > 0)
&& (graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
graphed.set(j, graphed.get(j - 1));
j = j - 1;
}
graphed.set(j, index);
}
ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>();
HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>();
for (GraphSpecies g : graphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation")) {
if (new File(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), y
.getText().trim(), g.getRunNumber(), null);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e1) {
ableToGraph = false;
}
if (ableToGraph) {
int next = 1;
while (!new File(outDir + separator + "run-" + next + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
next++;
}
readGraphSpecies(outDir + separator + "run-" + next + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "run-1."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), y
.getText().trim(), g.getRunNumber().toLowerCase(), null);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
else {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation")) {
if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber()
+ "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator
+ g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8),
biomodelsim.frame());
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getDirectory() + separator
+ g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8),
biomodelsim.frame(), y.getText().trim(), g.getRunNumber(), g.getDirectory());
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir + separator + g.getDirectory()).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e1) {
ableToGraph = false;
}
if (ableToGraph) {
int next = 1;
while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + next
+ "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
next++;
}
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "run-" + next
+ "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getDirectory() + separator + "run-1."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), y
.getText().trim(), g.getRunNumber().toLowerCase(), g.getDirectory());
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
}
for (GraphSpecies g : unableToGraph) {
graphed.remove(g);
}
XYSeriesCollection dataset = new XYSeriesCollection();
for (int i = 0; i < graphData.size(); i++) {
dataset.addSeries(graphData.get(i));
}
fixGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), dataset);
chart.getXYPlot().setRenderer(rend);
XYPlot plot = chart.getXYPlot();
if (resize.isSelected()) {
resize(dataset);
}
else {
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minY, maxY);
axis.setTickUnit(new NumberTickUnit(scaleY));
axis = (NumberAxis) plot.getDomainAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minX, maxX);
axis.setTickUnit(new NumberTickUnit(scaleX));
}
}
else {
selected = "";
int size = graphed.size();
for (int i = 0; i < size; i++) {
graphed.remove();
}
for (GraphSpecies g : old) {
graphed.add(g);
}
}
// WindowListener w = new WindowListener() {
// public void windowClosing(WindowEvent arg0) {
// cancel.doClick();
// }
// public void windowOpened(WindowEvent arg0) {
// }
// public void windowClosed(WindowEvent arg0) {
// }
// public void windowIconified(WindowEvent arg0) {
// }
// public void windowDeiconified(WindowEvent arg0) {
// }
// public void windowActivated(WindowEvent arg0) {
// }
// public void windowDeactivated(WindowEvent arg0) {
// }
// };
// f.addWindowListener(w);
// f.setContentPane(all);
// f.pack();
// Dimension screenSize;
// try {
// Toolkit tk = Toolkit.getDefaultToolkit();
// screenSize = tk.getScreenSize();
// }
// catch (AWTError awe) {
// screenSize = new Dimension(640, 480);
// }
// Dimension frameSize = f.getSize();
// if (frameSize.height > screenSize.height) {
// frameSize.height = screenSize.height;
// }
// if (frameSize.width > screenSize.width) {
// frameSize.width = screenSize.width;
// }
// int xx = screenSize.width / 2 - frameSize.width / 2;
// int yy = screenSize.height / 2 - frameSize.height / 2;
// f.setLocation(xx, yy);
// f.setVisible(true);
}
}
private JPanel fixGraphChoices(final String directory) {
if (directory.equals("")) {
if (selected.equals("Average") || selected.equals("Variance")
|| selected.equals("Standard Deviation")) {
int nextOne = 1;
while (!new File(outDir + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
}
else {
readGraphSpecies(outDir + separator + selected + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
}
}
else {
if (selected.equals("Average") || selected.equals("Variance")
|| selected.equals("Standard Deviation")) {
int nextOne = 1;
while (!new File(outDir + separator + directory + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + directory + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
}
else {
readGraphSpecies(outDir + separator + directory + separator + selected + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
}
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
JPanel speciesPanel1 = new JPanel(new GridLayout(graphSpecies.size(), 1));
JPanel speciesPanel2 = new JPanel(new GridLayout(graphSpecies.size(), 3));
JPanel speciesPanel3 = new JPanel(new GridLayout(graphSpecies.size(), 3));
use = new JCheckBox("Use");
JLabel specs = new JLabel("Species");
JLabel color = new JLabel("Color");
JLabel shape = new JLabel("Shape");
connectedLabel = new JCheckBox("Connected");
visibleLabel = new JCheckBox("Visible");
filledLabel = new JCheckBox("Filled");
connectedLabel.setSelected(true);
visibleLabel.setSelected(true);
filledLabel.setSelected(true);
boxes = new ArrayList<JCheckBox>();
series = new ArrayList<JTextField>();
colorsCombo = new ArrayList<JComboBox>();
shapesCombo = new ArrayList<JComboBox>();
connected = new ArrayList<JCheckBox>();
visible = new ArrayList<JCheckBox>();
filled = new ArrayList<JCheckBox>();
use.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (use.isSelected()) {
for (JCheckBox box : boxes) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : boxes) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
connectedLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (connectedLabel.isSelected()) {
for (JCheckBox box : connected) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : connected) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
visibleLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (visibleLabel.isSelected()) {
for (JCheckBox box : visible) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : visible) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
filledLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (filledLabel.isSelected()) {
for (JCheckBox box : filled) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : filled) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
speciesPanel1.add(use);
speciesPanel2.add(specs);
speciesPanel2.add(color);
speciesPanel2.add(shape);
speciesPanel3.add(connectedLabel);
speciesPanel3.add(visibleLabel);
speciesPanel3.add(filledLabel);
final HashMap<String, Shape> shapey = this.shapes;
final HashMap<String, Paint> colory = this.colors;
for (int i = 0; i < graphSpecies.size() - 1; i++) {
JCheckBox temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
String s = series.get(i).getText();
((JCheckBox) e.getSource()).setSelected(false);
int[] cols = new int[34];
int[] shaps = new int[10];
for (int k = 0; k < boxes.size(); k++) {
if (boxes.get(k).isSelected()) {
if (colorsCombo.get(k).getSelectedItem().equals("Red")) {
cols[0]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) {
cols[1]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green")) {
cols[2]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) {
cols[3]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) {
cols[4]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) {
cols[5]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) {
cols[6]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) {
cols[7]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) {
cols[8]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) {
cols[9]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Dark)")) {
cols[10]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Dark)")) {
cols[11]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Dark)")) {
cols[12]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Black")) {
cols[14]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red ")) {
cols[15]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue ")) {
cols[16]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green ")) {
cols[17]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow ")) {
cols[18]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta ")) {
cols[19]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan ")) {
cols[20]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Light)")) {
cols[21]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Extra Dark)")) {
cols[22]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Extra Dark)")) {
cols[23]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Extra Dark)")) {
cols[24]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Extra Dark)")) {
cols[25]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Extra Dark)")) {
cols[26]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Extra Dark)")) {
cols[27]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) {
cols[28]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Light)")) {
cols[29]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Light)")) {
cols[30]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Light)")) {
cols[31]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Light)")) {
cols[32]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Light)")) {
cols[33]++;
}
if (shapesCombo.get(k).getSelectedItem().equals("Square")) {
shaps[0]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Circle")) {
shaps[1]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Triangle")) {
shaps[2]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Diamond")) {
shaps[3]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Rectangle (Horizontal)")) {
shaps[4]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Triangle (Upside Down)")) {
shaps[5]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Circle (Half)")) {
shaps[6]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Arrow")) {
shaps[7]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Rectangle (Vertical)")) {
shaps[8]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Arrow (Backwards)")) {
shaps[9]++;
}
}
}
for (GraphSpecies graph : graphed) {
if (graph.getShapeAndPaint().getPaintName().equals("Red")) {
cols[0]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue")) {
cols[1]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green")) {
cols[2]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow")) {
cols[3]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta")) {
cols[4]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan")) {
cols[5]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Tan")) {
cols[6]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Dark)")) {
cols[7]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Dark)")) {
cols[8]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Dark)")) {
cols[9]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Dark)")) {
cols[10]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Dark)")) {
cols[11]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Dark)")) {
cols[12]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Black")) {
cols[14]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red ")) {
cols[15]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue ")) {
cols[16]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green ")) {
cols[17]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow ")) {
cols[18]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta ")) {
cols[19]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan ")) {
cols[20]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Light)")) {
cols[21]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Extra Dark)")) {
cols[22]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Extra Dark)")) {
cols[23]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Extra Dark)")) {
cols[24]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Extra Dark)")) {
cols[25]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Extra Dark)")) {
cols[26]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Extra Dark)")) {
cols[27]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Light)")) {
cols[28]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Light)")) {
cols[29]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Light)")) {
cols[30]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Light)")) {
cols[31]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Light)")) {
cols[32]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Light)")) {
cols[33]++;
}
if (graph.getShapeAndPaint().getShapeName().equals("Square")) {
shaps[0]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Circle")) {
shaps[1]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Triangle")) {
shaps[2]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Diamond")) {
shaps[3]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Rectangle (Horizontal)")) {
shaps[4]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Triangle (Upside Down)")) {
shaps[5]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Circle (Half)")) {
shaps[6]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Arrow")) {
shaps[7]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Rectangle (Vertical)")) {
shaps[8]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Arrow (Backwards)")) {
shaps[9]++;
}
}
((JCheckBox) e.getSource()).setSelected(true);
series.get(i).setText(s);
int colorSet = 0;
for (int j = 1; j < cols.length; j++) {
if (cols[j] < cols[colorSet]) {
colorSet = j;
}
}
int shapeSet = 0;
for (int j = 1; j < shaps.length; j++) {
if (shaps[j] < shaps[shapeSet]) {
shapeSet = j;
}
}
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
for (int j = 0; j < colorSet; j++) {
draw.getNextPaint();
}
Paint paint = draw.getNextPaint();
Object[] set = colory.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (paint == colory.get(set[j])) {
colorsCombo.get(i).setSelectedItem(set[j]);
}
}
for (int j = 0; j < shapeSet; j++) {
draw.getNextShape();
}
Shape shape = draw.getNextShape();
set = shapey.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (shape == shapey.get(set[j])) {
shapesCombo.get(i).setSelectedItem(set[j]);
}
}
boolean allChecked = true;
for (JCheckBox temp : boxes) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
use.setSelected(true);
}
graphed.add(new GraphSpecies(shapey.get(shapesCombo.get(i).getSelectedItem()), colory
.get(colorsCombo.get(i).getSelectedItem()), filled.get(i).isSelected(), visible
.get(i).isSelected(), connected.get(i).isSelected(), selected, boxes.get(i)
.getName(), series.get(i).getText().trim(), i, directory));
}
else {
ArrayList<GraphSpecies> remove = new ArrayList<GraphSpecies>();
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
remove.add(g);
}
}
for (GraphSpecies g : remove) {
graphed.remove(g);
}
use.setSelected(false);
colorsCombo.get(i).setSelectedIndex(0);
shapesCombo.get(i).setSelectedIndex(0);
}
}
});
boxes.add(temp);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : visible) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
visibleLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setVisible(true);
}
}
}
else {
visibleLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setVisible(false);
}
}
}
}
});
visible.add(temp);
visible.get(i).setSelected(true);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : filled) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
filledLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setFilled(true);
}
}
}
else {
filledLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setFilled(false);
}
}
}
}
});
filled.add(temp);
filled.get(i).setSelected(true);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : connected) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
connectedLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setConnected(true);
}
}
}
else {
connectedLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setConnected(false);
}
}
}
}
});
connected.add(temp);
connected.get(i).setSelected(true);
JTextField seriesName = new JTextField(graphSpecies.get(i + 1));
seriesName.setName("" + i);
seriesName.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyReleased(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyTyped(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
});
series.add(seriesName);
Object[] col = this.colors.keySet().toArray();
Arrays.sort(col);
Object[] shap = this.shapes.keySet().toArray();
Arrays.sort(shap);
JComboBox colBox = new JComboBox(col);
colBox.setActionCommand("" + i);
colBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setPaint((String) ((JComboBox) e.getSource()).getSelectedItem());
}
}
}
});
JComboBox shapBox = new JComboBox(shap);
shapBox.setActionCommand("" + i);
shapBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setShape((String) ((JComboBox) e.getSource()).getSelectedItem());
}
}
}
});
colorsCombo.add(colBox);
shapesCombo.add(shapBox);
speciesPanel1.add(boxes.get(i));
speciesPanel2.add(series.get(i));
speciesPanel2.add(colorsCombo.get(i));
speciesPanel2.add(shapesCombo.get(i));
speciesPanel3.add(connected.get(i));
speciesPanel3.add(visible.get(i));
speciesPanel3.add(filled.get(i));
}
JPanel speciesPanel = new JPanel(new BorderLayout());
speciesPanel.add(speciesPanel1, "West");
speciesPanel.add(speciesPanel2, "Center");
speciesPanel.add(speciesPanel3, "East");
return speciesPanel;
}
private void fixGraph(String title, String x, String y, XYSeriesCollection dataset) {
curData = dataset;
chart = ChartFactory.createXYLineChart(title, x, y, dataset, PlotOrientation.VERTICAL, true,
true, false);
chart.addProgressListener(this);
ChartPanel graph = new ChartPanel(chart);
if (graphed.isEmpty()) {
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Click here to create graph");
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
}
graph.addMouseListener(this);
JPanel ButtonHolder = new JPanel();
save = new JButton("Save Graph");
export = new JButton("Export");
// exportJPeg = new JButton("Export As JPEG");
// exportPng = new JButton("Export As PNG");
// exportPdf = new JButton("Export As PDF");
// exportEps = new JButton("Export As EPS");
// exportSvg = new JButton("Export As SVG");
// exportCsv = new JButton("Export As CSV");
save.addActionListener(this);
export.addActionListener(this);
// exportJPeg.addActionListener(this);
// exportPng.addActionListener(this);
// exportPdf.addActionListener(this);
// exportEps.addActionListener(this);
// exportSvg.addActionListener(this);
// exportCsv.addActionListener(this);
ButtonHolder.add(save);
ButtonHolder.add(export);
// ButtonHolder.add(exportJPeg);
// ButtonHolder.add(exportPng);
// ButtonHolder.add(exportPdf);
// ButtonHolder.add(exportEps);
// ButtonHolder.add(exportSvg);
// ButtonHolder.add(exportCsv);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, ButtonHolder, null);
splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
this.add(splitPane, "South");
this.revalidate();
}
/**
* This method saves the graph as a jpeg or as a png file.
*/
public void export() {
try {
int output = 2; /* Default is currently pdf */
int width = -1;
int height = -1;
JPanel sizePanel = new JPanel(new GridLayout(2, 2));
JLabel heightLabel = new JLabel("Desired pixel height:");
JLabel widthLabel = new JLabel("Desired pixel width:");
JTextField heightField = new JTextField("400");
JTextField widthField = new JTextField("650");
sizePanel.add(widthLabel);
sizePanel.add(widthField);
sizePanel.add(heightLabel);
sizePanel.add(heightField);
Object[] options2 = { "Export", "Cancel" };
int value;
File file;
if (savedPics != null) {
file = new File(savedPics);
}
else {
file = null;
}
String filename = Buttons.browse(biomodelsim.frame(), file, null, JFileChooser.FILES_ONLY,
"Export");
if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length()).equals(".jpg"))) {
output = 0;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length()).equals(".png"))) {
output = 1;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length()).equals(".pdf"))) {
output = 2;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length()).equals(".eps"))) {
output = 3;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length()).equals(".svg"))) {
output = 4;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length()).equals(".csv"))) {
output = 5;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length()).equals(".dat"))) {
output = 6;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length()).equals(".tsd"))) {
output = 7;
}
if (!filename.equals("")) {
file = new File(filename);
boolean exportIt = true;
if (file.exists()) {
Object[] options = { "Overwrite", "Cancel" };
value = JOptionPane.showOptionDialog(biomodelsim.frame(), "File already exists."
+ " Overwrite?", "File Already Exists", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
exportIt = false;
if (value == JOptionPane.YES_OPTION) {
exportIt = true;
}
}
if (exportIt) {
if ((output != 5) && (output != 6) && (output != 7)) {
value = JOptionPane.showOptionDialog(biomodelsim.frame(), sizePanel,
"Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options2, options2[0]);
if (value == JOptionPane.YES_OPTION) {
while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1))
try {
width = Integer.parseInt(widthField.getText().trim());
height = Integer.parseInt(heightField.getText().trim());
if (width < 1 || height < 1) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(biomodelsim.frame(), sizePanel,
"Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options2, options2[0]);
}
}
catch (Exception e2) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(biomodelsim.frame(), sizePanel,
"Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options2, options2[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
if (output == 0) {
ChartUtilities.saveChartAsJPEG(file, chart, width, height);
}
else if (output == 1) {
ChartUtilities.saveChartAsPNG(file, chart, width, height);
}
else if (output == 2) {
Rectangle pagesize = new Rectangle(width, height);
Document document = new Document(pagesize, 50, 50, 50, 50);
FileOutputStream out = new FileOutputStream(file);
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
chart.draw(g2, new java.awt.Rectangle(width, height));
g2.dispose();
cb.addTemplate(tp, 0, 0);
document.close();
out.close();
}
else if (output == 3) {
Graphics2D g = new EpsGraphics2D();
chart.draw(g, new java.awt.Rectangle(width, height));
Writer out = new FileWriter(file);
out.write(g.toString());
out.close();
}
else if (output == 4) {
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
chart.draw(svgGenerator, new java.awt.Rectangle(width, height));
boolean useCSS = true;
FileOutputStream outStream = new FileOutputStream(file);
Writer out = new OutputStreamWriter(outStream, "UTF-8");
svgGenerator.stream(out, useCSS);
out.close();
outStream.close();
}
else if ((output == 5) || (output == 6) || (output == 7)) {
exportDataFile(file, output);
}
savedPics = filename;
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Export File!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void exportDataFile(File file, int output) {
try {
int count = curData.getSeries(0).getItemCount();
for (int i = 1; i < curData.getSeriesCount(); i++) {
if (curData.getSeries(i).getItemCount() != count) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Data series do not have the same number of points!", "Unable to Export Data File",
JOptionPane.ERROR_MESSAGE);
return;
}
}
for (int j = 0; j < count; j++) {
Number Xval = curData.getSeries(0).getDataItem(j).getX();
for (int i = 1; i < curData.getSeriesCount(); i++) {
if (curData.getSeries(i).getDataItem(j).getX() != Xval) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Data series time points are not the same!", "Unable to Export Data File",
JOptionPane.ERROR_MESSAGE);
return;
}
}
}
FileOutputStream csvFile = new FileOutputStream(file);
PrintWriter csvWriter = new PrintWriter(csvFile);
if (output == 7) {
csvWriter.print("((");
}
else if (output == 6) {
csvWriter.print("#");
}
csvWriter.print("\"Time\"");
count = curData.getSeries(0).getItemCount();
int pos = 0;
for (int i = 0; i < curData.getSeriesCount(); i++) {
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
csvWriter.print("\"" + curData.getSeriesKey(i) + "\"");
if (curData.getSeries(i).getItemCount() > count) {
count = curData.getSeries(i).getItemCount();
pos = i;
}
}
if (output == 7) {
csvWriter.print(")");
}
else {
csvWriter.println("");
}
for (int j = 0; j < count; j++) {
if (output == 7) {
csvWriter.print(",");
}
for (int i = 0; i < curData.getSeriesCount(); i++) {
if (i == 0) {
if (output == 7) {
csvWriter.print("(");
}
csvWriter.print(curData.getSeries(pos).getDataItem(j).getX());
}
XYSeries data = curData.getSeries(i);
if (j < data.getItemCount()) {
XYDataItem item = data.getDataItem(j);
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
csvWriter.print(item.getY());
}
else {
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
}
}
if (output == 7) {
csvWriter.print(")");
}
else {
csvWriter.println("");
}
}
if (output == 7) {
csvWriter.println(")");
}
csvWriter.close();
csvFile.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Export File!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
private ArrayList<ArrayList<Double>> calculateAverageVarianceDeviation(String startFile,
String fileStem, int choice, String directory) {
ArrayList<ArrayList<Double>> average = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> variance = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> deviation = new ArrayList<ArrayList<Double>>();
try {
FileInputStream fileInput = new FileInputStream(new File(startFile));
ProgressMonitorInputStream prog = new ProgressMonitorInputStream(biomodelsim.frame(),
"Reading Reb2sac Output Data From " + new File(startFile).getName(), fileInput);
InputStream input = new BufferedInputStream(prog);
boolean reading = true;
char cha;
int readCount = 0;
while (reading) {
String word = "";
boolean readWord = true;
while (readWord) {
int read = input.read();
readCount++;
if (read == -1) {
reading = false;
readWord = false;
}
cha = (char) read;
if (Character.isWhitespace(cha)) {
input.mark(3);
char next = (char) input.read();
char after = (char) input.read();
String check = "" + next + after;
if (word.equals("") || word.equals("0") || check.equals("0,")) {
readWord = false;
}
else {
word += cha;
}
input.reset();
}
else if (cha == ',' || cha == ':' || cha == ';' || cha == '!' || cha == '?'
|| cha == '\"' || cha == '\'' || cha == '(' || cha == ')' || cha == '{' || cha == '}'
|| cha == '[' || cha == ']' || cha == '<' || cha == '>' || cha == '*' || cha == '='
|| cha == '#') {
readWord = false;
}
else if (read != -1) {
word += cha;
}
}
int getNum;
try {
getNum = Integer.parseInt(word);
if (getNum == 0) {
boolean first = true;
int runsToMake = 1;
String[] findNum = startFile.split(separator);
String search = findNum[findNum.length - 1];
int firstOne = Integer.parseInt(search.substring(4, search.length() - 4));
if (directory == null) {
for (String f : new File(outDir).list()) {
if (f.contains(fileStem)) {
int tempNum = Integer.parseInt(f.substring(fileStem.length(), f.length() - 4));
if (tempNum > runsToMake) {
runsToMake = tempNum;
}
}
}
}
else {
for (String f : new File(outDir + separator + directory).list()) {
if (f.contains(fileStem)) {
int tempNum = Integer.parseInt(f.substring(fileStem.length(), f.length() - 4));
if (tempNum > runsToMake) {
runsToMake = tempNum;
}
}
}
}
for (int i = 0; i < graphSpecies.size(); i++) {
average.add(new ArrayList<Double>());
variance.add(new ArrayList<Double>());
}
(average.get(0)).add(0.0);
(variance.get(0)).add(0.0);
int count = 0;
int skip = firstOne;
for (int j = 0; j < runsToMake; j++) {
int counter = 1;
if (!first) {
if (firstOne != 1) {
j--;
firstOne = 1;
}
boolean loop = true;
while (loop && j < runsToMake && (j + 1) != skip) {
if (directory == null) {
if (new File(outDir + separator + fileStem + (j + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
input.close();
prog.close();
fileInput.close();
fileInput = new FileInputStream(new File(outDir + separator + fileStem
+ (j + 1) + "." + printer_id.substring(0, printer_id.length() - 8)));
prog = new ProgressMonitorInputStream(biomodelsim.frame(),
"Reading Reb2sac Output Data From "
+ new File(outDir + separator + fileStem + (j + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).getName(),
fileInput);
input = new BufferedInputStream(prog);
for (int i = 0; i < readCount; i++) {
input.read();
}
loop = false;
count++;
}
else {
j++;
}
}
else {
if (new File(outDir + separator + directory + separator + fileStem + (j + 1)
+ "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
input.close();
prog.close();
fileInput.close();
fileInput = new FileInputStream(new File(outDir + separator + directory
+ separator + fileStem + (j + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)));
prog = new ProgressMonitorInputStream(biomodelsim.frame(),
"Reading Reb2sac Output Data From "
+ new File(outDir + separator + directory + separator + fileStem
+ (j + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).getName(),
fileInput);
input = new BufferedInputStream(prog);
for (int i = 0; i < readCount; i++) {
input.read();
}
loop = false;
count++;
}
else {
j++;
}
}
}
}
reading = true;
while (reading) {
word = "";
readWord = true;
int read;
while (readWord) {
read = input.read();
cha = (char) read;
while (!Character.isWhitespace(cha) && cha != ',' && cha != ':' && cha != ';'
&& cha != '!' && cha != '?' && cha != '\"' && cha != '\'' && cha != '('
&& cha != ')' && cha != '{' && cha != '}' && cha != '[' && cha != ']'
&& cha != '<' && cha != '>' && cha != '_' && cha != '*' && cha != '='
&& read != -1) {
word += cha;
read = input.read();
cha = (char) read;
}
if (read == -1) {
reading = false;
first = false;
}
readWord = false;
}
int insert;
if (!word.equals("")) {
if (first) {
if (counter < graphSpecies.size()) {
insert = counter;
(average.get(insert)).add(Double.parseDouble(word));
if (insert == 0) {
(variance.get(insert)).add(Double.parseDouble(word));
}
else {
(variance.get(insert)).add(0.0);
}
}
else {
insert = counter % graphSpecies.size();
(average.get(insert)).add(Double.parseDouble(word));
if (insert == 0) {
(variance.get(insert)).add(Double.parseDouble(word));
}
else {
(variance.get(insert)).add(0.0);
}
}
}
else {
if (counter < graphSpecies.size()) {
insert = counter;
try {
double old = (average.get(insert)).get(insert / graphSpecies.size());
(average.get(insert)).set(insert / graphSpecies.size(), old
+ ((Double.parseDouble(word) - old) / (count + 1)));
double newMean = (average.get(insert)).get(insert / graphSpecies.size());
if (insert == 0) {
(variance.get(insert)).set(insert / graphSpecies.size(), old
+ ((Double.parseDouble(word) - old) / (count + 1)));
}
else {
double vary = (((count - 1) * (variance.get(insert)).get(insert
/ graphSpecies.size())) + (Double.parseDouble(word) - newMean)
* (Double.parseDouble(word) - old))
/ count;
(variance.get(insert)).set(insert / graphSpecies.size(), vary);
}
}
catch (Exception e2) {
(average.get(insert)).add(Double.parseDouble(word));
if (insert == 0) {
(variance.get(insert)).add(Double.parseDouble(word));
}
else {
(variance.get(insert)).add(0.0);
}
}
}
else {
insert = counter % graphSpecies.size();
try {
double old = (average.get(insert)).get(counter / graphSpecies.size());
(average.get(insert)).set(counter / graphSpecies.size(), old
+ ((Double.parseDouble(word) - old) / (count + 1)));
double newMean = (average.get(insert)).get(counter / graphSpecies.size());
if (insert == 0) {
(variance.get(insert)).set(counter / graphSpecies.size(), old
+ ((Double.parseDouble(word) - old) / (count + 1)));
}
else {
double vary = (((count - 1) * (variance.get(insert)).get(counter
/ graphSpecies.size())) + (Double.parseDouble(word) - newMean)
* (Double.parseDouble(word) - old))
/ count;
(variance.get(insert)).set(counter / graphSpecies.size(), vary);
}
}
catch (Exception e2) {
(average.get(insert)).add(Double.parseDouble(word));
if (insert == 0) {
(variance.get(insert)).add(Double.parseDouble(word));
}
else {
(variance.get(insert)).add(0.0);
}
}
}
}
counter++;
}
}
}
}
}
catch (Exception e1) {
}
}
deviation = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < variance.size(); i++) {
deviation.add(new ArrayList<Double>());
for (int j = 0; j < variance.get(i).size(); j++) {
deviation.get(i).add(variance.get(i).get(j));
}
}
for (int i = 1; i < deviation.size(); i++) {
for (int j = 0; j < deviation.get(i).size(); j++) {
deviation.get(i).set(j, Math.sqrt(deviation.get(i).get(j)));
}
}
input.close();
prog.close();
fileInput.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Error Reading Data!"
+ "\nThere was an error reading the simulation output data.", "Error Reading Data",
JOptionPane.ERROR_MESSAGE);
}
if (choice == 0) {
return average;
}
else if (choice == 1) {
return variance;
}
else {
return deviation;
}
}
public void save() {
if (timeSeries) {
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel());
graph.setProperty("x.min", XMin.getText());
graph.setProperty("x.max", XMax.getText());
graph.setProperty("x.scale", XScale.getText());
graph.setProperty("y.min", YMin.getText());
graph.setProperty("y.max", YMax.getText());
graph.setProperty("y.scale", YScale.getText());
graph.setProperty("auto.resize", "" + resize.isSelected());
for (int i = 0; i < graphed.size(); i++) {
graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected());
graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled());
graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber());
graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber());
graph.setProperty("species.name." + i, graphed.get(i).getSpecies());
graph.setProperty("species.id." + i, graphed.get(i).getID());
graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible());
graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint().getPaintName());
graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint().getShapeName());
graph.setProperty("species.directory." + i, graphed.get(i).getDirectory());
}
try {
FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName));
graph.store(store, "Graph Data");
store.close();
log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n");
change = false;
}
catch (Exception except) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Save Graph!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel());
for (int i = 0; i < probGraphed.size(); i++) {
graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber());
graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies());
graph.setProperty("species.id." + i, probGraphed.get(i).getID());
graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName());
graph.setProperty("species.directory." + i, probGraphed.get(i).getDirectory());
}
try {
FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName));
graph.store(store, "Probability Data");
store.close();
log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n");
change = false;
}
catch (Exception except) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Save Graph!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
private void open(String filename) {
if (timeSeries) {
Properties graph = new Properties();
try {
FileInputStream load = new FileInputStream(new File(filename));
graph.load(load);
load.close();
XMin.setText(graph.getProperty("x.min"));
XMax.setText(graph.getProperty("x.max"));
XScale.setText(graph.getProperty("x.scale"));
YMin.setText(graph.getProperty("y.min"));
YMax.setText(graph.getProperty("y.max"));
YScale.setText(graph.getProperty("y.scale"));
chart.setTitle(graph.getProperty("title"));
chart.getXYPlot().getDomainAxis().setLabel(graph.getProperty("x.axis"));
chart.getXYPlot().getRangeAxis().setLabel(graph.getProperty("y.axis"));
if (graph.getProperty("auto.resize").equals("true")) {
resize.setSelected(true);
}
else {
resize.setSelected(false);
}
int next = 0;
while (graph.containsKey("species.name." + next)) {
boolean connected, filled, visible;
if (graph.getProperty("species.connected." + next).equals("true")) {
connected = true;
}
else {
connected = false;
}
if (graph.getProperty("species.filled." + next).equals("true")) {
filled = true;
}
else {
filled = false;
}
if (graph.getProperty("species.visible." + next).equals("true")) {
visible = true;
}
else {
visible = false;
}
graphed.add(new GraphSpecies(shapes.get(graph.getProperty("species.shape." + next)),
colors.get(graph.getProperty("species.paint." + next)), filled, visible, connected,
graph.getProperty("species.run.number." + next), graph.getProperty("species.id."
+ next), graph.getProperty("species.name." + next), Integer.parseInt(graph
.getProperty("species.number." + next)), graph.getProperty("species.directory."
+ next)));
next++;
}
refresh();
}
catch (Exception except) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Load Graph!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
Properties graph = new Properties();
try {
FileInputStream load = new FileInputStream(new File(filename));
graph.load(load);
load.close();
chart.setTitle(graph.getProperty("title"));
chart.getCategoryPlot().getDomainAxis().setLabel(graph.getProperty("x.axis"));
chart.getCategoryPlot().getRangeAxis().setLabel(graph.getProperty("y.axis"));
int next = 0;
while (graph.containsKey("species.name." + next)) {
probGraphed.add(new GraphProbs(colors.get(graph.getProperty("species.paint." + next)),
graph.getProperty("species.paint." + next), graph.getProperty("species.id." + next),
graph.getProperty("species.name." + next), Integer.parseInt(graph
.getProperty("species.number." + next)), graph.getProperty("species.directory."
+ next)));
next++;
}
refreshProb();
}
catch (Exception except) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Load Graph!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
public void refresh() {
double minY = 0;
double maxY = 0;
double scaleY = 0;
double minX = 0;
double maxX = 0;
double scaleX = 0;
try {
minY = Double.parseDouble(YMin.getText().trim());
maxY = Double.parseDouble(YMax.getText().trim());
scaleY = Double.parseDouble(YScale.getText().trim());
minX = Double.parseDouble(XMin.getText().trim());
maxX = Double.parseDouble(XMax.getText().trim());
scaleX = Double.parseDouble(XScale.getText().trim());
NumberFormat num = NumberFormat.getInstance();
num.setMaximumFractionDigits(4);
num.setGroupingUsed(false);
minY = Double.parseDouble(num.format(minY));
maxY = Double.parseDouble(num.format(maxY));
scaleY = Double.parseDouble(num.format(scaleY));
minX = Double.parseDouble(num.format(minX));
maxX = Double.parseDouble(num.format(maxX));
scaleX = Double.parseDouble(num.format(scaleX));
}
catch (Exception e1) {
}
ArrayList<XYSeries> graphData = new ArrayList<XYSeries>();
XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < graphed.size(); i++) {
GraphSpecies index = graphed.get(i);
int j = i;
while ((j > 0)
&& (graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
graphed.set(j, graphed.get(j - 1));
j = j - 1;
}
graphed.set(j, index);
}
ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>();
HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>();
for (GraphSpecies g : graphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation")) {
if (new File(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
}
else {
data = readData(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), chart
.getXYPlot().getRangeAxis().getLabel(), g.getRunNumber(), null);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace('(', '~');
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e) {
ableToGraph = false;
}
if (ableToGraph) {
int nextOne = 1;
while (!new File(outDir + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
}
else {
data = readData(outDir + separator + "run-1."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), chart
.getXYPlot().getRangeAxis().getLabel(), g.getRunNumber().toLowerCase(), null);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace('(', '~');
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
else {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation")) {
if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + g.getRunNumber()
+ "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
}
else {
data = readData(outDir + separator + g.getDirectory() + separator + g.getRunNumber()
+ "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(),
chart.getXYPlot().getRangeAxis().getLabel(), g.getRunNumber(), g.getDirectory());
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace('(', '~');
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir + separator + g.getDirectory()).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e) {
ableToGraph = false;
}
if (ableToGraph) {
int nextOne = 1;
while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + nextOne
+ "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "run-" + nextOne
+ "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
}
else {
data = readData(outDir + separator + g.getDirectory() + separator + "run-1."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), chart
.getXYPlot().getRangeAxis().getLabel(), g.getRunNumber().toLowerCase(), g
.getDirectory());
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace('(', '~');
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
}
for (GraphSpecies g : unableToGraph) {
graphed.remove(g);
}
XYSeriesCollection dataset = new XYSeriesCollection();
for (int i = 0; i < graphData.size(); i++) {
dataset.addSeries(graphData.get(i));
}
fixGraph(chart.getTitle().getText(), chart.getXYPlot().getDomainAxis().getLabel(), chart
.getXYPlot().getRangeAxis().getLabel(), dataset);
chart.getXYPlot().setRenderer(rend);
XYPlot plot = chart.getXYPlot();
if (resize.isSelected()) {
resize(dataset);
}
else {
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minY, maxY);
axis.setTickUnit(new NumberTickUnit(scaleY));
axis = (NumberAxis) plot.getDomainAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minX, maxX);
axis.setTickUnit(new NumberTickUnit(scaleX));
}
}
private class ShapeAndPaint {
private Shape shape;
private Paint paint;
private ShapeAndPaint(Shape s, Paint p) {
shape = s;
paint = p;
}
private Shape getShape() {
return shape;
}
private Paint getPaint() {
return paint;
}
private String getShapeName() {
Object[] set = shapes.keySet().toArray();
for (int i = 0; i < set.length; i++) {
if (shape == shapes.get(set[i])) {
return (String) set[i];
}
}
return "Unknown Shape";
}
private String getPaintName() {
Object[] set = colors.keySet().toArray();
for (int i = 0; i < set.length; i++) {
if (paint == colors.get(set[i])) {
return (String) set[i];
}
}
return "Unknown Color";
}
public void setPaint(String paint) {
this.paint = colors.get(paint);
}
public void setShape(String shape) {
this.shape = shapes.get(shape);
}
}
private class GraphSpecies {
private ShapeAndPaint sP;
private boolean filled, visible, connected;
private String runNumber, species, directory, id;
private int number;
private GraphSpecies(Shape s, Paint p, boolean filled, boolean visible, boolean connected,
String runNumber, String id, String species, int number, String directory) {
sP = new ShapeAndPaint(s, p);
this.filled = filled;
this.visible = visible;
this.connected = connected;
this.runNumber = runNumber;
this.species = species;
this.number = number;
this.directory = directory;
this.id = id;
}
public void setNumber(int number) {
this.number = number;
}
private void setSpecies(String species) {
this.species = species;
}
private void setPaint(String paint) {
sP.setPaint(paint);
}
private void setShape(String shape) {
sP.setShape(shape);
}
private void setVisible(boolean b) {
visible = b;
}
private void setFilled(boolean b) {
filled = b;
}
private void setConnected(boolean b) {
connected = b;
}
private int getNumber() {
return number;
}
private String getSpecies() {
return species;
}
private ShapeAndPaint getShapeAndPaint() {
return sP;
}
private boolean getFilled() {
return filled;
}
private boolean getVisible() {
return visible;
}
private boolean getConnected() {
return connected;
}
private String getRunNumber() {
return runNumber;
}
private String getDirectory() {
return directory;
}
private String getID() {
return id;
}
}
public void setDirectory(String newDirectory) {
outDir = newDirectory;
}
public void setGraphName(String graphName) {
this.graphName = graphName;
}
public boolean hasChanged() {
return change;
}
private void probGraph(String label) {
chart = ChartFactory.createBarChart(label, "", "Percent", new DefaultCategoryDataset(),
PlotOrientation.VERTICAL, true, true, false);
ChartPanel graph = new ChartPanel(chart);
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Click here to create graph");
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
graph.addMouseListener(this);
change = false;
// creates the buttons for the graph frame
JPanel ButtonHolder = new JPanel();
save = new JButton("Save Graph");
export = new JButton("Export");
save.addActionListener(this);
export.addActionListener(this);
ButtonHolder.add(save);
ButtonHolder.add(export);
// puts all the components of the graph gui into a display panel
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, ButtonHolder, null);
splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
this.add(splitPane, "South");
}
private void editProbGraph() {
final ArrayList<GraphProbs> old = new ArrayList<GraphProbs>();
for (GraphProbs g : probGraphed) {
old.add(g);
}
JPanel titlePanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Title:");
JLabel xLabel = new JLabel("X-Axis Label:");
JLabel yLabel = new JLabel("Y-Axis Label:");
final JTextField title = new JTextField(chart.getTitle().getText(), 5);
final JTextField x = new JTextField(chart.getCategoryPlot().getDomainAxis().getLabel(), 5);
final JTextField y = new JTextField(chart.getCategoryPlot().getRangeAxis().getLabel(), 5);
String simDirString = outDir.split(separator)[outDir.split(separator).length - 1];
final DefaultMutableTreeNode simDir = new DefaultMutableTreeNode(simDirString);
String[] files = new File(outDir).list();
for (int i = 1; i < files.length; i++) {
String index = files[i];
int j = i;
while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) {
files[j] = files[j - 1];
j = j - 1;
}
files[j] = index;
}
final ArrayList<String> directories = new ArrayList<String>();
for (String file : files) {
if (file.length() > 3 && file.substring(file.length() - 4).equals(".txt")) {
if (file.contains("sim-rep")) {
simDir.add(new DefaultMutableTreeNode(file.substring(0, file.length() - 4)));
}
}
else if (new File(outDir + separator + file).isDirectory()) {
boolean addIt = false;
for (String getFile : new File(outDir + separator + file).list()) {
if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals(".txt")
&& getFile.contains("sim-rep")) {
addIt = true;
}
}
if (addIt) {
directories.add(file);
DefaultMutableTreeNode d = new DefaultMutableTreeNode(file);
for (String f : new File(outDir + separator + file).list()) {
if (f.equals("sim-rep.txt")) {
d.add(new DefaultMutableTreeNode(f.substring(0, f.length() - 4)));
}
}
simDir.add(d);
}
}
}
if (simDir.getChildCount() == 0) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "No data to graph."
+ "\nPerform some simutations to create some data first.", "No Data",
JOptionPane.PLAIN_MESSAGE);
}
else {
final JTree tree = new JTree(simDir);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.expandRow(i);
}
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
final JPanel specPanel = new JPanel();
boolean stop = false;
int selectionRow = 1;
for (int i = 1; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (selected.equals(lastSelected)) {
stop = true;
selectionRow = i;
break;
}
}
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
if (!directories.contains(node.toString())) {
selected = node.toString();
int select;
if (selected.equals("sim-rep")) {
select = 0;
}
else {
select = -1;
}
if (select != -1) {
specPanel.removeAll();
if (directories.contains(node.getParent().toString())) {
specPanel.add(fixProbChoices(node.getParent().toString()));
}
else {
specPanel.add(fixProbChoices(""));
}
specPanel.revalidate();
specPanel.repaint();
for (int i = 0; i < series.size(); i++) {
series.get(i).setText(graphProbs.get(i));
}
for (int i = 0; i < boxes.size(); i++) {
boxes.get(i).setSelected(false);
}
if (directories.contains(node.getParent().toString())) {
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(node.getParent().toString())) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName());
}
}
}
else {
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName());
}
}
}
boolean allChecked = true;
for (int i = 0; i < boxes.size(); i++) {
if (!boxes.get(i).isSelected()) {
allChecked = false;
String s = "";
if (directories.contains(node.getParent().toString())) {
s = "(" + node.getParent().toString() + ")";
}
String text = series.get(i).getText();
String end = "";
if (!s.equals("")) {
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
}
boxes.get(i).setName(text);
series.get(i).setText(text);
colorsCombo.get(i).setSelectedIndex(0);
}
else {
String s = "";
if (directories.contains(node.getParent().toString())) {
s = "(" + node.getParent().toString() + ")";
}
String text = graphProbs.get(i);
String end = "";
if (!s.equals("")) {
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
}
boxes.get(i).setName(text);
}
}
if (allChecked) {
use.setSelected(true);
}
else {
use.setSelected(false);
}
}
}
else {
specPanel.removeAll();
specPanel.revalidate();
specPanel.repaint();
}
}
});
if (!stop) {
tree.setSelectionRow(0);
tree.setSelectionRow(1);
}
else {
tree.setSelectionRow(0);
tree.setSelectionRow(selectionRow);
}
JScrollPane scroll = new JScrollPane();
scroll.setPreferredSize(new Dimension(1050, 500));
JPanel editPanel = new JPanel(new BorderLayout());
editPanel.add(specPanel, "Center");
editPanel.add(scrollpane, "West");
scroll.setViewportView(editPanel);
final JButton deselect = new JButton("Deselect All");
deselect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int size = probGraphed.size();
for (int i = 0; i < size; i++) {
probGraphed.remove();
}
if (tree.getSelectionCount() > 0) {
int selectedRow = tree.getSelectionRows()[0];
tree.setSelectionRow(0);
tree.setSelectionRow(selectedRow);
}
}
});
JPanel titlePanel1 = new JPanel(new GridLayout(1, 6));
JPanel titlePanel2 = new JPanel(new GridLayout(1, 6));
titlePanel1.add(titleLabel);
titlePanel1.add(title);
titlePanel1.add(xLabel);
titlePanel1.add(x);
titlePanel1.add(yLabel);
titlePanel1.add(y);
titlePanel2.add(new JPanel());
JPanel deselectPanel = new JPanel();
deselectPanel.add(deselect);
titlePanel2.add(deselectPanel);
titlePanel2.add(new JPanel());
titlePanel2.add(new JPanel());
titlePanel2.add(new JPanel());
titlePanel2.add(new JPanel());
titlePanel.add(titlePanel1, "Center");
titlePanel.add(titlePanel2, "South");
JPanel all = new JPanel(new BorderLayout());
all.add(titlePanel, "North");
all.add(scroll, "Center");
Object[] options = { "Ok", "Cancel" };
int value = JOptionPane.showOptionDialog(biomodelsim.frame(), all, "Edit Probability Graph",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
change = true;
lastSelected = selected;
selected = "";
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0)
&& (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt")
.exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator
+ "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), histDataset,
rend);
}
else {
selected = "";
int size = probGraphed.size();
for (int i = 0; i < size; i++) {
probGraphed.remove();
}
for (GraphProbs g : old) {
probGraphed.add(g);
}
}
}
}
private JPanel fixProbChoices(final String directory) {
if (directory.equals("")) {
readProbSpecies(outDir + separator + "sim-rep.txt");
}
else {
readProbSpecies(outDir + separator + directory + separator + "sim-rep.txt");
}
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
j = j - 1;
}
graphProbs.set(j, index);
}
JPanel speciesPanel1 = new JPanel(new GridLayout(graphProbs.size() + 1, 1));
JPanel speciesPanel2 = new JPanel(new GridLayout(graphProbs.size() + 1, 2));
use = new JCheckBox("Use");
JLabel specs = new JLabel("Species");
JLabel color = new JLabel("Color");
boxes = new ArrayList<JCheckBox>();
series = new ArrayList<JTextField>();
colorsCombo = new ArrayList<JComboBox>();
use.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (use.isSelected()) {
for (JCheckBox box : boxes) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : boxes) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
speciesPanel1.add(use);
speciesPanel2.add(specs);
speciesPanel2.add(color);
final HashMap<String, Paint> colory = this.colors;
for (int i = 0; i < graphProbs.size(); i++) {
JCheckBox temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
String s = series.get(i).getText();
((JCheckBox) e.getSource()).setSelected(false);
int[] cols = new int[34];
for (int k = 0; k < boxes.size(); k++) {
if (boxes.get(k).isSelected()) {
if (colorsCombo.get(k).getSelectedItem().equals("Red")) {
cols[0]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) {
cols[1]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green")) {
cols[2]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) {
cols[3]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) {
cols[4]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) {
cols[5]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) {
cols[6]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) {
cols[7]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) {
cols[8]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) {
cols[9]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Dark)")) {
cols[10]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Dark)")) {
cols[11]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Dark)")) {
cols[12]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Black")) {
cols[14]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red ")) {
cols[15]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue ")) {
cols[16]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green ")) {
cols[17]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow ")) {
cols[18]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta ")) {
cols[19]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan ")) {
cols[20]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Light)")) {
cols[21]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Extra Dark)")) {
cols[22]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Extra Dark)")) {
cols[23]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Extra Dark)")) {
cols[24]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Extra Dark)")) {
cols[25]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Extra Dark)")) {
cols[26]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Extra Dark)")) {
cols[27]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) {
cols[28]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Light)")) {
cols[29]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Light)")) {
cols[30]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Light)")) {
cols[31]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Light)")) {
cols[32]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Light)")) {
cols[33]++;
}
}
}
for (GraphProbs graph : probGraphed) {
if (graph.getPaintName().equals("Red")) {
cols[0]++;
}
else if (graph.getPaintName().equals("Blue")) {
cols[1]++;
}
else if (graph.getPaintName().equals("Green")) {
cols[2]++;
}
else if (graph.getPaintName().equals("Yellow")) {
cols[3]++;
}
else if (graph.getPaintName().equals("Magenta")) {
cols[4]++;
}
else if (graph.getPaintName().equals("Cyan")) {
cols[5]++;
}
else if (graph.getPaintName().equals("Tan")) {
cols[6]++;
}
else if (graph.getPaintName().equals("Gray (Dark)")) {
cols[7]++;
}
else if (graph.getPaintName().equals("Red (Dark)")) {
cols[8]++;
}
else if (graph.getPaintName().equals("Blue (Dark)")) {
cols[9]++;
}
else if (graph.getPaintName().equals("Green (Dark)")) {
cols[10]++;
}
else if (graph.getPaintName().equals("Yellow (Dark)")) {
cols[11]++;
}
else if (graph.getPaintName().equals("Magenta (Dark)")) {
cols[12]++;
}
else if (graph.getPaintName().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (graph.getPaintName().equals("Black")) {
cols[14]++;
}
else if (graph.getPaintName().equals("Red ")) {
cols[15]++;
}
else if (graph.getPaintName().equals("Blue ")) {
cols[16]++;
}
else if (graph.getPaintName().equals("Green ")) {
cols[17]++;
}
else if (graph.getPaintName().equals("Yellow ")) {
cols[18]++;
}
else if (graph.getPaintName().equals("Magenta ")) {
cols[19]++;
}
else if (graph.getPaintName().equals("Cyan ")) {
cols[20]++;
}
else if (graph.getPaintName().equals("Gray (Light)")) {
cols[21]++;
}
else if (graph.getPaintName().equals("Red (Extra Dark)")) {
cols[22]++;
}
else if (graph.getPaintName().equals("Blue (Extra Dark)")) {
cols[23]++;
}
else if (graph.getPaintName().equals("Green (Extra Dark)")) {
cols[24]++;
}
else if (graph.getPaintName().equals("Yellow (Extra Dark)")) {
cols[25]++;
}
else if (graph.getPaintName().equals("Magenta (Extra Dark)")) {
cols[26]++;
}
else if (graph.getPaintName().equals("Cyan (Extra Dark)")) {
cols[27]++;
}
else if (graph.getPaintName().equals("Red (Light)")) {
cols[28]++;
}
else if (graph.getPaintName().equals("Blue (Light)")) {
cols[29]++;
}
else if (graph.getPaintName().equals("Green (Light)")) {
cols[30]++;
}
else if (graph.getPaintName().equals("Yellow (Light)")) {
cols[31]++;
}
else if (graph.getPaintName().equals("Magenta (Light)")) {
cols[32]++;
}
else if (graph.getPaintName().equals("Cyan (Light)")) {
cols[33]++;
}
}
((JCheckBox) e.getSource()).setSelected(true);
series.get(i).setText(s);
int colorSet = 0;
for (int j = 1; j < cols.length; j++) {
if (cols[j] < cols[colorSet]) {
colorSet = j;
}
}
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
for (int j = 0; j < colorSet; j++) {
draw.getNextPaint();
}
Paint paint = draw.getNextPaint();
Object[] set = colory.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (paint == colory.get(set[j])) {
colorsCombo.get(i).setSelectedItem(set[j]);
}
}
boolean allChecked = true;
for (JCheckBox temp : boxes) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
use.setSelected(true);
}
probGraphed.add(new GraphProbs(colory.get(colorsCombo.get(i).getSelectedItem()),
(String) colorsCombo.get(i).getSelectedItem(), boxes.get(i).getName(), series
.get(i).getText().trim(), i, directory));
}
else {
ArrayList<GraphProbs> remove = new ArrayList<GraphProbs>();
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
remove.add(g);
}
}
for (GraphProbs g : remove) {
probGraphed.remove(g);
}
use.setSelected(false);
colorsCombo.get(i).setSelectedIndex(0);
}
}
});
boxes.add(temp);
JTextField seriesName = new JTextField(graphProbs.get(i));
seriesName.setName("" + i);
seriesName.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyReleased(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyTyped(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
});
series.add(seriesName);
Object[] col = this.colors.keySet().toArray();
Arrays.sort(col);
JComboBox colBox = new JComboBox(col);
colBox.setActionCommand("" + i);
colBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaintName((String) ((JComboBox) e.getSource()).getSelectedItem());
g.setPaint(colory.get(((JComboBox) e.getSource()).getSelectedItem()));
}
}
}
});
colorsCombo.add(colBox);
speciesPanel1.add(boxes.get(i));
speciesPanel2.add(series.get(i));
speciesPanel2.add(colorsCombo.get(i));
}
JPanel speciesPanel = new JPanel(new BorderLayout());
speciesPanel.add(speciesPanel1, "West");
speciesPanel.add(speciesPanel2, "Center");
return speciesPanel;
}
private void readProbSpecies(String file) {
graphProbs = new ArrayList<String>();
ArrayList<String> data = new ArrayList<String>();
try {
Scanner s = new Scanner(new File(file));
while (s.hasNextLine()) {
String[] ss = s.nextLine().split(" ");
if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination")
&& ss[3].equals("count:") && ss[4].equals("0")) {
return;
}
if (data.size() == 0) {
for (String add : ss) {
data.add(add);
}
}
else {
for (int i = 0; i < ss.length; i++) {
data.set(i, data.get(i) + " " + ss[i]);
}
}
}
}
catch (Exception e) {
}
for (String s : data) {
if (!s.split(" ")[0].equals("#total")) {
graphProbs.add(s.split(" ")[0]);
}
}
}
private double[] readProbs(String file) {
ArrayList<String> data = new ArrayList<String>();
try {
Scanner s = new Scanner(new File(file));
while (s.hasNextLine()) {
String[] ss = s.nextLine().split(" ");
if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination")
&& ss[3].equals("count:") && ss[4].equals("0")) {
return new double[0];
}
if (data.size() == 0) {
for (String add : ss) {
data.add(add);
}
}
else {
for (int i = 0; i < ss.length; i++) {
data.set(i, data.get(i) + " " + ss[i]);
}
}
}
}
catch (Exception e) {
}
double[] dataSet = new double[data.size()];
double total = 0;
int i = 0;
if (data.get(0).split(" ")[0].equals("#total")) {
total = Double.parseDouble(data.get(0).split(" ")[1]);
i = 1;
}
for (; i < data.size(); i++) {
if (total == 0) {
dataSet[i] = Double.parseDouble(data.get(i).split(" ")[1]);
}
else {
dataSet[i - 1] = 100 * ((Double.parseDouble(data.get(i).split(" ")[1])) / total);
}
}
return dataSet;
}
private void fixProbGraph(String label, String xLabel, String yLabel,
DefaultCategoryDataset dataset, BarRenderer rend) {
chart = ChartFactory.createBarChart(label, xLabel, yLabel, dataset, PlotOrientation.VERTICAL,
true, true, false);
chart.getCategoryPlot().setRenderer(rend);
ChartPanel graph = new ChartPanel(chart);
if (probGraphed.isEmpty()) {
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Click here to create graph");
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
}
graph.addMouseListener(this);
JPanel ButtonHolder = new JPanel();
save = new JButton("Save Graph");
export = new JButton("Export");
save.addActionListener(this);
export.addActionListener(this);
ButtonHolder.add(save);
ButtonHolder.add(export);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, ButtonHolder, null);
splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
this.add(splitPane, "South");
this.revalidate();
}
public void refreshProb() {
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0)
&& (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator
+ "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis().getLabel(),
chart.getCategoryPlot().getRangeAxis().getLabel(), histDataset, rend);
}
private class GraphProbs {
private Paint paint;
private String species, directory, id, paintName;
private int number;
private GraphProbs(Paint paint, String paintName, String id, String species, int number,
String directory) {
this.paint = paint;
this.paintName = paintName;
this.species = species;
this.number = number;
this.directory = directory;
this.id = id;
}
private Paint getPaint() {
return paint;
}
private void setPaint(Paint p) {
paint = p;
}
private String getPaintName() {
return paintName;
}
private void setPaintName(String p) {
paintName = p;
}
private String getSpecies() {
return species;
}
private void setSpecies(String s) {
species = s;
}
private String getDirectory() {
return directory;
}
private String getID() {
return id;
}
private int getNumber() {
return number;
}
}
}
| gui/src/graph/Graph.java | package graph;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import org.apache.batik.dom.*;
import org.apache.batik.svggen.*;
import org.jfree.chart.*;
import org.jfree.chart.axis.*;
import org.jfree.chart.event.*;
import org.jfree.chart.plot.*;
import org.jfree.chart.renderer.category.*;
import org.jfree.chart.renderer.xy.*;
import org.jfree.data.category.*;
import org.jfree.data.xy.*;
import org.jibble.epsgraphics.EpsGraphics2D;
import org.w3c.dom.*;
import com.lowagie.text.Document;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.*;
import biomodelsim.*;
import buttons.*;
/**
* This is the Graph class. It takes in data and draws a graph of that data. The
* Graph class implements the ActionListener class, the ChartProgressListener
* class, and the MouseListener class. This allows the Graph class to perform
* actions when buttons are pressed, when the chart is drawn, or when the chart
* is clicked.
*
* @author Curtis Madsen
*/
public class Graph extends JPanel implements ActionListener, MouseListener, ChartProgressListener {
private static final long serialVersionUID = 4350596002373546900L;
private JFreeChart chart; // Graph of the output data
private XYSeriesCollection curData; // Data in the current graph
private String outDir; // output directory
private String printer_id; // printer id
/*
* Text fields used to change the graph window
*/
private JTextField XMin, XMax, XScale, YMin, YMax, YScale;
private ArrayList<String> graphSpecies; // names of species in the graph
private String savedPics; // directory for saved pictures
private BioSim biomodelsim; // tstubd gui
private JButton save;
private JButton export; // buttons
// private JButton exportJPeg, exportPng, exportPdf, exportEps, exportSvg,
// exportCsv; // buttons
private HashMap<String, Paint> colors;
private HashMap<String, Shape> shapes;
private String selected, lastSelected;
private LinkedList<GraphSpecies> graphed;
private LinkedList<GraphProbs> probGraphed;
private JCheckBox resize;
private Log log;
private ArrayList<JCheckBox> boxes;
private ArrayList<JTextField> series;
private ArrayList<JComboBox> colorsCombo;
private ArrayList<JComboBox> shapesCombo;
private ArrayList<JCheckBox> connected;
private ArrayList<JCheckBox> visible;
private ArrayList<JCheckBox> filled;
private JCheckBox use;
private JCheckBox connectedLabel;
private JCheckBox visibleLabel;
private JCheckBox filledLabel;
private String graphName;
private String separator;
private boolean change;
private boolean timeSeries;
private ArrayList<String> graphProbs;
/**
* Creates a Graph Object from the data given and calls the private graph
* helper method.
*/
public Graph(String printer_track_quantity, String label, String printer_id, String outDir,
String time, BioSim biomodelsim, String open, Log log, String graphName, boolean timeSeries) {
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
// initializes member variables
this.log = log;
this.timeSeries = timeSeries;
if (timeSeries) {
if (graphName != null) {
this.graphName = graphName;
}
else {
this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".grf";
}
}
else {
if (graphName != null) {
this.graphName = graphName;
}
else {
this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".prb";
}
}
this.outDir = outDir;
this.printer_id = printer_id;
this.biomodelsim = biomodelsim;
XYSeriesCollection data = new XYSeriesCollection();
// graph the output data
if (timeSeries) {
setUpShapesAndColors();
graphed = new LinkedList<GraphSpecies>();
selected = "";
lastSelected = "";
graph(printer_track_quantity, label, data, time);
if (open != null) {
open(open);
}
}
else {
setUpShapesAndColors();
probGraphed = new LinkedList<GraphProbs>();
selected = "";
lastSelected = "";
probGraph(label);
if (open != null) {
open(open);
}
}
}
/**
* This private helper method calls the private readData method, sets up a
* graph frame, and graphs the data.
*
* @param dataset
* @param time
*/
private void graph(String printer_track_quantity, String label, XYSeriesCollection dataset,
String time) {
chart = ChartFactory.createXYLineChart(label, time, printer_track_quantity, dataset,
PlotOrientation.VERTICAL, true, true, false);
chart.addProgressListener(this);
ChartPanel graph = new ChartPanel(chart);
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Click here to create graph");
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
graph.addMouseListener(this);
change = false;
// creates text fields for changing the graph's dimensions
resize = new JCheckBox("Auto Resize");
resize.setSelected(true);
XMin = new JTextField();
XMax = new JTextField();
XScale = new JTextField();
YMin = new JTextField();
YMax = new JTextField();
YScale = new JTextField();
// creates the buttons for the graph frame
JPanel ButtonHolder = new JPanel();
save = new JButton("Save Graph");
export = new JButton("Export");
// exportJPeg = new JButton("Export As JPEG");
// exportPng = new JButton("Export As PNG");
// exportPdf = new JButton("Export As PDF");
// exportEps = new JButton("Export As EPS");
// exportSvg = new JButton("Export As SVG");
// exportCsv = new JButton("Export As CSV");
save.addActionListener(this);
export.addActionListener(this);
// exportJPeg.addActionListener(this);
// exportPng.addActionListener(this);
// exportPdf.addActionListener(this);
// exportEps.addActionListener(this);
// exportSvg.addActionListener(this);
// exportCsv.addActionListener(this);
ButtonHolder.add(save);
ButtonHolder.add(export);
// ButtonHolder.add(exportJPeg);
// ButtonHolder.add(exportPng);
// ButtonHolder.add(exportPdf);
// ButtonHolder.add(exportEps);
// ButtonHolder.add(exportSvg);
// ButtonHolder.add(exportCsv);
// puts all the components of the graph gui into a display panel
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, ButtonHolder, null);
splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
this.add(splitPane, "South");
// determines maximum and minimum values and resizes
resize(dataset);
this.revalidate();
}
private void readGraphSpecies(String file, Component component) {
component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
FileInputStream fileInput = new FileInputStream(new File(file));
ProgressMonitorInputStream prog = new ProgressMonitorInputStream(component,
"Reading Reb2sac Output Data From " + new File(file).getName(), fileInput);
InputStream input = new BufferedInputStream(prog);
graphSpecies = new ArrayList<String>();
boolean reading = true;
char cha;
int readCount = 0;
while (reading) {
String word = "";
boolean readWord = true;
while (readWord) {
int read = input.read();
readCount++;
if (read == -1) {
reading = false;
readWord = false;
}
cha = (char) read;
if (Character.isWhitespace(cha)) {
input.mark(3);
char next = (char) input.read();
char after = (char) input.read();
String check = "" + next + after;
if (word.equals("") || word.equals("0") || check.equals("0,")) {
readWord = false;
}
else {
word += cha;
}
input.reset();
}
else if (cha == ',' || cha == ':' || cha == ';' || cha == '\"' || cha == '\''
|| cha == '(' || cha == ')' || cha == '[' || cha == ']') {
readWord = false;
}
else if (read != -1) {
word += cha;
}
}
int getNum;
try {
getNum = Integer.parseInt(word);
if (getNum == 0) {
int read = 0;
while (read != -1) {
read = input.read();
}
}
}
catch (Exception e1) {
if (word.equals("")) {
}
else {
graphSpecies.add(word);
}
}
}
input.close();
prog.close();
fileInput.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(component, "Error Reading Data!"
+ "\nThere was an error reading the simulation output data.", "Error Reading Data",
JOptionPane.ERROR_MESSAGE);
}
component.setCursor(null);
}
/**
* This private helper method parses the output file of ODE, monte carlo, and
* markov abstractions.
*/
private ArrayList<ArrayList<Double>> readData(String file, Component component,
String printer_track_quantity, String label, String directory) {
String[] s = file.split(separator);
String getLast = s[s.length - 1];
String stem = "";
int t = 0;
try {
while (!Character.isDigit(getLast.charAt(t))) {
stem += getLast.charAt(t);
t++;
}
}
catch (Exception e) {
}
if (label.contains("variance")) {
return calculateAverageVarianceDeviation(file, stem, 1, directory);
}
else if (label.contains("deviation")) {
return calculateAverageVarianceDeviation(file, stem, 2, directory);
}
else if (label.contains("average")) {
return calculateAverageVarianceDeviation(file, stem, 0, directory);
}
else {
ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>();
component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
FileInputStream fileInput = new FileInputStream(new File(file));
ProgressMonitorInputStream prog = new ProgressMonitorInputStream(component,
"Reading Reb2sac Output Data From " + new File(file).getName(), fileInput);
InputStream input = new BufferedInputStream(prog);
boolean reading = true;
char cha;
int readCount = 0;
while (reading) {
String word = "";
boolean readWord = true;
while (readWord) {
int read = input.read();
readCount++;
if (read == -1) {
reading = false;
readWord = false;
}
cha = (char) read;
if (Character.isWhitespace(cha)) {
input.mark(3);
char next = (char) input.read();
char after = (char) input.read();
String check = "" + next + after;
if (word.equals("") || word.equals("0") || check.equals("0,")) {
readWord = false;
}
else {
word += cha;
}
input.reset();
}
else if (cha == ',' || cha == ':' || cha == ';' || cha == '!' || cha == '?'
|| cha == '\"' || cha == '\'' || cha == '(' || cha == ')' || cha == '{'
|| cha == '}' || cha == '[' || cha == ']' || cha == '<' || cha == '>' || cha == '*'
|| cha == '=' || cha == '#') {
readWord = false;
}
else if (read != -1) {
word += cha;
}
}
int getNum;
try {
getNum = Integer.parseInt(word);
if (getNum == 0) {
for (int i = 0; i < graphSpecies.size(); i++) {
data.add(new ArrayList<Double>());
}
(data.get(0)).add(0.0);
int counter = 1;
reading = true;
while (reading) {
word = "";
readWord = true;
int read;
while (readWord) {
read = input.read();
cha = (char) read;
while (!Character.isWhitespace(cha) && cha != ',' && cha != ':' && cha != ';'
&& cha != '!' && cha != '?' && cha != '\"' && cha != '\'' && cha != '('
&& cha != ')' && cha != '{' && cha != '}' && cha != '[' && cha != ']'
&& cha != '<' && cha != '>' && cha != '_' && cha != '*' && cha != '='
&& read != -1) {
word += cha;
read = input.read();
cha = (char) read;
}
if (read == -1) {
reading = false;
}
readWord = false;
}
int insert;
if (!word.equals("")) {
if (counter < graphSpecies.size()) {
insert = counter;
}
else {
insert = counter % graphSpecies.size();
}
(data.get(insert)).add(Double.parseDouble(word));
counter++;
}
}
}
}
catch (Exception e1) {
}
}
input.close();
prog.close();
fileInput.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(component, "Error Reading Data!"
+ "\nThere was an error reading the simulation output data.", "Error Reading Data",
JOptionPane.ERROR_MESSAGE);
}
component.setCursor(null);
return data;
}
}
/**
* This method adds and removes plots from the graph depending on what check
* boxes are selected.
*/
public void actionPerformed(ActionEvent e) {
// if the save button is clicked
if (e.getSource() == save) {
save();
}
// if the export button is clicked
else if (e.getSource() == export) {
export();
}
// // if the export as jpeg button is clicked
// else if (e.getSource() == exportJPeg) {
// export(0);
// }
// // if the export as png button is clicked
// else if (e.getSource() == exportPng) {
// export(1);
// }
// // if the export as pdf button is clicked
// else if (e.getSource() == exportPdf) {
// export(2);
// }
// // if the export as eps button is clicked
// else if (e.getSource() == exportEps) {
// export(3);
// }
// // if the export as svg button is clicked
// else if (e.getSource() == exportSvg) {
// export(4);
// } else if (e.getSource() == exportCsv) {
// export(5);
// }
}
/**
* Private method used to auto resize the graph.
*/
private void resize(XYSeriesCollection dataset) {
NumberFormat num = NumberFormat.getInstance();
num.setMaximumFractionDigits(4);
num.setGroupingUsed(false);
XYPlot plot = chart.getXYPlot();
XYItemRenderer rend = plot.getRenderer();
double minY = Double.MAX_VALUE;
double maxY = Double.MIN_VALUE;
double minX = Double.MAX_VALUE;
double maxX = Double.MIN_VALUE;
for (int j = 0; j < dataset.getSeriesCount(); j++) {
XYSeries series = dataset.getSeries(j);
Boolean visible = rend.getSeriesVisible(j);
if (visible == null || visible.equals(true)) {
for (int k = 0; k < series.getItemCount(); k++) {
maxY = Math.max(series.getY(k).doubleValue(), maxY);
minY = Math.min(series.getY(k).doubleValue(), minY);
maxX = Math.max(series.getX(k).doubleValue(), maxX);
minX = Math.min(series.getX(k).doubleValue(), minX);
}
}
}
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
if (minY == Double.MAX_VALUE || maxY == Double.MIN_VALUE) {
axis.setRange(-1, 1);
}
else if ((maxY - minY) < .001) {
axis.setRange(minY - 1, maxY + 1);
}
else {
axis.setRange(Double.parseDouble(num.format(minY - (Math.abs(minY) * .1))), Double
.parseDouble(num.format(maxY + (Math.abs(maxY) * .1))));
}
axis.setAutoTickUnitSelection(true);
axis = (NumberAxis) plot.getDomainAxis();
if (minX == Double.MAX_VALUE || maxX == Double.MIN_VALUE) {
axis.setRange(-1, 1);
}
else if ((maxX - minX) < .001) {
axis.setRange(minX - 1, maxX + 1);
}
else {
axis.setRange(Double.parseDouble(num.format(minX)), Double.parseDouble(num.format(maxX)));
}
axis.setAutoTickUnitSelection(true);
}
/**
* After the chart is redrawn, this method calculates the x and y scale and
* updates those text fields.
*/
public void chartProgress(ChartProgressEvent e) {
// if the chart drawing is started
if (e.getType() == ChartProgressEvent.DRAWING_STARTED) {
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
// if the chart drawing is finished
else if (e.getType() == ChartProgressEvent.DRAWING_FINISHED) {
this.setCursor(null);
JFreeChart chart = e.getChart();
XYPlot plot = (XYPlot) chart.getPlot();
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
YMin.setText("" + axis.getLowerBound());
YMax.setText("" + axis.getUpperBound());
YScale.setText("" + axis.getTickUnit().getSize());
axis = (NumberAxis) plot.getDomainAxis();
XMin.setText("" + axis.getLowerBound());
XMax.setText("" + axis.getUpperBound());
XScale.setText("" + axis.getTickUnit().getSize());
}
}
/**
* Invoked when the mouse is clicked on the chart. Allows the user to edit the
* title and labels of the chart.
*/
public void mouseClicked(MouseEvent e) {
if (timeSeries) {
editGraph();
}
else {
editProbGraph();
}
}
/**
* This method currently does nothing.
*/
public void mousePressed(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseReleased(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseEntered(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseExited(MouseEvent e) {
}
private void setUpShapesAndColors() {
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
colors = new HashMap<String, Paint>();
shapes = new HashMap<String, Shape>();
colors.put("Red", draw.getNextPaint());
colors.put("Blue", draw.getNextPaint());
colors.put("Green", draw.getNextPaint());
colors.put("Yellow", draw.getNextPaint());
colors.put("Magenta", draw.getNextPaint());
colors.put("Cyan", draw.getNextPaint());
colors.put("Tan", draw.getNextPaint());
colors.put("Gray (Dark)", draw.getNextPaint());
colors.put("Red (Dark)", draw.getNextPaint());
colors.put("Blue (Dark)", draw.getNextPaint());
colors.put("Green (Dark)", draw.getNextPaint());
colors.put("Yellow (Dark)", draw.getNextPaint());
colors.put("Magenta (Dark)", draw.getNextPaint());
colors.put("Cyan (Dark)", draw.getNextPaint());
colors.put("Black", draw.getNextPaint());
colors.put("Red ", draw.getNextPaint());
colors.put("Blue ", draw.getNextPaint());
colors.put("Green ", draw.getNextPaint());
colors.put("Yellow ", draw.getNextPaint());
colors.put("Magenta ", draw.getNextPaint());
colors.put("Cyan ", draw.getNextPaint());
colors.put("Gray (Light)", draw.getNextPaint());
colors.put("Red (Extra Dark)", draw.getNextPaint());
colors.put("Blue (Extra Dark)", draw.getNextPaint());
colors.put("Green (Extra Dark)", draw.getNextPaint());
colors.put("Yellow (Extra Dark)", draw.getNextPaint());
colors.put("Magenta (Extra Dark)", draw.getNextPaint());
colors.put("Cyan (Extra Dark)", draw.getNextPaint());
colors.put("Red (Light)", draw.getNextPaint());
colors.put("Blue (Light)", draw.getNextPaint());
colors.put("Green (Light)", draw.getNextPaint());
colors.put("Yellow (Light)", draw.getNextPaint());
colors.put("Magenta (Light)", draw.getNextPaint());
colors.put("Cyan (Light)", draw.getNextPaint());
shapes.put("Square", draw.getNextShape());
shapes.put("Circle", draw.getNextShape());
shapes.put("Triangle", draw.getNextShape());
shapes.put("Diamond", draw.getNextShape());
shapes.put("Rectangle (Horizontal)", draw.getNextShape());
shapes.put("Triangle (Upside Down)", draw.getNextShape());
shapes.put("Circle (Half)", draw.getNextShape());
shapes.put("Arrow", draw.getNextShape());
shapes.put("Rectangle (Vertical)", draw.getNextShape());
shapes.put("Arrow (Backwards)", draw.getNextShape());
}
private void editGraph() {
final ArrayList<GraphSpecies> old = new ArrayList<GraphSpecies>();
for (GraphSpecies g : graphed) {
old.add(g);
}
JPanel titlePanel = new JPanel(new GridLayout(4, 6));
JLabel titleLabel = new JLabel("Title:");
JLabel xLabel = new JLabel("X-Axis Label:");
JLabel yLabel = new JLabel("Y-Axis Label:");
final JTextField title = new JTextField(chart.getTitle().getText(), 5);
final JTextField x = new JTextField(chart.getXYPlot().getDomainAxis().getLabel(), 5);
final JTextField y = new JTextField(chart.getXYPlot().getRangeAxis().getLabel(), 5);
final JLabel xMin = new JLabel("X-Min:");
final JLabel xMax = new JLabel("X-Max:");
final JLabel xScale = new JLabel("X-Step:");
final JLabel yMin = new JLabel("Y-Min:");
final JLabel yMax = new JLabel("Y-Max:");
final JLabel yScale = new JLabel("Y-Step:");
resize.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
xMin.setEnabled(false);
XMin.setEnabled(false);
xMax.setEnabled(false);
XMax.setEnabled(false);
xScale.setEnabled(false);
XScale.setEnabled(false);
yMin.setEnabled(false);
YMin.setEnabled(false);
yMax.setEnabled(false);
YMax.setEnabled(false);
yScale.setEnabled(false);
YScale.setEnabled(false);
}
else {
xMin.setEnabled(true);
XMin.setEnabled(true);
xMax.setEnabled(true);
XMax.setEnabled(true);
xScale.setEnabled(true);
XScale.setEnabled(true);
yMin.setEnabled(true);
YMin.setEnabled(true);
yMax.setEnabled(true);
YMax.setEnabled(true);
yScale.setEnabled(true);
YScale.setEnabled(true);
}
}
});
if (resize.isSelected()) {
xMin.setEnabled(false);
XMin.setEnabled(false);
xMax.setEnabled(false);
XMax.setEnabled(false);
xScale.setEnabled(false);
XScale.setEnabled(false);
yMin.setEnabled(false);
YMin.setEnabled(false);
yMax.setEnabled(false);
YMax.setEnabled(false);
yScale.setEnabled(false);
YScale.setEnabled(false);
}
else {
xMin.setEnabled(true);
XMin.setEnabled(true);
xMax.setEnabled(true);
XMax.setEnabled(true);
xScale.setEnabled(true);
XScale.setEnabled(true);
yMin.setEnabled(true);
YMin.setEnabled(true);
yMax.setEnabled(true);
YMax.setEnabled(true);
yScale.setEnabled(true);
YScale.setEnabled(true);
}
String simDirString = outDir.split(separator)[outDir.split(separator).length - 1];
final DefaultMutableTreeNode simDir = new DefaultMutableTreeNode(simDirString);
String[] files = new File(outDir).list();
for (int i = 1; i < files.length; i++) {
String index = files[i];
int j = i;
while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) {
files[j] = files[j - 1];
j = j - 1;
}
files[j] = index;
}
boolean add = false;
final ArrayList<String> directories = new ArrayList<String>();
for (String file : files) {
if (file.length() > 3
&& file.substring(file.length() - 4).equals(
"." + printer_id.substring(0, printer_id.length() - 8))) {
if (file.contains("run-")) {
add = true;
}
else {
simDir.add(new DefaultMutableTreeNode(file.substring(0, file.length() - 4)));
}
}
else if (new File(outDir + separator + file).isDirectory()) {
boolean addIt = false;
for (String getFile : new File(outDir + separator + file).list()) {
if (getFile.length() > 3
&& getFile.substring(getFile.length() - 4).equals(
"." + printer_id.substring(0, printer_id.length() - 8))) {
addIt = true;
}
}
if (addIt) {
directories.add(file);
DefaultMutableTreeNode d = new DefaultMutableTreeNode(file);
boolean add2 = false;
for (String f : new File(outDir + separator + file).list()) {
if (f.contains(printer_id.substring(0, printer_id.length() - 8))) {
if (f.contains("run-")) {
add2 = true;
}
else {
d.add(new DefaultMutableTreeNode(f.substring(0, f.length() - 4)));
}
}
}
if (add2) {
d.add(new DefaultMutableTreeNode("Average"));
d.add(new DefaultMutableTreeNode("Variance"));
d.add(new DefaultMutableTreeNode("Standard Deviation"));
}
int run = 1;
for (String s : new File(outDir + separator + file).list()) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + file + separator + "run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
d.add(new DefaultMutableTreeNode("run-" + (i + 1)));
}
}
simDir.add(d);
}
}
}
if (add) {
simDir.add(new DefaultMutableTreeNode("Average"));
simDir.add(new DefaultMutableTreeNode("Variance"));
simDir.add(new DefaultMutableTreeNode("Standard Deviation"));
}
int run = 1;
for (String s : new File(outDir).list()) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + "run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
simDir.add(new DefaultMutableTreeNode("run-" + (i + 1)));
}
}
if (simDir.getChildCount() == 0) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "No data to graph."
+ "\nPerform some simutations to create some data first.", "No Data",
JOptionPane.PLAIN_MESSAGE);
}
else {
final JTree tree = new JTree(simDir);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.expandRow(i);
}
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
final JPanel specPanel = new JPanel();
// final JFrame f = new JFrame("Edit Graph");
boolean stop = false;
int selectionRow = 1;
for (int i = 1; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (selected.equals(lastSelected)) {
stop = true;
selectionRow = i;
break;
}
}
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
if (!directories.contains(node.toString())) {
selected = node.toString();
int select;
if (selected.equals("Average")) {
select = 0;
}
else if (selected.equals("Variance")) {
select = 1;
}
else if (selected.equals("Standard Deviation")) {
select = 2;
}
else if (selected.contains("-run")) {
select = 0;
}
else {
try {
if (selected.contains("run-")) {
select = Integer.parseInt(selected.substring(4)) + 2;
}
else {
select = -1;
}
}
catch (Exception e1) {
select = -1;
}
}
if (select != -1) {
specPanel.removeAll();
if (directories.contains(node.getParent().toString())) {
specPanel.add(fixGraphChoices(node.getParent().toString()));
}
else {
specPanel.add(fixGraphChoices(""));
}
specPanel.revalidate();
specPanel.repaint();
for (int i = 0; i < series.size(); i++) {
series.get(i).setText(graphSpecies.get(i + 1));
}
for (int i = 0; i < boxes.size(); i++) {
boxes.get(i).setSelected(false);
}
if (directories.contains(node.getParent().toString())) {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected)
&& g.getDirectory().equals(node.getParent().toString())) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
colorsCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getPaintName());
shapesCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
else {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getDirectory().equals("")) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
colorsCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getPaintName());
shapesCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
boolean allChecked = true;
boolean allCheckedVisible = true;
boolean allCheckedFilled = true;
boolean allCheckedConnected = true;
for (int i = 0; i < boxes.size(); i++) {
if (!boxes.get(i).isSelected()) {
allChecked = false;
String s = "";
s = e.getPath().getLastPathComponent().toString();
if (directories.contains(node.getParent().toString())) {
if (s.equals("Average")) {
s = "(" + node.getParent().toString() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + node.getParent().toString() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + node.getParent().toString() + ", " + (char) 948 + ")";
}
else {
if (s.contains("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.contains("run-")) {
s = s.substring(4);
}
s = "(" + node.getParent().toString() + ", " + s + ")";
}
}
else {
if (s.equals("Average")) {
s = "(" + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + (char) 948 + ")";
}
else {
if (s.contains("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.contains("run-")) {
s = s.substring(4);
}
s = "(" + s + ")";
}
}
String text = graphSpecies.get(i + 1);
String end = "";
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
boxes.get(i).setName(text);
series.get(i).setText(text);
colorsCombo.get(i).setSelectedIndex(0);
shapesCombo.get(i).setSelectedIndex(0);
}
else {
String s = "";
s = e.getPath().getLastPathComponent().toString();
if (directories.contains(node.getParent().toString())) {
if (s.equals("Average")) {
s = "(" + node.getParent().toString() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + node.getParent().toString() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + node.getParent().toString() + ", " + (char) 948 + ")";
}
else {
if (s.contains("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.contains("run-")) {
s = s.substring(4);
}
s = "(" + node.getParent().toString() + ", " + s + ")";
}
}
else {
if (s.equals("Average")) {
s = "(" + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + (char) 948 + ")";
}
else {
if (s.contains("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.contains("run-")) {
s = s.substring(4);
}
s = "(" + s + ")";
}
}
String text = series.get(i).getText();
String end = "";
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
boxes.get(i).setName(text);
}
if (!visible.get(i).isSelected()) {
allCheckedVisible = false;
}
if (!connected.get(i).isSelected()) {
allCheckedConnected = false;
}
if (!filled.get(i).isSelected()) {
allCheckedFilled = false;
}
}
if (allChecked) {
use.setSelected(true);
}
else {
use.setSelected(false);
}
if (allCheckedVisible) {
visibleLabel.setSelected(true);
}
else {
visibleLabel.setSelected(false);
}
if (allCheckedFilled) {
filledLabel.setSelected(true);
}
else {
filledLabel.setSelected(false);
}
if (allCheckedConnected) {
connectedLabel.setSelected(true);
}
else {
connectedLabel.setSelected(false);
}
}
}
else {
specPanel.removeAll();
specPanel.revalidate();
specPanel.repaint();
}
}
});
if (!stop) {
tree.setSelectionRow(0);
tree.setSelectionRow(1);
}
else {
tree.setSelectionRow(0);
tree.setSelectionRow(selectionRow);
}
JScrollPane scroll = new JScrollPane();
scroll.setPreferredSize(new Dimension(1050, 500));
JPanel editPanel = new JPanel(new BorderLayout());
editPanel.add(titlePanel, "North");
editPanel.add(specPanel, "Center");
editPanel.add(scrollpane, "West");
scroll.setViewportView(editPanel);
// JButton ok = new JButton("Ok");
/*
* ok.addActionListener(new ActionListener() { public void
* actionPerformed(ActionEvent e) { double minY; double maxY; double
* scaleY; double minX; double maxX; double scaleX; change = true; try {
* minY = Double.parseDouble(YMin.getText().trim()); maxY =
* Double.parseDouble(YMax.getText().trim()); scaleY =
* Double.parseDouble(YScale.getText().trim()); minX =
* Double.parseDouble(XMin.getText().trim()); maxX =
* Double.parseDouble(XMax.getText().trim()); scaleX =
* Double.parseDouble(XScale.getText().trim()); NumberFormat num =
* NumberFormat.getInstance(); num.setMaximumFractionDigits(4);
* num.setGroupingUsed(false); minY =
* Double.parseDouble(num.format(minY)); maxY =
* Double.parseDouble(num.format(maxY)); scaleY =
* Double.parseDouble(num.format(scaleY)); minX =
* Double.parseDouble(num.format(minX)); maxX =
* Double.parseDouble(num.format(maxX)); scaleX =
* Double.parseDouble(num.format(scaleX)); } catch (Exception e1) {
* JOptionPane.showMessageDialog(biomodelsim.frame(), "Must enter doubles
* into the inputs " + "to change the graph's dimensions!", "Error",
* JOptionPane.ERROR_MESSAGE); return; } lastSelected = selected; selected =
* ""; ArrayList<XYSeries> graphData = new ArrayList<XYSeries>();
* XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer)
* chart.getXYPlot().getRenderer(); int thisOne = -1; for (int i = 1; i <
* graphed.size(); i++) { GraphSpecies index = graphed.get(i); int j = i;
* while ((j > 0) && (graphed.get(j -
* 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
* graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j, index); }
* ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>();
* HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String,
* ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) { if
* (g.getDirectory().equals("")) { thisOne++;
* rend.setSeriesVisible(thisOne, true);
* rend.setSeriesLinesVisible(thisOne, g.getConnected());
* rend.setSeriesShapesFilled(thisOne, g.getFilled());
* rend.setSeriesShapesVisible(thisOne, g.getVisible());
* rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
* rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if
* (!g.getRunNumber().equals("Average") &&
* !g.getRunNumber().equals("Variance") &&
* !g.getRunNumber().equals("Standard Deviation")) { if (new File(outDir +
* separator + g.getRunNumber() + "." + printer_id.substring(0,
* printer_id.length() - 8)).exists()) { readGraphSpecies(outDir +
* separator + g.getRunNumber() + "." + printer_id.substring(0,
* printer_id.length() - 8), biomodelsim.frame()); ArrayList<ArrayList<Double>>
* data; if (allData.containsKey(g.getRunNumber() + " " +
* g.getDirectory())) { data = allData.get(g.getRunNumber() + " " +
* g.getDirectory()); } else { data = readData(outDir + separator +
* g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() -
* 8), biomodelsim.frame(), y.getText().trim(), g.getRunNumber(), null);
* for (int i = 2; i < graphSpecies.size(); i++) { String index =
* graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j =
* i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) >
* 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j,
* data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j,
* index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(),
* data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() !=
* 0) { for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph =
* false; try { for (String s : new File(outDir).list()) { if (s.length() >
* 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } }
* catch (Exception e1) { ableToGraph = false; } if (ableToGraph) { int
* next = 1; while (!new File(outDir + separator + "run-" + next + "." +
* printer_id.substring(0, printer_id.length() - 8)).exists()) { next++; }
* readGraphSpecies(outDir + separator + "run-" + next + "." +
* printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
* ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data =
* allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data =
* readData(outDir + separator + "run-1." + printer_id.substring(0,
* printer_id.length() - 8), biomodelsim.frame(), y.getText().trim(),
* g.getRunNumber().toLowerCase(), null); for (int i = 2; i <
* graphSpecies.size(); i++) { String index = graphSpecies.get(i);
* ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) &&
* graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
* graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j -
* 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) {
* for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } } else { thisOne++;
* rend.setSeriesVisible(thisOne, true);
* rend.setSeriesLinesVisible(thisOne, g.getConnected());
* rend.setSeriesShapesFilled(thisOne, g.getFilled());
* rend.setSeriesShapesVisible(thisOne, g.getVisible());
* rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
* rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if
* (!g.getRunNumber().equals("Average") &&
* !g.getRunNumber().equals("Variance") &&
* !g.getRunNumber().equals("Standard Deviation")) { if (new File(outDir +
* separator + g.getDirectory() + separator + g.getRunNumber() + "." +
* printer_id.substring(0, printer_id.length() - 8)).exists()) {
* readGraphSpecies( outDir + separator + g.getDirectory() + separator +
* g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() -
* 8), biomodelsim.frame()); ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data =
* allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data =
* readData(outDir + separator + g.getDirectory() + separator +
* g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() -
* 8), biomodelsim.frame(), y.getText().trim(), g.getRunNumber(),
* g.getDirectory()); for (int i = 2; i < graphSpecies.size(); i++) {
* String index = graphSpecies.get(i); ArrayList<Double> index2 =
* data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j -
* 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j,
* graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; }
* graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) {
* for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph =
* false; try { for (String s : new File(outDir + separator +
* g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0,
* 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e1) {
* ableToGraph = false; } if (ableToGraph) { int next = 1; while (!new
* File(outDir + separator + g.getDirectory() + separator + "run-" + next +
* "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
* next++; } readGraphSpecies(outDir + separator + g.getDirectory() +
* separator + "run-" + next + "." + printer_id.substring(0,
* printer_id.length() - 8), biomodelsim.frame()); ArrayList<ArrayList<Double>>
* data; if (allData.containsKey(g.getRunNumber() + " " +
* g.getDirectory())) { data = allData.get(g.getRunNumber() + " " +
* g.getDirectory()); } else { data = readData(outDir + separator +
* g.getDirectory() + separator + "run-1." + printer_id.substring(0,
* printer_id.length() - 8), biomodelsim.frame(), y.getText().trim(),
* g.getRunNumber().toLowerCase(), g.getDirectory()); for (int i = 2; i <
* graphSpecies.size(); i++) { String index = graphSpecies.get(i);
* ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) &&
* graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
* graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j -
* 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) {
* for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } } } for (GraphSpecies g :
* unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset = new
* XYSeriesCollection(); for (int i = 0; i < graphData.size(); i++) {
* dataset.addSeries(graphData.get(i)); } fixGraph(title.getText().trim(),
* x.getText().trim(), y.getText().trim(), dataset);
* chart.getXYPlot().setRenderer(rend); XYPlot plot = chart.getXYPlot();
* if (resize.isSelected()) { resize(dataset); } else { NumberAxis axis =
* (NumberAxis) plot.getRangeAxis(); axis.setAutoTickUnitSelection(false);
* axis.setRange(minY, maxY); axis.setTickUnit(new
* NumberTickUnit(scaleY)); axis = (NumberAxis) plot.getDomainAxis();
* axis.setAutoTickUnitSelection(false); axis.setRange(minX, maxX);
* axis.setTickUnit(new NumberTickUnit(scaleX)); } //f.dispose(); } });
*/
// final JButton cancel = new JButton("Cancel");
// cancel.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// selected = "";
// int size = graphed.size();
// for (int i = 0; i < size; i++) {
// graphed.remove();
// }
// for (GraphSpecies g : old) {
// graphed.add(g);
// }
// f.dispose();
// }
// });
final JButton deselect = new JButton("Deselect All");
deselect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// selected = "";
int size = graphed.size();
for (int i = 0; i < size; i++) {
graphed.remove();
}
if (tree.getSelectionCount() > 0) {
int selectedRow = tree.getSelectionRows()[0];
tree.setSelectionRow(0);
tree.setSelectionRow(selectedRow);
}
}
});
titlePanel.add(titleLabel);
titlePanel.add(title);
titlePanel.add(xMin);
titlePanel.add(XMin);
titlePanel.add(yMin);
titlePanel.add(YMin);
titlePanel.add(xLabel);
titlePanel.add(x);
titlePanel.add(xMax);
titlePanel.add(XMax);
titlePanel.add(yMax);
titlePanel.add(YMax);
titlePanel.add(yLabel);
titlePanel.add(y);
titlePanel.add(xScale);
titlePanel.add(XScale);
titlePanel.add(yScale);
titlePanel.add(YScale);
titlePanel.add(new JPanel());
JPanel deselectPanel = new JPanel();
deselectPanel.add(deselect);
titlePanel.add(deselectPanel);
titlePanel.add(new JPanel());
titlePanel.add(new JPanel());
titlePanel.add(new JPanel());
titlePanel.add(resize);
// JPanel buttonPanel = new JPanel();
// buttonPanel.add(ok);
// buttonPanel.add(deselect);
// buttonPanel.add(cancel);
JPanel all = new JPanel(new BorderLayout());
all.add(scroll, "Center");
// all.add(buttonPanel, "South");
Object[] options = { "Ok", "Cancel" };
int value = JOptionPane.showOptionDialog(biomodelsim.frame(), all, "Edit Graph",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
double minY;
double maxY;
double scaleY;
double minX;
double maxX;
double scaleX;
change = true;
try {
minY = Double.parseDouble(YMin.getText().trim());
maxY = Double.parseDouble(YMax.getText().trim());
scaleY = Double.parseDouble(YScale.getText().trim());
minX = Double.parseDouble(XMin.getText().trim());
maxX = Double.parseDouble(XMax.getText().trim());
scaleX = Double.parseDouble(XScale.getText().trim());
NumberFormat num = NumberFormat.getInstance();
num.setMaximumFractionDigits(4);
num.setGroupingUsed(false);
minY = Double.parseDouble(num.format(minY));
maxY = Double.parseDouble(num.format(maxY));
scaleY = Double.parseDouble(num.format(scaleY));
minX = Double.parseDouble(num.format(minX));
maxX = Double.parseDouble(num.format(maxX));
scaleX = Double.parseDouble(num.format(scaleX));
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Must enter doubles into the inputs "
+ "to change the graph's dimensions!", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
lastSelected = selected;
selected = "";
ArrayList<XYSeries> graphData = new ArrayList<XYSeries>();
XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < graphed.size(); i++) {
GraphSpecies index = graphed.get(i);
int j = i;
while ((j > 0)
&& (graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
graphed.set(j, graphed.get(j - 1));
j = j - 1;
}
graphed.set(j, index);
}
ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>();
HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>();
for (GraphSpecies g : graphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation")) {
if (new File(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), y
.getText().trim(), g.getRunNumber(), null);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e1) {
ableToGraph = false;
}
if (ableToGraph) {
int next = 1;
while (!new File(outDir + separator + "run-" + next + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
next++;
}
readGraphSpecies(outDir + separator + "run-" + next + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "run-1."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), y
.getText().trim(), g.getRunNumber().toLowerCase(), null);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
else {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation")) {
if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber()
+ "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator
+ g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8),
biomodelsim.frame());
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getDirectory() + separator
+ g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8),
biomodelsim.frame(), y.getText().trim(), g.getRunNumber(), g.getDirectory());
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir + separator + g.getDirectory()).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e1) {
ableToGraph = false;
}
if (ableToGraph) {
int next = 1;
while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + next
+ "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
next++;
}
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "run-" + next
+ "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getDirectory() + separator + "run-1."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), y
.getText().trim(), g.getRunNumber().toLowerCase(), g.getDirectory());
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
}
for (GraphSpecies g : unableToGraph) {
graphed.remove(g);
}
XYSeriesCollection dataset = new XYSeriesCollection();
for (int i = 0; i < graphData.size(); i++) {
dataset.addSeries(graphData.get(i));
}
fixGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), dataset);
chart.getXYPlot().setRenderer(rend);
XYPlot plot = chart.getXYPlot();
if (resize.isSelected()) {
resize(dataset);
}
else {
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minY, maxY);
axis.setTickUnit(new NumberTickUnit(scaleY));
axis = (NumberAxis) plot.getDomainAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minX, maxX);
axis.setTickUnit(new NumberTickUnit(scaleX));
}
}
else {
selected = "";
int size = graphed.size();
for (int i = 0; i < size; i++) {
graphed.remove();
}
for (GraphSpecies g : old) {
graphed.add(g);
}
}
// WindowListener w = new WindowListener() {
// public void windowClosing(WindowEvent arg0) {
// cancel.doClick();
// }
// public void windowOpened(WindowEvent arg0) {
// }
// public void windowClosed(WindowEvent arg0) {
// }
// public void windowIconified(WindowEvent arg0) {
// }
// public void windowDeiconified(WindowEvent arg0) {
// }
// public void windowActivated(WindowEvent arg0) {
// }
// public void windowDeactivated(WindowEvent arg0) {
// }
// };
// f.addWindowListener(w);
// f.setContentPane(all);
// f.pack();
// Dimension screenSize;
// try {
// Toolkit tk = Toolkit.getDefaultToolkit();
// screenSize = tk.getScreenSize();
// }
// catch (AWTError awe) {
// screenSize = new Dimension(640, 480);
// }
// Dimension frameSize = f.getSize();
// if (frameSize.height > screenSize.height) {
// frameSize.height = screenSize.height;
// }
// if (frameSize.width > screenSize.width) {
// frameSize.width = screenSize.width;
// }
// int xx = screenSize.width / 2 - frameSize.width / 2;
// int yy = screenSize.height / 2 - frameSize.height / 2;
// f.setLocation(xx, yy);
// f.setVisible(true);
}
}
private JPanel fixGraphChoices(final String directory) {
if (directory.equals("")) {
if (selected.equals("Average") || selected.equals("Variance")
|| selected.equals("Standard Deviation")) {
int nextOne = 1;
while (!new File(outDir + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
}
else {
readGraphSpecies(outDir + separator + selected + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
}
}
else {
if (selected.equals("Average") || selected.equals("Variance")
|| selected.equals("Standard Deviation")) {
int nextOne = 1;
while (!new File(outDir + separator + directory + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + directory + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
}
else {
readGraphSpecies(outDir + separator + directory + separator + selected + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
}
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
JPanel speciesPanel1 = new JPanel(new GridLayout(graphSpecies.size(), 1));
JPanel speciesPanel2 = new JPanel(new GridLayout(graphSpecies.size(), 3));
JPanel speciesPanel3 = new JPanel(new GridLayout(graphSpecies.size(), 3));
use = new JCheckBox("Use");
JLabel specs = new JLabel("Species");
JLabel color = new JLabel("Color");
JLabel shape = new JLabel("Shape");
connectedLabel = new JCheckBox("Connected");
visibleLabel = new JCheckBox("Visible");
filledLabel = new JCheckBox("Filled");
connectedLabel.setSelected(true);
visibleLabel.setSelected(true);
filledLabel.setSelected(true);
boxes = new ArrayList<JCheckBox>();
series = new ArrayList<JTextField>();
colorsCombo = new ArrayList<JComboBox>();
shapesCombo = new ArrayList<JComboBox>();
connected = new ArrayList<JCheckBox>();
visible = new ArrayList<JCheckBox>();
filled = new ArrayList<JCheckBox>();
use.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (use.isSelected()) {
for (JCheckBox box : boxes) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : boxes) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
connectedLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (connectedLabel.isSelected()) {
for (JCheckBox box : connected) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : connected) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
visibleLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (visibleLabel.isSelected()) {
for (JCheckBox box : visible) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : visible) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
filledLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (filledLabel.isSelected()) {
for (JCheckBox box : filled) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : filled) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
speciesPanel1.add(use);
speciesPanel2.add(specs);
speciesPanel2.add(color);
speciesPanel2.add(shape);
speciesPanel3.add(connectedLabel);
speciesPanel3.add(visibleLabel);
speciesPanel3.add(filledLabel);
final HashMap<String, Shape> shapey = this.shapes;
final HashMap<String, Paint> colory = this.colors;
for (int i = 0; i < graphSpecies.size() - 1; i++) {
JCheckBox temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
String s = series.get(i).getText();
((JCheckBox) e.getSource()).setSelected(false);
int[] cols = new int[34];
int[] shaps = new int[10];
for (int k = 0; k < boxes.size(); k++) {
if (boxes.get(k).isSelected()) {
if (colorsCombo.get(k).getSelectedItem().equals("Red")) {
cols[0]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) {
cols[1]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green")) {
cols[2]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) {
cols[3]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) {
cols[4]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) {
cols[5]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) {
cols[6]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) {
cols[7]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) {
cols[8]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) {
cols[9]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Dark)")) {
cols[10]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Dark)")) {
cols[11]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Dark)")) {
cols[12]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Black")) {
cols[14]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red ")) {
cols[15]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue ")) {
cols[16]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green ")) {
cols[17]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow ")) {
cols[18]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta ")) {
cols[19]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan ")) {
cols[20]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Light)")) {
cols[21]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Extra Dark)")) {
cols[22]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Extra Dark)")) {
cols[23]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Extra Dark)")) {
cols[24]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Extra Dark)")) {
cols[25]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Extra Dark)")) {
cols[26]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Extra Dark)")) {
cols[27]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) {
cols[28]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Light)")) {
cols[29]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Light)")) {
cols[30]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Light)")) {
cols[31]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Light)")) {
cols[32]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Light)")) {
cols[33]++;
}
if (shapesCombo.get(k).getSelectedItem().equals("Square")) {
shaps[0]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Circle")) {
shaps[1]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Triangle")) {
shaps[2]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Diamond")) {
shaps[3]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Rectangle (Horizontal)")) {
shaps[4]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Triangle (Upside Down)")) {
shaps[5]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Circle (Half)")) {
shaps[6]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Arrow")) {
shaps[7]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Rectangle (Vertical)")) {
shaps[8]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Arrow (Backwards)")) {
shaps[9]++;
}
}
}
for (GraphSpecies graph : graphed) {
if (graph.getShapeAndPaint().getPaintName().equals("Red")) {
cols[0]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue")) {
cols[1]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green")) {
cols[2]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow")) {
cols[3]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta")) {
cols[4]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan")) {
cols[5]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Tan")) {
cols[6]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Dark)")) {
cols[7]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Dark)")) {
cols[8]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Dark)")) {
cols[9]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Dark)")) {
cols[10]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Dark)")) {
cols[11]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Dark)")) {
cols[12]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Black")) {
cols[14]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red ")) {
cols[15]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue ")) {
cols[16]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green ")) {
cols[17]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow ")) {
cols[18]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta ")) {
cols[19]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan ")) {
cols[20]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Light)")) {
cols[21]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Extra Dark)")) {
cols[22]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Extra Dark)")) {
cols[23]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Extra Dark)")) {
cols[24]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Extra Dark)")) {
cols[25]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Extra Dark)")) {
cols[26]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Extra Dark)")) {
cols[27]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Light)")) {
cols[28]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Light)")) {
cols[29]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Light)")) {
cols[30]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Light)")) {
cols[31]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Light)")) {
cols[32]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Light)")) {
cols[33]++;
}
if (graph.getShapeAndPaint().getShapeName().equals("Square")) {
shaps[0]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Circle")) {
shaps[1]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Triangle")) {
shaps[2]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Diamond")) {
shaps[3]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Rectangle (Horizontal)")) {
shaps[4]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Triangle (Upside Down)")) {
shaps[5]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Circle (Half)")) {
shaps[6]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Arrow")) {
shaps[7]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Rectangle (Vertical)")) {
shaps[8]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Arrow (Backwards)")) {
shaps[9]++;
}
}
((JCheckBox) e.getSource()).setSelected(true);
series.get(i).setText(s);
int colorSet = 0;
for (int j = 1; j < cols.length; j++) {
if (cols[j] < cols[colorSet]) {
colorSet = j;
}
}
int shapeSet = 0;
for (int j = 1; j < shaps.length; j++) {
if (shaps[j] < shaps[shapeSet]) {
shapeSet = j;
}
}
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
for (int j = 0; j < colorSet; j++) {
draw.getNextPaint();
}
Paint paint = draw.getNextPaint();
Object[] set = colory.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (paint == colory.get(set[j])) {
colorsCombo.get(i).setSelectedItem(set[j]);
}
}
for (int j = 0; j < shapeSet; j++) {
draw.getNextShape();
}
Shape shape = draw.getNextShape();
set = shapey.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (shape == shapey.get(set[j])) {
shapesCombo.get(i).setSelectedItem(set[j]);
}
}
boolean allChecked = true;
for (JCheckBox temp : boxes) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
use.setSelected(true);
}
graphed.add(new GraphSpecies(shapey.get(shapesCombo.get(i).getSelectedItem()), colory
.get(colorsCombo.get(i).getSelectedItem()), filled.get(i).isSelected(), visible
.get(i).isSelected(), connected.get(i).isSelected(), selected, boxes.get(i)
.getName(), series.get(i).getText().trim(), i, directory));
}
else {
ArrayList<GraphSpecies> remove = new ArrayList<GraphSpecies>();
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
remove.add(g);
}
}
for (GraphSpecies g : remove) {
graphed.remove(g);
}
use.setSelected(false);
colorsCombo.get(i).setSelectedIndex(0);
shapesCombo.get(i).setSelectedIndex(0);
}
}
});
boxes.add(temp);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : visible) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
visibleLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setVisible(true);
}
}
}
else {
visibleLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setVisible(false);
}
}
}
}
});
visible.add(temp);
visible.get(i).setSelected(true);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : filled) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
filledLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setFilled(true);
}
}
}
else {
filledLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setFilled(false);
}
}
}
}
});
filled.add(temp);
filled.get(i).setSelected(true);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : connected) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
connectedLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setConnected(true);
}
}
}
else {
connectedLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setConnected(false);
}
}
}
}
});
connected.add(temp);
connected.get(i).setSelected(true);
JTextField seriesName = new JTextField(graphSpecies.get(i + 1));
seriesName.setName("" + i);
seriesName.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyReleased(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyTyped(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
});
series.add(seriesName);
Object[] col = this.colors.keySet().toArray();
Arrays.sort(col);
Object[] shap = this.shapes.keySet().toArray();
Arrays.sort(shap);
JComboBox colBox = new JComboBox(col);
colBox.setActionCommand("" + i);
colBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setPaint((String) ((JComboBox) e.getSource()).getSelectedItem());
}
}
}
});
JComboBox shapBox = new JComboBox(shap);
shapBox.setActionCommand("" + i);
shapBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setShape((String) ((JComboBox) e.getSource()).getSelectedItem());
}
}
}
});
colorsCombo.add(colBox);
shapesCombo.add(shapBox);
speciesPanel1.add(boxes.get(i));
speciesPanel2.add(series.get(i));
speciesPanel2.add(colorsCombo.get(i));
speciesPanel2.add(shapesCombo.get(i));
speciesPanel3.add(connected.get(i));
speciesPanel3.add(visible.get(i));
speciesPanel3.add(filled.get(i));
}
JPanel speciesPanel = new JPanel(new BorderLayout());
speciesPanel.add(speciesPanel1, "West");
speciesPanel.add(speciesPanel2, "Center");
speciesPanel.add(speciesPanel3, "East");
return speciesPanel;
}
private void fixGraph(String title, String x, String y, XYSeriesCollection dataset) {
curData = dataset;
chart = ChartFactory.createXYLineChart(title, x, y, dataset, PlotOrientation.VERTICAL, true,
true, false);
chart.addProgressListener(this);
ChartPanel graph = new ChartPanel(chart);
if (graphed.isEmpty()) {
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Click here to create graph");
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
}
graph.addMouseListener(this);
JPanel ButtonHolder = new JPanel();
save = new JButton("Save Graph");
export = new JButton("Export");
// exportJPeg = new JButton("Export As JPEG");
// exportPng = new JButton("Export As PNG");
// exportPdf = new JButton("Export As PDF");
// exportEps = new JButton("Export As EPS");
// exportSvg = new JButton("Export As SVG");
// exportCsv = new JButton("Export As CSV");
save.addActionListener(this);
export.addActionListener(this);
// exportJPeg.addActionListener(this);
// exportPng.addActionListener(this);
// exportPdf.addActionListener(this);
// exportEps.addActionListener(this);
// exportSvg.addActionListener(this);
// exportCsv.addActionListener(this);
ButtonHolder.add(save);
ButtonHolder.add(export);
// ButtonHolder.add(exportJPeg);
// ButtonHolder.add(exportPng);
// ButtonHolder.add(exportPdf);
// ButtonHolder.add(exportEps);
// ButtonHolder.add(exportSvg);
// ButtonHolder.add(exportCsv);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, ButtonHolder, null);
splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
this.add(splitPane, "South");
this.revalidate();
}
/**
* This method saves the graph as a jpeg or as a png file.
*/
public void export() {
try {
int output = 2; /* Default is currently pdf */
int width = -1;
int height = -1;
JPanel sizePanel = new JPanel(new GridLayout(2, 2));
JLabel heightLabel = new JLabel("Desired pixel height:");
JLabel widthLabel = new JLabel("Desired pixel width:");
JTextField heightField = new JTextField("400");
JTextField widthField = new JTextField("650");
sizePanel.add(widthLabel);
sizePanel.add(widthField);
sizePanel.add(heightLabel);
sizePanel.add(heightField);
Object[] options2 = { "Export", "Cancel" };
int value;
File file;
if (savedPics != null) {
file = new File(savedPics);
}
else {
file = null;
}
String filename = Buttons.browse(biomodelsim.frame(), file, null, JFileChooser.FILES_ONLY,
"Export");
if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length()).equals(".jpg"))) {
output = 0;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length()).equals(".png"))) {
output = 1;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length()).equals(".pdf"))) {
output = 2;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length()).equals(".eps"))) {
output = 3;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length()).equals(".svg"))) {
output = 4;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length()).equals(".csv"))) {
output = 5;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length()).equals(".dat"))) {
output = 6;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length()).equals(".tsd"))) {
output = 7;
}
if (!filename.equals("")) {
file = new File(filename);
boolean exportIt = true;
if (file.exists()) {
Object[] options = { "Overwrite", "Cancel" };
value = JOptionPane.showOptionDialog(biomodelsim.frame(), "File already exists."
+ " Overwrite?", "File Already Exists", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
exportIt = false;
if (value == JOptionPane.YES_OPTION) {
exportIt = true;
}
}
if (exportIt) {
if ((output != 5) && (output != 6) && (output != 7)) {
value = JOptionPane.showOptionDialog(biomodelsim.frame(), sizePanel,
"Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options2, options2[0]);
if (value == JOptionPane.YES_OPTION) {
while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1))
try {
width = Integer.parseInt(widthField.getText().trim());
height = Integer.parseInt(heightField.getText().trim());
if (width < 1 || height < 1) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(biomodelsim.frame(), sizePanel,
"Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options2, options2[0]);
}
}
catch (Exception e2) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(biomodelsim.frame(), sizePanel,
"Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options2, options2[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
if (output == 0) {
ChartUtilities.saveChartAsJPEG(file, chart, width, height);
}
else if (output == 1) {
ChartUtilities.saveChartAsPNG(file, chart, width, height);
}
else if (output == 2) {
Rectangle pagesize = new Rectangle(width, height);
Document document = new Document(pagesize, 50, 50, 50, 50);
FileOutputStream out = new FileOutputStream(file);
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
chart.draw(g2, new java.awt.Rectangle(width, height));
g2.dispose();
cb.addTemplate(tp, 0, 0);
document.close();
out.close();
}
else if (output == 3) {
Graphics2D g = new EpsGraphics2D();
chart.draw(g, new java.awt.Rectangle(width, height));
Writer out = new FileWriter(file);
out.write(g.toString());
out.close();
}
else if (output == 4) {
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
chart.draw(svgGenerator, new java.awt.Rectangle(width, height));
boolean useCSS = true;
FileOutputStream outStream = new FileOutputStream(file);
Writer out = new OutputStreamWriter(outStream, "UTF-8");
svgGenerator.stream(out, useCSS);
out.close();
outStream.close();
}
else if ((output == 5) || (output == 6) || (output == 7)) {
exportDataFile(file, output);
}
savedPics = filename;
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Export File!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void exportDataFile(File file, int output) {
try {
int count = curData.getSeries(0).getItemCount();
for (int i = 1; i < curData.getSeriesCount(); i++) {
if (curData.getSeries(i).getItemCount() != count) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Data series do not have the same number of points!", "Unable to Export Data File",
JOptionPane.ERROR_MESSAGE);
return;
}
}
for (int j = 0; j < count; j++) {
Number Xval = curData.getSeries(0).getDataItem(j).getX();
for (int i = 1; i < curData.getSeriesCount(); i++) {
if (curData.getSeries(i).getDataItem(j).getX() != Xval) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Data series time points are not the same!", "Unable to Export Data File",
JOptionPane.ERROR_MESSAGE);
return;
}
}
}
FileOutputStream csvFile = new FileOutputStream(file);
PrintWriter csvWriter = new PrintWriter(csvFile);
if (output == 7) {
csvWriter.print("((");
}
else if (output == 6) {
csvWriter.print("#");
}
csvWriter.print("\"Time\"");
count = curData.getSeries(0).getItemCount();
int pos = 0;
for (int i = 0; i < curData.getSeriesCount(); i++) {
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
csvWriter.print("\"" + curData.getSeriesKey(i) + "\"");
if (curData.getSeries(i).getItemCount() > count) {
count = curData.getSeries(i).getItemCount();
pos = i;
}
}
if (output == 7) {
csvWriter.print(")");
}
else {
csvWriter.println("");
}
for (int j = 0; j < count; j++) {
if (output == 7) {
csvWriter.print(",");
}
for (int i = 0; i < curData.getSeriesCount(); i++) {
if (i == 0) {
if (output == 7) {
csvWriter.print("(");
}
csvWriter.print(curData.getSeries(pos).getDataItem(j).getX());
}
XYSeries data = curData.getSeries(i);
if (j < data.getItemCount()) {
XYDataItem item = data.getDataItem(j);
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
csvWriter.print(item.getY());
}
else {
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
}
}
if (output == 7) {
csvWriter.print(")");
}
else {
csvWriter.println("");
}
}
if (output == 7) {
csvWriter.println(")");
}
csvWriter.close();
csvFile.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Export File!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
private ArrayList<ArrayList<Double>> calculateAverageVarianceDeviation(String startFile,
String fileStem, int choice, String directory) {
ArrayList<ArrayList<Double>> average = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> variance = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> deviation = new ArrayList<ArrayList<Double>>();
try {
FileInputStream fileInput = new FileInputStream(new File(startFile));
ProgressMonitorInputStream prog = new ProgressMonitorInputStream(biomodelsim.frame(),
"Reading Reb2sac Output Data From " + new File(startFile).getName(), fileInput);
InputStream input = new BufferedInputStream(prog);
boolean reading = true;
char cha;
int readCount = 0;
while (reading) {
String word = "";
boolean readWord = true;
while (readWord) {
int read = input.read();
readCount++;
if (read == -1) {
reading = false;
readWord = false;
}
cha = (char) read;
if (Character.isWhitespace(cha)) {
input.mark(3);
char next = (char) input.read();
char after = (char) input.read();
String check = "" + next + after;
if (word.equals("") || word.equals("0") || check.equals("0,")) {
readWord = false;
}
else {
word += cha;
}
input.reset();
}
else if (cha == ',' || cha == ':' || cha == ';' || cha == '!' || cha == '?'
|| cha == '\"' || cha == '\'' || cha == '(' || cha == ')' || cha == '{' || cha == '}'
|| cha == '[' || cha == ']' || cha == '<' || cha == '>' || cha == '*' || cha == '='
|| cha == '#') {
readWord = false;
}
else if (read != -1) {
word += cha;
}
}
int getNum;
try {
getNum = Integer.parseInt(word);
if (getNum == 0) {
boolean first = true;
int runsToMake = 1;
String[] findNum = startFile.split(separator);
String search = findNum[findNum.length - 1];
int firstOne = Integer.parseInt(search.substring(4, search.length() - 4));
if (directory == null) {
for (String f : new File(outDir).list()) {
if (f.contains(fileStem)) {
int tempNum = Integer.parseInt(f.substring(fileStem.length(), f.length() - 4));
if (tempNum > runsToMake) {
runsToMake = tempNum;
}
}
}
}
else {
for (String f : new File(outDir + separator + directory).list()) {
if (f.contains(fileStem)) {
int tempNum = Integer.parseInt(f.substring(fileStem.length(), f.length() - 4));
if (tempNum > runsToMake) {
runsToMake = tempNum;
}
}
}
}
for (int i = 0; i < graphSpecies.size(); i++) {
average.add(new ArrayList<Double>());
variance.add(new ArrayList<Double>());
}
(average.get(0)).add(0.0);
(variance.get(0)).add(0.0);
int count = 0;
int skip = firstOne;
for (int j = 0; j < runsToMake; j++) {
int counter = 1;
if (!first) {
if (firstOne != 1) {
j--;
firstOne = 1;
}
boolean loop = true;
while (loop && j < runsToMake && (j + 1) != skip) {
if (directory == null) {
if (new File(outDir + separator + fileStem + (j + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
input.close();
prog.close();
fileInput.close();
fileInput = new FileInputStream(new File(outDir + separator + fileStem
+ (j + 1) + "." + printer_id.substring(0, printer_id.length() - 8)));
prog = new ProgressMonitorInputStream(biomodelsim.frame(),
"Reading Reb2sac Output Data From "
+ new File(outDir + separator + fileStem + (j + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).getName(),
fileInput);
input = new BufferedInputStream(prog);
for (int i = 0; i < readCount; i++) {
input.read();
}
loop = false;
count++;
}
else {
j++;
}
}
else {
if (new File(outDir + separator + directory + separator + fileStem + (j + 1)
+ "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
input.close();
prog.close();
fileInput.close();
fileInput = new FileInputStream(new File(outDir + separator + directory
+ separator + fileStem + (j + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)));
prog = new ProgressMonitorInputStream(biomodelsim.frame(),
"Reading Reb2sac Output Data From "
+ new File(outDir + separator + directory + separator + fileStem
+ (j + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).getName(),
fileInput);
input = new BufferedInputStream(prog);
for (int i = 0; i < readCount; i++) {
input.read();
}
loop = false;
count++;
}
else {
j++;
}
}
}
}
reading = true;
while (reading) {
word = "";
readWord = true;
int read;
while (readWord) {
read = input.read();
cha = (char) read;
while (!Character.isWhitespace(cha) && cha != ',' && cha != ':' && cha != ';'
&& cha != '!' && cha != '?' && cha != '\"' && cha != '\'' && cha != '('
&& cha != ')' && cha != '{' && cha != '}' && cha != '[' && cha != ']'
&& cha != '<' && cha != '>' && cha != '_' && cha != '*' && cha != '='
&& read != -1) {
word += cha;
read = input.read();
cha = (char) read;
}
if (read == -1) {
reading = false;
first = false;
}
readWord = false;
}
int insert;
if (!word.equals("")) {
if (first) {
if (counter < graphSpecies.size()) {
insert = counter;
(average.get(insert)).add(Double.parseDouble(word));
if (insert == 0) {
(variance.get(insert)).add(Double.parseDouble(word));
}
else {
(variance.get(insert)).add(0.0);
}
}
else {
insert = counter % graphSpecies.size();
(average.get(insert)).add(Double.parseDouble(word));
if (insert == 0) {
(variance.get(insert)).add(Double.parseDouble(word));
}
else {
(variance.get(insert)).add(0.0);
}
}
}
else {
if (counter < graphSpecies.size()) {
insert = counter;
try {
double old = (average.get(insert)).get(insert / graphSpecies.size());
(average.get(insert)).set(insert / graphSpecies.size(), old
+ ((Double.parseDouble(word) - old) / (count + 1)));
double newMean = (average.get(insert)).get(insert / graphSpecies.size());
if (insert == 0) {
(variance.get(insert)).set(insert / graphSpecies.size(), old
+ ((Double.parseDouble(word) - old) / (count + 1)));
}
else {
double vary = (((count - 1) * (variance.get(insert)).get(insert
/ graphSpecies.size())) + (Double.parseDouble(word) - newMean)
* (Double.parseDouble(word) - old))
/ count;
(variance.get(insert)).set(insert / graphSpecies.size(), vary);
}
}
catch (Exception e2) {
(average.get(insert)).add(Double.parseDouble(word));
if (insert == 0) {
(variance.get(insert)).add(Double.parseDouble(word));
}
else {
(variance.get(insert)).add(0.0);
}
}
}
else {
insert = counter % graphSpecies.size();
try {
double old = (average.get(insert)).get(counter / graphSpecies.size());
(average.get(insert)).set(counter / graphSpecies.size(), old
+ ((Double.parseDouble(word) - old) / (count + 1)));
double newMean = (average.get(insert)).get(counter / graphSpecies.size());
if (insert == 0) {
(variance.get(insert)).set(counter / graphSpecies.size(), old
+ ((Double.parseDouble(word) - old) / (count + 1)));
}
else {
double vary = (((count - 1) * (variance.get(insert)).get(counter
/ graphSpecies.size())) + (Double.parseDouble(word) - newMean)
* (Double.parseDouble(word) - old))
/ count;
(variance.get(insert)).set(counter / graphSpecies.size(), vary);
}
}
catch (Exception e2) {
(average.get(insert)).add(Double.parseDouble(word));
if (insert == 0) {
(variance.get(insert)).add(Double.parseDouble(word));
}
else {
(variance.get(insert)).add(0.0);
}
}
}
}
counter++;
}
}
}
}
}
catch (Exception e1) {
}
}
deviation = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < variance.size(); i++) {
deviation.add(new ArrayList<Double>());
for (int j = 0; j < variance.get(i).size(); j++) {
deviation.get(i).add(variance.get(i).get(j));
}
}
for (int i = 1; i < deviation.size(); i++) {
for (int j = 0; j < deviation.get(i).size(); j++) {
deviation.get(i).set(j, Math.sqrt(deviation.get(i).get(j)));
}
}
input.close();
prog.close();
fileInput.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Error Reading Data!"
+ "\nThere was an error reading the simulation output data.", "Error Reading Data",
JOptionPane.ERROR_MESSAGE);
}
if (choice == 0) {
return average;
}
else if (choice == 1) {
return variance;
}
else {
return deviation;
}
}
public void save() {
if (timeSeries) {
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel());
graph.setProperty("x.min", XMin.getText());
graph.setProperty("x.max", XMax.getText());
graph.setProperty("x.scale", XScale.getText());
graph.setProperty("y.min", YMin.getText());
graph.setProperty("y.max", YMax.getText());
graph.setProperty("y.scale", YScale.getText());
graph.setProperty("auto.resize", "" + resize.isSelected());
for (int i = 0; i < graphed.size(); i++) {
graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected());
graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled());
graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber());
graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber());
graph.setProperty("species.name." + i, graphed.get(i).getSpecies());
graph.setProperty("species.id." + i, graphed.get(i).getID());
graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible());
graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint().getPaintName());
graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint().getShapeName());
graph.setProperty("species.directory." + i, graphed.get(i).getDirectory());
}
try {
FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName));
graph.store(store, "Graph Data");
store.close();
log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n");
change = false;
}
catch (Exception except) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Save Graph!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel());
for (int i = 0; i < probGraphed.size(); i++) {
graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber());
graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies());
graph.setProperty("species.id." + i, probGraphed.get(i).getID());
graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName());
graph.setProperty("species.directory." + i, probGraphed.get(i).getDirectory());
}
try {
FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName));
graph.store(store, "Probability Data");
store.close();
log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n");
change = false;
}
catch (Exception except) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Save Graph!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
private void open(String filename) {
if (timeSeries) {
Properties graph = new Properties();
try {
FileInputStream load = new FileInputStream(new File(filename));
graph.load(load);
load.close();
XMin.setText(graph.getProperty("x.min"));
XMax.setText(graph.getProperty("x.max"));
XScale.setText(graph.getProperty("x.scale"));
YMin.setText(graph.getProperty("y.min"));
YMax.setText(graph.getProperty("y.max"));
YScale.setText(graph.getProperty("y.scale"));
chart.setTitle(graph.getProperty("title"));
chart.getXYPlot().getDomainAxis().setLabel(graph.getProperty("x.axis"));
chart.getXYPlot().getRangeAxis().setLabel(graph.getProperty("y.axis"));
if (graph.getProperty("auto.resize").equals("true")) {
resize.setSelected(true);
}
else {
resize.setSelected(false);
}
int next = 0;
while (graph.containsKey("species.name." + next)) {
boolean connected, filled, visible;
if (graph.getProperty("species.connected." + next).equals("true")) {
connected = true;
}
else {
connected = false;
}
if (graph.getProperty("species.filled." + next).equals("true")) {
filled = true;
}
else {
filled = false;
}
if (graph.getProperty("species.visible." + next).equals("true")) {
visible = true;
}
else {
visible = false;
}
graphed.add(new GraphSpecies(shapes.get(graph.getProperty("species.shape." + next)),
colors.get(graph.getProperty("species.paint." + next)), filled, visible, connected,
graph.getProperty("species.run.number." + next), graph.getProperty("species.id."
+ next), graph.getProperty("species.name." + next), Integer.parseInt(graph
.getProperty("species.number." + next)), graph.getProperty("species.directory."
+ next)));
next++;
}
refresh();
}
catch (Exception except) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Load Graph!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
Properties graph = new Properties();
try {
FileInputStream load = new FileInputStream(new File(filename));
graph.load(load);
load.close();
chart.setTitle(graph.getProperty("title"));
chart.getCategoryPlot().getDomainAxis().setLabel(graph.getProperty("x.axis"));
chart.getCategoryPlot().getRangeAxis().setLabel(graph.getProperty("y.axis"));
int next = 0;
while (graph.containsKey("species.name." + next)) {
probGraphed.add(new GraphProbs(colors.get(graph.getProperty("species.paint." + next)),
graph.getProperty("species.paint." + next), graph.getProperty("species.id." + next),
graph.getProperty("species.name." + next), Integer.parseInt(graph
.getProperty("species.number." + next)), graph.getProperty("species.directory."
+ next)));
next++;
}
refreshProb();
}
catch (Exception except) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Load Graph!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
public void refresh() {
double minY = 0;
double maxY = 0;
double scaleY = 0;
double minX = 0;
double maxX = 0;
double scaleX = 0;
try {
minY = Double.parseDouble(YMin.getText().trim());
maxY = Double.parseDouble(YMax.getText().trim());
scaleY = Double.parseDouble(YScale.getText().trim());
minX = Double.parseDouble(XMin.getText().trim());
maxX = Double.parseDouble(XMax.getText().trim());
scaleX = Double.parseDouble(XScale.getText().trim());
NumberFormat num = NumberFormat.getInstance();
num.setMaximumFractionDigits(4);
num.setGroupingUsed(false);
minY = Double.parseDouble(num.format(minY));
maxY = Double.parseDouble(num.format(maxY));
scaleY = Double.parseDouble(num.format(scaleY));
minX = Double.parseDouble(num.format(minX));
maxX = Double.parseDouble(num.format(maxX));
scaleX = Double.parseDouble(num.format(scaleX));
}
catch (Exception e1) {
}
ArrayList<XYSeries> graphData = new ArrayList<XYSeries>();
XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < graphed.size(); i++) {
GraphSpecies index = graphed.get(i);
int j = i;
while ((j > 0)
&& (graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
graphed.set(j, graphed.get(j - 1));
j = j - 1;
}
graphed.set(j, index);
}
ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>();
HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>();
for (GraphSpecies g : graphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation")) {
if (new File(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
}
else {
data = readData(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), chart
.getXYPlot().getRangeAxis().getLabel(), g.getRunNumber(), null);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace('(', '~');
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e) {
ableToGraph = false;
}
if (ableToGraph) {
int nextOne = 1;
while (!new File(outDir + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
}
else {
data = readData(outDir + separator + "run-1."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), chart
.getXYPlot().getRangeAxis().getLabel(), g.getRunNumber().toLowerCase(), null);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace('(', '~');
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
else {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation")) {
if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + g.getRunNumber()
+ "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
}
else {
data = readData(outDir + separator + g.getDirectory() + separator + g.getRunNumber()
+ "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(),
chart.getXYPlot().getRangeAxis().getLabel(), g.getRunNumber(), g.getDirectory());
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace('(', '~');
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir + separator + g.getDirectory()).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e) {
ableToGraph = false;
}
if (ableToGraph) {
int nextOne = 1;
while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + nextOne
+ "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "run-" + nextOne
+ "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame());
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
}
else {
data = readData(outDir + separator + g.getDirectory() + separator + "run-1."
+ printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), chart
.getXYPlot().getRangeAxis().getLabel(), g.getRunNumber().toLowerCase(), g
.getDirectory());
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace('(', '~');
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
}
for (GraphSpecies g : unableToGraph) {
graphed.remove(g);
}
XYSeriesCollection dataset = new XYSeriesCollection();
for (int i = 0; i < graphData.size(); i++) {
dataset.addSeries(graphData.get(i));
}
fixGraph(chart.getTitle().getText(), chart.getXYPlot().getDomainAxis().getLabel(), chart
.getXYPlot().getRangeAxis().getLabel(), dataset);
chart.getXYPlot().setRenderer(rend);
XYPlot plot = chart.getXYPlot();
if (resize.isSelected()) {
resize(dataset);
}
else {
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minY, maxY);
axis.setTickUnit(new NumberTickUnit(scaleY));
axis = (NumberAxis) plot.getDomainAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minX, maxX);
axis.setTickUnit(new NumberTickUnit(scaleX));
}
}
private class ShapeAndPaint {
private Shape shape;
private Paint paint;
private ShapeAndPaint(Shape s, Paint p) {
shape = s;
paint = p;
}
private Shape getShape() {
return shape;
}
private Paint getPaint() {
return paint;
}
private String getShapeName() {
Object[] set = shapes.keySet().toArray();
for (int i = 0; i < set.length; i++) {
if (shape == shapes.get(set[i])) {
return (String) set[i];
}
}
return "Unknown Shape";
}
private String getPaintName() {
Object[] set = colors.keySet().toArray();
for (int i = 0; i < set.length; i++) {
if (paint == colors.get(set[i])) {
return (String) set[i];
}
}
return "Unknown Color";
}
public void setPaint(String paint) {
this.paint = colors.get(paint);
}
public void setShape(String shape) {
this.shape = shapes.get(shape);
}
}
private class GraphSpecies {
private ShapeAndPaint sP;
private boolean filled, visible, connected;
private String runNumber, species, directory, id;
private int number;
private GraphSpecies(Shape s, Paint p, boolean filled, boolean visible, boolean connected,
String runNumber, String id, String species, int number, String directory) {
sP = new ShapeAndPaint(s, p);
this.filled = filled;
this.visible = visible;
this.connected = connected;
this.runNumber = runNumber;
this.species = species;
this.number = number;
this.directory = directory;
this.id = id;
}
public void setNumber(int number) {
this.number = number;
}
private void setSpecies(String species) {
this.species = species;
}
private void setPaint(String paint) {
sP.setPaint(paint);
}
private void setShape(String shape) {
sP.setShape(shape);
}
private void setVisible(boolean b) {
visible = b;
}
private void setFilled(boolean b) {
filled = b;
}
private void setConnected(boolean b) {
connected = b;
}
private int getNumber() {
return number;
}
private String getSpecies() {
return species;
}
private ShapeAndPaint getShapeAndPaint() {
return sP;
}
private boolean getFilled() {
return filled;
}
private boolean getVisible() {
return visible;
}
private boolean getConnected() {
return connected;
}
private String getRunNumber() {
return runNumber;
}
private String getDirectory() {
return directory;
}
private String getID() {
return id;
}
}
public void setDirectory(String newDirectory) {
outDir = newDirectory;
}
public void setGraphName(String graphName) {
this.graphName = graphName;
}
public boolean hasChanged() {
return change;
}
private void probGraph(String label) {
chart = ChartFactory.createBarChart(label, "", "Percent", new DefaultCategoryDataset(),
PlotOrientation.VERTICAL, true, true, false);
ChartPanel graph = new ChartPanel(chart);
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Click here to create graph");
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
graph.addMouseListener(this);
change = false;
// creates the buttons for the graph frame
JPanel ButtonHolder = new JPanel();
save = new JButton("Save Graph");
export = new JButton("Export");
save.addActionListener(this);
export.addActionListener(this);
ButtonHolder.add(save);
ButtonHolder.add(export);
// puts all the components of the graph gui into a display panel
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, ButtonHolder, null);
splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
this.add(splitPane, "South");
}
private void editProbGraph() {
final ArrayList<GraphProbs> old = new ArrayList<GraphProbs>();
for (GraphProbs g : probGraphed) {
old.add(g);
}
JPanel titlePanel = new JPanel(new GridLayout(2, 6));
JLabel titleLabel = new JLabel("Title:");
JLabel xLabel = new JLabel("X-Axis Label:");
JLabel yLabel = new JLabel("Y-Axis Label:");
final JTextField title = new JTextField(chart.getTitle().getText(), 5);
final JTextField x = new JTextField(chart.getCategoryPlot().getDomainAxis().getLabel(), 5);
final JTextField y = new JTextField(chart.getCategoryPlot().getRangeAxis().getLabel(), 5);
String simDirString = outDir.split(separator)[outDir.split(separator).length - 1];
final DefaultMutableTreeNode simDir = new DefaultMutableTreeNode(simDirString);
String[] files = new File(outDir).list();
for (int i = 1; i < files.length; i++) {
String index = files[i];
int j = i;
while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) {
files[j] = files[j - 1];
j = j - 1;
}
files[j] = index;
}
final ArrayList<String> directories = new ArrayList<String>();
for (String file : files) {
if (file.length() > 3 && file.substring(file.length() - 4).equals(".txt")) {
if (file.contains("sim-rep")) {
simDir.add(new DefaultMutableTreeNode(file.substring(0, file.length() - 4)));
}
}
else if (new File(outDir + separator + file).isDirectory()) {
boolean addIt = false;
for (String getFile : new File(outDir + separator + file).list()) {
if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals(".txt")
&& getFile.contains("sim-rep")) {
addIt = true;
}
}
if (addIt) {
directories.add(file);
DefaultMutableTreeNode d = new DefaultMutableTreeNode(file);
for (String f : new File(outDir + separator + file).list()) {
if (f.contains(".txt") && f.contains("sim-rep")) {
d.add(new DefaultMutableTreeNode(f.substring(0, f.length() - 4)));
}
}
}
}
}
if (simDir.getChildCount() == 0) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "No data to graph."
+ "\nPerform some simutations to create some data first.", "No Data",
JOptionPane.PLAIN_MESSAGE);
}
else {
final JTree tree = new JTree(simDir);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.expandRow(i);
}
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
final JPanel specPanel = new JPanel();
boolean stop = false;
int selectionRow = 1;
for (int i = 1; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (selected.equals(lastSelected)) {
stop = true;
selectionRow = i;
break;
}
}
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
if (!directories.contains(node.toString())) {
selected = node.toString();
int select;
if (selected.equals("sim-rep")) {
select = 0;
}
else {
select = -1;
}
if (select != -1) {
specPanel.removeAll();
if (directories.contains(node.getParent().toString())) {
specPanel.add(fixProbChoices(node.getParent().toString()));
}
else {
specPanel.add(fixProbChoices(""));
}
specPanel.revalidate();
specPanel.repaint();
for (int i = 0; i < series.size(); i++) {
series.get(i).setText(graphProbs.get(i));
}
for (int i = 0; i < boxes.size(); i++) {
boxes.get(i).setSelected(false);
}
if (directories.contains(node.getParent().toString())) {
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(node.getParent().toString())) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName());
}
}
}
else {
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName());
}
}
}
boolean allChecked = true;
for (int i = 0; i < boxes.size(); i++) {
if (!boxes.get(i).isSelected()) {
allChecked = false;
String s = "";
if (directories.contains(node.getParent().toString())) {
s = "(" + node.getParent().toString() + ")";
}
String text = series.get(i).getText();
String end = "";
if (!s.equals("")) {
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
}
boxes.get(i).setName(text);
series.get(i).setText(text);
colorsCombo.get(i).setSelectedIndex(0);
}
else {
String s = "";
if (directories.contains(node.getParent().toString())) {
s = "(" + node.getParent().toString() + ")";
}
String text = graphProbs.get(i);
String end = "";
if (!s.equals("")) {
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
}
boxes.get(i).setName(text);
}
}
if (allChecked) {
use.setSelected(true);
}
else {
use.setSelected(false);
}
}
}
else {
specPanel.removeAll();
specPanel.revalidate();
specPanel.repaint();
}
}
});
if (!stop) {
tree.setSelectionRow(0);
tree.setSelectionRow(1);
}
else {
tree.setSelectionRow(0);
tree.setSelectionRow(selectionRow);
}
JScrollPane scroll = new JScrollPane();
scroll.setPreferredSize(new Dimension(1050, 500));
JPanel editPanel = new JPanel(new BorderLayout());
editPanel.add(titlePanel, "North");
editPanel.add(specPanel, "Center");
editPanel.add(scrollpane, "West");
scroll.setViewportView(editPanel);
final JButton deselect = new JButton("Deselect All");
deselect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int size = probGraphed.size();
for (int i = 0; i < size; i++) {
probGraphed.remove();
}
if (tree.getSelectionCount() > 0) {
int selectedRow = tree.getSelectionRows()[0];
tree.setSelectionRow(0);
tree.setSelectionRow(selectedRow);
}
}
});
titlePanel.add(titleLabel);
titlePanel.add(title);
titlePanel.add(xLabel);
titlePanel.add(x);
titlePanel.add(yLabel);
titlePanel.add(y);
titlePanel.add(new JPanel());
JPanel deselectPanel = new JPanel();
deselectPanel.add(deselect);
titlePanel.add(deselectPanel);
titlePanel.add(new JPanel());
titlePanel.add(new JPanel());
titlePanel.add(new JPanel());
titlePanel.add(new JPanel());
JPanel all = new JPanel(new BorderLayout());
all.add(scroll, "Center");
Object[] options = { "Ok", "Cancel" };
int value = JOptionPane.showOptionDialog(biomodelsim.frame(), all, "Edit Probability Graph",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
change = true;
lastSelected = selected;
selected = "";
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0)
&& (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt")
.exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator
+ "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), histDataset,
rend);
}
else {
selected = "";
int size = probGraphed.size();
for (int i = 0; i < size; i++) {
probGraphed.remove();
}
for (GraphProbs g : old) {
probGraphed.add(g);
}
}
}
}
private JPanel fixProbChoices(final String directory) {
if (directory.equals("")) {
readProbSpecies(outDir + separator + "sim-rep.txt");
}
else {
readProbSpecies(outDir + separator + directory + separator + "sim-rep.txt");
}
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
j = j - 1;
}
graphProbs.set(j, index);
}
JPanel speciesPanel1 = new JPanel(new GridLayout(graphProbs.size() + 1, 1));
JPanel speciesPanel2 = new JPanel(new GridLayout(graphProbs.size() + 1, 2));
use = new JCheckBox("Use");
JLabel specs = new JLabel("Species");
JLabel color = new JLabel("Color");
boxes = new ArrayList<JCheckBox>();
series = new ArrayList<JTextField>();
colorsCombo = new ArrayList<JComboBox>();
use.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (use.isSelected()) {
for (JCheckBox box : boxes) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : boxes) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
speciesPanel1.add(use);
speciesPanel2.add(specs);
speciesPanel2.add(color);
final HashMap<String, Paint> colory = this.colors;
for (int i = 0; i < graphProbs.size(); i++) {
JCheckBox temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
String s = series.get(i).getText();
((JCheckBox) e.getSource()).setSelected(false);
int[] cols = new int[34];
for (int k = 0; k < boxes.size(); k++) {
if (boxes.get(k).isSelected()) {
if (colorsCombo.get(k).getSelectedItem().equals("Red")) {
cols[0]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) {
cols[1]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green")) {
cols[2]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) {
cols[3]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) {
cols[4]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) {
cols[5]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) {
cols[6]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) {
cols[7]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) {
cols[8]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) {
cols[9]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Dark)")) {
cols[10]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Dark)")) {
cols[11]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Dark)")) {
cols[12]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Black")) {
cols[14]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red ")) {
cols[15]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue ")) {
cols[16]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green ")) {
cols[17]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow ")) {
cols[18]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta ")) {
cols[19]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan ")) {
cols[20]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Light)")) {
cols[21]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Extra Dark)")) {
cols[22]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Extra Dark)")) {
cols[23]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Extra Dark)")) {
cols[24]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Extra Dark)")) {
cols[25]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Extra Dark)")) {
cols[26]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Extra Dark)")) {
cols[27]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) {
cols[28]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Light)")) {
cols[29]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Light)")) {
cols[30]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Light)")) {
cols[31]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Light)")) {
cols[32]++;
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Light)")) {
cols[33]++;
}
}
}
for (GraphProbs graph : probGraphed) {
if (graph.getPaintName().equals("Red")) {
cols[0]++;
}
else if (graph.getPaintName().equals("Blue")) {
cols[1]++;
}
else if (graph.getPaintName().equals("Green")) {
cols[2]++;
}
else if (graph.getPaintName().equals("Yellow")) {
cols[3]++;
}
else if (graph.getPaintName().equals("Magenta")) {
cols[4]++;
}
else if (graph.getPaintName().equals("Cyan")) {
cols[5]++;
}
else if (graph.getPaintName().equals("Tan")) {
cols[6]++;
}
else if (graph.getPaintName().equals("Gray (Dark)")) {
cols[7]++;
}
else if (graph.getPaintName().equals("Red (Dark)")) {
cols[8]++;
}
else if (graph.getPaintName().equals("Blue (Dark)")) {
cols[9]++;
}
else if (graph.getPaintName().equals("Green (Dark)")) {
cols[10]++;
}
else if (graph.getPaintName().equals("Yellow (Dark)")) {
cols[11]++;
}
else if (graph.getPaintName().equals("Magenta (Dark)")) {
cols[12]++;
}
else if (graph.getPaintName().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (graph.getPaintName().equals("Black")) {
cols[14]++;
}
else if (graph.getPaintName().equals("Red ")) {
cols[15]++;
}
else if (graph.getPaintName().equals("Blue ")) {
cols[16]++;
}
else if (graph.getPaintName().equals("Green ")) {
cols[17]++;
}
else if (graph.getPaintName().equals("Yellow ")) {
cols[18]++;
}
else if (graph.getPaintName().equals("Magenta ")) {
cols[19]++;
}
else if (graph.getPaintName().equals("Cyan ")) {
cols[20]++;
}
else if (graph.getPaintName().equals("Gray (Light)")) {
cols[21]++;
}
else if (graph.getPaintName().equals("Red (Extra Dark)")) {
cols[22]++;
}
else if (graph.getPaintName().equals("Blue (Extra Dark)")) {
cols[23]++;
}
else if (graph.getPaintName().equals("Green (Extra Dark)")) {
cols[24]++;
}
else if (graph.getPaintName().equals("Yellow (Extra Dark)")) {
cols[25]++;
}
else if (graph.getPaintName().equals("Magenta (Extra Dark)")) {
cols[26]++;
}
else if (graph.getPaintName().equals("Cyan (Extra Dark)")) {
cols[27]++;
}
else if (graph.getPaintName().equals("Red (Light)")) {
cols[28]++;
}
else if (graph.getPaintName().equals("Blue (Light)")) {
cols[29]++;
}
else if (graph.getPaintName().equals("Green (Light)")) {
cols[30]++;
}
else if (graph.getPaintName().equals("Yellow (Light)")) {
cols[31]++;
}
else if (graph.getPaintName().equals("Magenta (Light)")) {
cols[32]++;
}
else if (graph.getPaintName().equals("Cyan (Light)")) {
cols[33]++;
}
}
((JCheckBox) e.getSource()).setSelected(true);
series.get(i).setText(s);
int colorSet = 0;
for (int j = 1; j < cols.length; j++) {
if (cols[j] < cols[colorSet]) {
colorSet = j;
}
}
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
for (int j = 0; j < colorSet; j++) {
draw.getNextPaint();
}
Paint paint = draw.getNextPaint();
Object[] set = colory.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (paint == colory.get(set[j])) {
colorsCombo.get(i).setSelectedItem(set[j]);
}
}
boolean allChecked = true;
for (JCheckBox temp : boxes) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
use.setSelected(true);
}
probGraphed.add(new GraphProbs(colory.get(colorsCombo.get(i).getSelectedItem()),
(String) colorsCombo.get(i).getSelectedItem(), boxes.get(i).getName(), series
.get(i).getText().trim(), i, directory));
}
else {
ArrayList<GraphProbs> remove = new ArrayList<GraphProbs>();
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
remove.add(g);
}
}
for (GraphProbs g : remove) {
probGraphed.remove(g);
}
use.setSelected(false);
colorsCombo.get(i).setSelectedIndex(0);
}
}
});
boxes.add(temp);
JTextField seriesName = new JTextField(graphProbs.get(i));
seriesName.setName("" + i);
seriesName.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyReleased(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyTyped(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
});
series.add(seriesName);
Object[] col = this.colors.keySet().toArray();
Arrays.sort(col);
JComboBox colBox = new JComboBox(col);
colBox.setActionCommand("" + i);
colBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaintName((String) ((JComboBox) e.getSource()).getSelectedItem());
g.setPaint(colory.get(((JComboBox) e.getSource()).getSelectedItem()));
}
}
}
});
colorsCombo.add(colBox);
speciesPanel1.add(boxes.get(i));
speciesPanel2.add(series.get(i));
speciesPanel2.add(colorsCombo.get(i));
}
JPanel speciesPanel = new JPanel(new BorderLayout());
speciesPanel.add(speciesPanel1, "West");
speciesPanel.add(speciesPanel2, "Center");
return speciesPanel;
}
private void readProbSpecies(String file) {
graphProbs = new ArrayList<String>();
ArrayList<String> data = new ArrayList<String>();
try {
Scanner s = new Scanner(new File(file));
while (s.hasNextLine()) {
String[] ss = s.nextLine().split(" ");
if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination")
&& ss[3].equals("count:") && ss[4].equals("0")) {
return;
}
if (data.size() == 0) {
for (String add : ss) {
data.add(add);
}
}
else {
for (int i = 0; i < ss.length; i++) {
data.set(i, data.get(i) + " " + ss[i]);
}
}
}
}
catch (Exception e) {
}
for (String s : data) {
if (!s.split(" ")[0].equals("#total")) {
graphProbs.add(s.split(" ")[0]);
}
}
}
private double[] readProbs(String file) {
ArrayList<String> data = new ArrayList<String>();
try {
Scanner s = new Scanner(new File(file));
while (s.hasNextLine()) {
String[] ss = s.nextLine().split(" ");
if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination")
&& ss[3].equals("count:") && ss[4].equals("0")) {
return new double[0];
}
if (data.size() == 0) {
for (String add : ss) {
data.add(add);
}
}
else {
for (int i = 0; i < ss.length; i++) {
data.set(i, data.get(i) + " " + ss[i]);
}
}
}
}
catch (Exception e) {
}
double[] dataSet = new double[data.size()];
double total = 0;
int i = 0;
if (data.get(0).split(" ")[0].equals("#total")) {
total = Double.parseDouble(data.get(0).split(" ")[1]);
i = 1;
}
for (; i < data.size(); i++) {
if (total == 0) {
dataSet[i] = Double.parseDouble(data.get(i).split(" ")[1]);
}
else {
dataSet[i - 1] = 100 * ((Double.parseDouble(data.get(i).split(" ")[1])) / total);
}
}
return dataSet;
}
private void fixProbGraph(String label, String xLabel, String yLabel,
DefaultCategoryDataset dataset, BarRenderer rend) {
chart = ChartFactory.createBarChart(label, xLabel, yLabel, dataset, PlotOrientation.VERTICAL,
true, true, false);
chart.getCategoryPlot().setRenderer(rend);
ChartPanel graph = new ChartPanel(chart);
if (probGraphed.isEmpty()) {
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Click here to create graph");
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
}
graph.addMouseListener(this);
JPanel ButtonHolder = new JPanel();
save = new JButton("Save Graph");
export = new JButton("Export");
save.addActionListener(this);
export.addActionListener(this);
ButtonHolder.add(save);
ButtonHolder.add(export);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, ButtonHolder, null);
splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
this.add(splitPane, "South");
this.revalidate();
}
public void refreshProb() {
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0)
&& (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator
+ "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis().getLabel(),
chart.getCategoryPlot().getRangeAxis().getLabel(), histDataset, rend);
}
private class GraphProbs {
private Paint paint;
private String species, directory, id, paintName;
private int number;
private GraphProbs(Paint paint, String paintName, String id, String species, int number,
String directory) {
this.paint = paint;
this.paintName = paintName;
this.species = species;
this.number = number;
this.directory = directory;
this.id = id;
}
private Paint getPaint() {
return paint;
}
private void setPaint(Paint p) {
paint = p;
}
private String getPaintName() {
return paintName;
}
private void setPaintName(String p) {
paintName = p;
}
private String getSpecies() {
return species;
}
private void setSpecies(String s) {
species = s;
}
private String getDirectory() {
return directory;
}
private String getID() {
return id;
}
private int getNumber() {
return number;
}
}
}
| Worked on graph
| gui/src/graph/Graph.java | Worked on graph |
|
Java | apache-2.0 | 343fae3b01c6cda33f4fa522993985bfcf370cb3 | 0 | JohnReedLOL/Nineteen_Characters | /**
* Implementor: Alex Stewart
* Last Update: 15-02-13
*/
package src;
import src.controller.Entity;
import src.model.MapMain_Relation;
import src.view.Display;
import src.view.MapView;
import java.io.*;
import java.lang.StackTraceElement;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Initializes, opens the program.
* @author JohnReedLOL, Alex Stewart
*/
public class Main
{
private static ProgramOpts pOpts_ = null;
private static SavedGame saveGame_;
private static MapMain_Relation mmr_;
public static void main(String[] args) {
// Commenting out errors
/*
parseArgs(args); // Parse command line arguments
initialize(); // Initialize any data we need to before loading
handleArgs(args);
// testing
saveGameToDisk();
exitGame();
//initializeEverything();
*/
}
// <editor-fold desc="GAME METHODS" defaultstate="collapsed">
private static void exitGame() {
}
private static void initialize() {
saveGame_ = null;
mmr_ = new MapMain_Relation(); // Initialize the Map Object
MapMain_Relation newmmr_ = new MapMain_Relation();
newmmr_.createNewMap(5, 5); // Each MapMain Relation creates a map and binds itself to that map.
newmmr_.addEntity(new src.controller.Avatar("test", 'x', 0, 0), 0, 0);
}
private static void saveGameToDisk() {
if (saveGame_ == null) {
saveGame_ = SavedGame.newSavedGame();
}
Exception e = null;
saveGame_.saveFile(mmr_, e);
if (e != null)
errOut(e);
}
// TODO: complete
private static int startNewGame() {
return 0;
}
// </editor-fold>
// <editor-fold desc="UTILITIES" defaultstate="collapsed">
// Error date format for the errOut(Exception) write
private static SimpleDateFormat errDateFormat_ = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
/**
* This class holds information about optional program utilities which may
* be triggered via command line arguments. Reference {@link #parseArgs}
* for parsing implementation.
*/
private static class ProgramOpts {
// Debug Mode
String[] dbg_match = {"-d", "--debug"};
boolean dbg_flag = false;
// Load Saved Game
String[] lsg_match = {"-l", "--load"}; // option flag match string
boolean lsg_flag = false; // whether or not to load the game
int lsg_path = -1; // the index in args to get the path from
// Redirect STDERR
String[] err_match = {"-e", "-err-out"};
boolean err_flag = false;
int err_path = -1;
}
/**
* Writes the provided String to the errOut stream with the prefix: (DEBUG).
* @param s The String to write.
*/
public static void dbgOut(String s) {
if (s == null) s = "NULL";
if (pOpts_.dbg_flag)
errOut("(DEBUG) " + s);
}
/**
* Writes the provided Exception to the errOut stream with the prefix: "ERROR:" and WITHOUT a stack trace called.
* If you wish to print the stack tace, call {@link #errOut(Exception, boolean)} with printTrace set to TRUE.
* @param e The Exception to write
*/
public static void errOut(Exception e) {
errOut(e, false);
}
/**
* Writes the provided Exception to the errOut stream with the prefix: "ERROR:"
* @param e The Exception object to write
* @param printTrace whether or not to print the Exception's stack trace below the error output
*/
public static void errOut(Exception e, boolean printTrace) {
if (e == null) {
errOut("errOut called with null Exception");
}
errOut("ERROR: " + e.getMessage());
if (!printTrace)
return;
for (StackTraceElement elem : e.getStackTrace()) {
errOut("TRACE: " + elem.toString());
}
}
/**
* Writes the provided String to the errOut stream.
* @param s The message to write out.
*/
public static void errOut(String s) {
if (s == null) s = "NULL";
System.err.println("[" + errDateFormat_.format(new Date()) + "] " + s);
}
private static void handleArgs(String[] args) {
if (pOpts_.err_flag) {
try {
System.setErr(new PrintStream(args[pOpts_.err_path]));
} catch (FileNotFoundException e) {
errOut(e);
}
}
if (pOpts_.lsg_flag) {
saveGame_ = new SavedGame(args[pOpts_.lsg_path]);
Exception e = null;
int s = saveGame_.loadFile(mmr_, e);
if (s == 0) { // the saved game load has failed
errOut(e); // print out error
if (startNewGame() == 0) {
errOut(e);
exitGame();
}
}
}
}
private static void parseArgs(String[] args) {
pOpts_ = new ProgramOpts();
for (int a = 0; a < args.length; a++) {
// DEBUG
for (String m : pOpts_.dbg_match) {
if (m.equals(args[a])) {
pOpts_.dbg_flag = true;
break;
}
}
// LOAD SAVED GAME
for (String m : pOpts_.lsg_match) {
if (m.equals(args[a]) && (args.length > a + 1)) {
pOpts_.lsg_path = a + 1;
pOpts_.lsg_flag = true;
break;
}
}
// REDIRECT STDERR
for (String m : pOpts_.err_match) {
if (m.equals(args[a]) && (args.length > a + 1)) {
pOpts_.err_path = a + 1;
pOpts_.err_flag = true;
break;
}
}
}
}
// </editor-fold>
} // end of Main
| src/src/Main.java | /**
* Implementor: Alex Stewart
* Last Update: 15-02-13
*/
package src;
import src.controller.Entity;
import src.model.MapMain_Relation;
import src.view.Display;
import src.view.MapView;
import java.io.*;
import java.lang.StackTraceElement;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Initializes, opens the program.
* @author JohnReedLOL, Alex Stewart
*/
public class Main
{
private static ProgramOpts pOpts_ = null;
private static SavedGame saveGame_;
private static MapMain_Relation mmr_;
public static void main(String[] args) {
parseArgs(args); // Parse command line arguments
initialize(); // Initialize any data we need to before loading
handleArgs(args);
// testing
saveGameToDisk();
exitGame();
//initializeEverything();
}
// <editor-fold desc="GAME METHODS" defaultstate="collapsed">
private static void exitGame() {
}
private static void initialize() {
saveGame_ = null;
mmr_ = new MapMain_Relation(); // Initialize the Map Object
MapMain_Relation newmmr_ = new MapMain_Relation();
newmmr_.createNewMap(5, 5); // Each MapMain Relation creates a map and binds itself to that map.
newmmr_.addEntity(new src.controller.Avatar("test", 'x', 0, 0), 0, 0);
}
private static void saveGameToDisk() {
if (saveGame_ == null) {
saveGame_ = SavedGame.newSavedGame();
}
Exception e = null;
saveGame_.saveFile(mmr_, e);
if (e != null)
errOut(e);
}
// TODO: complete
private static int startNewGame() {
return 0;
}
// </editor-fold>
// <editor-fold desc="UTILITIES" defaultstate="collapsed">
// Error date format for the errOut(Exception) write
private static SimpleDateFormat errDateFormat_ = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
/**
* This class holds information about optional program utilities which may
* be triggered via command line arguments. Reference {@link #parseArgs}
* for parsing implementation.
*/
private static class ProgramOpts {
// Debug Mode
String[] dbg_match = {"-d", "--debug"};
boolean dbg_flag = false;
// Load Saved Game
String[] lsg_match = {"-l", "--load"}; // option flag match string
boolean lsg_flag = false; // whether or not to load the game
int lsg_path = -1; // the index in args to get the path from
// Redirect STDERR
String[] err_match = {"-e", "-err-out"};
boolean err_flag = false;
int err_path = -1;
}
/**
* Writes the provided String to the errOut stream with the prefix: (DEBUG).
* @param s The String to write.
*/
public static void dbgOut(String s) {
if (s == null) s = "NULL";
if (pOpts_.dbg_flag)
errOut("(DEBUG) " + s);
}
/**
* Writes the provided Exception to the errOut stream with the prefix: "ERROR:" and WITHOUT a stack trace called.
* If you wish to print the stack tace, call {@link #errOut(Exception, boolean)} with printTrace set to TRUE.
* @param e The Exception to write
*/
public static void errOut(Exception e) {
errOut(e, false);
}
/**
* Writes the provided Exception to the errOut stream with the prefix: "ERROR:"
* @param e The Exception object to write
* @param printTrace whether or not to print the Exception's stack trace below the error output
*/
public static void errOut(Exception e, boolean printTrace) {
if (e == null) {
errOut("errOut called with null Exception");
}
errOut("ERROR: " + e.getMessage());
if (!printTrace)
return;
for (StackTraceElement elem : e.getStackTrace()) {
errOut("TRACE: " + elem.toString());
}
}
/**
* Writes the provided String to the errOut stream.
* @param s The message to write out.
*/
public static void errOut(String s) {
if (s == null) s = "NULL";
System.err.println("[" + errDateFormat_.format(new Date()) + "] " + s);
}
private static void handleArgs(String[] args) {
if (pOpts_.err_flag) {
try {
System.setErr(new PrintStream(args[pOpts_.err_path]));
} catch (FileNotFoundException e) {
errOut(e);
}
}
if (pOpts_.lsg_flag) {
saveGame_ = new SavedGame(args[pOpts_.lsg_path]);
Exception e = null;
int s = saveGame_.loadFile(mmr_, e);
if (s == 0) { // the saved game load has failed
errOut(e); // print out error
if (startNewGame() == 0) {
errOut(e);
exitGame();
}
}
}
}
private static void parseArgs(String[] args) {
pOpts_ = new ProgramOpts();
for (int a = 0; a < args.length; a++) {
// DEBUG
for (String m : pOpts_.dbg_match) {
if (m.equals(args[a])) {
pOpts_.dbg_flag = true;
break;
}
}
// LOAD SAVED GAME
for (String m : pOpts_.lsg_match) {
if (m.equals(args[a]) && (args.length > a + 1)) {
pOpts_.lsg_path = a + 1;
pOpts_.lsg_flag = true;
break;
}
}
// REDIRECT STDERR
for (String m : pOpts_.err_match) {
if (m.equals(args[a]) && (args.length > a + 1)) {
pOpts_.err_path = a + 1;
pOpts_.err_flag = true;
break;
}
}
}
}
// </editor-fold>
} // end of Main
| Temporarily commenting out errors | src/src/Main.java | Temporarily commenting out errors |
|
Java | apache-2.0 | 3f0cbd1bcaf66d5dac6bf62031de25e0faa23a29 | 0 | missioncommand/mil-sym-java,missioncommand/mil-sym-java,missioncommand/mil-sym-java,missioncommand/mil-sym-java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package RenderMultipoints;
import JavaTacticalRenderer.clsUtility;
import JavaTacticalRenderer.TGLight;
import java.util.ArrayList;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.Line2D;
import java.awt.Polygon;
import ArmyC2.C2SD.Utilities.ErrorLogger;
import ArmyC2.C2SD.Utilities.RendererException;
import JavaLineArray.POINT2;
import JavaLineArray.TacticalLines;
import JavaLineArray.Shape2;
import JavaLineArray.lineutility;
import java.util.HashMap;
import java.util.Map;
/**
* Class to clip polygons
* @author Michael Deutch
*/
public class clsClipQuad {
private static String _className = "clsClipQuad";
/**
* Use the new version which takes an array for polygon clip bounds instead of rectangle
* @param polygon
* @param clipBounds
* @return
*/
private static int AddBoundaryPointsForLines(ArrayList<Point2D> polygon,
ArrayList<Point2D> clipBounds)
{
int result=0;
try
{
Point2D pt02d=polygon.get(0);
Point2D ptLast2d=polygon.get((polygon.size()-1));
POINT2 pt0=new POINT2(pt02d.getX(),pt02d.getY());
POINT2 ptLast=new POINT2(ptLast2d.getX(),ptLast2d.getY());
Point2D nearestPt=new Point2D.Double();
Polygon clipArray=new Polygon();
int j=0;
double minDist=Double.MAX_VALUE;
double dist=0;
POINT2 sidePt=new POINT2();
Boolean addToFront = false, addToEnd = false;
for(j=0;j<clipBounds.size();j++)
{
clipArray.addPoint((int)clipBounds.get(j).getX(), (int)clipBounds.get(j).getY());
}
double totalX=0,totalY=0;
int counter=0;
for(j=0;j<clipBounds.size()-1;j++)
{
totalX+=clipBounds.get(j).getX();
totalY+=clipBounds.get(j).getY();
counter++;
}
//if clipBounds is not closed add the jth point
if( clipBounds.get(0).getX()!=clipBounds.get(j).getX() ||
clipBounds.get(0).getY()!=clipBounds.get(j).getY() )
{
totalX+=clipBounds.get(j).getX();
totalY+=clipBounds.get(j).getY();
counter++;
}
double avgX=totalX/counter;
double avgY=totalY/counter;
POINT2 ptCenter=new POINT2(avgX,avgY);
POINT2 ptNear=null;
//first point outside the clip bounds
if(clipArray.contains(pt02d)==false)
{
//add nearest segment midpoint to the front
for(j=0;j<clipBounds.size();j++)
{
sidePt.x=clipBounds.get(j).getX();
sidePt.y=clipBounds.get(j).getY();
dist=lineutility.CalcDistanceDouble(pt0, sidePt);
if(dist<minDist)
{
minDist=dist;
//minDistIndex=j;
nearestPt.setLocation(sidePt.x,sidePt.y);
}
}
//move nearestPt in a bit to not get clipped
ptNear=new POINT2(nearestPt.getX(),nearestPt.getY());
ptNear=lineutility.ExtendAlongLineDouble(ptNear, ptCenter, 2);
nearestPt.setLocation(ptNear.x, ptNear.y);
polygon.add(0, nearestPt);
addToFront=true;
}
//re-initialize variables
nearestPt=new Point2D.Double();
minDist=Double.MAX_VALUE;
//last point outside the clip bounds
if(clipArray.contains(ptLast2d)==false)
{
//add nearest segment midpoint to the front
for(j=0;j<clipBounds.size();j++)
{
sidePt.x=clipBounds.get(j).getX();
sidePt.y=clipBounds.get(j).getY();
dist=lineutility.CalcDistanceDouble(ptLast, sidePt);
if(dist<minDist)
{
minDist=dist;
//minDistIndex=j;
nearestPt.setLocation(sidePt.x,sidePt.y);
}
}
//move nearestPt in a bit to not get clipped
ptNear=new POINT2(nearestPt.getX(),nearestPt.getY());
ptNear=lineutility.ExtendAlongLineDouble(ptNear, ptCenter, 2);
nearestPt.setLocation(ptNear.x, ptNear.y);
polygon.add(nearestPt);
addToEnd=true;
}
if (addToFront == false && addToEnd == false) {
result = 0;
}
else if (addToFront == true && addToEnd == false) {
result = 1;
}
else if (addToFront == false && addToEnd == true) {
result = 2;
}
else if (addToFront == true && addToEnd == true) {
result = 3;
}
}
catch (Exception exc)
{
ErrorLogger.LogException(_className, "AddBoundaryPointsForLines",
new RendererException("Failed inside AddBoundaryPointsForLines", exc));
}
return result;
}
/**
* @deprecated
* @param polygon
* @param clipBounds
* @return
*/
private static int AddBoundaryPointsForLines(ArrayList<Point2D> polygon,
Rectangle2D clipBounds) {
int result = 0;
try {
double ulx = 0, uly = 0, lrx = 0, lry = 0;
ulx = clipBounds.getMinX();
uly = clipBounds.getMinY();
lrx = clipBounds.getMaxX();
lry = clipBounds.getMaxY();
//move these inside by 10 pixels so the algoithm will treat them as inside points
Point2D ul = new Point2D.Double(ulx + 10, uly + 10);
Point2D lr = new Point2D.Double(lrx - 10, lry - 10);
Point2D pt0 = polygon.get(0);
Point2D ptn = polygon.get(polygon.size() - 1);
Boolean addToFront = false, addToEnd = false;
//add a point to the begining of the array
if (pt0.getY() < uly) //above the top clip
{
polygon.add(0, ul);
addToFront = true;
} else if (pt0.getX() < ulx) //outside the left clip
{
polygon.add(0, ul);
addToFront = true;
} else if (pt0.getX() > lrx) //outside the right clip
{
polygon.add(0, lr);
addToFront = true;
} else if (pt0.getY() > lry) //below the bottom clip
{
polygon.add(0, lr);
addToFront = true;
}
//add a point to the end of the array
if (ptn.getY() < uly) //above the top clip
{
polygon.add(ul);
addToEnd = true;
} else if (ptn.getX() < ulx) //outside the left clip
{
polygon.add(ul);
addToEnd = true;
} else if (ptn.getX() > lrx) //outside the right clip
{
polygon.add(lr);
addToEnd = true;
} else if (ptn.getY() > lry) //below the bottom clip
{
polygon.add(lr);
addToEnd = true;
}
if (addToFront == false && addToEnd == false) {
result = 0;
}
if (addToFront == true && addToEnd == false) {
result = 1;
}
if (addToFront == false && addToEnd == true) {
result = 2;
}
if (addToFront == true && addToEnd == true) {
result = 3;
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "AddBoundaryPointsForLines",
new RendererException("Failed inside AddBoundaryPointsForLines", exc));
}
return result;
}
private static Point2D CalcTrueIntersectDouble(double m1,
double b1,
double m2,
double b2,
int bolVertical1,
int bolVertical2,
double X1, //x intercept if line1 is vertical
double X2)
{
//POINT2 ptIntersect=new POINT2();
Point2D ptIntersect=new Point2D.Double(X1,X2);
try
{
//declarations
double x=0,y=0;
//end declarations
//initialize ptIntersect
//ptIntersect.x=X1;
//ptIntersect.y=X2;
if(bolVertical1==0 && bolVertical2==0) //both lines vertical
return ptIntersect;
//the following 3 if blocks are the only ways to get an intersection
if(bolVertical1==0 && bolVertical2==1) //line1 vertical, line2 not
{
//ptIntersect.x=X1;
//ptIntersect.y=m2*X1+b2;
ptIntersect.setLocation(X1, m2*X1+b2);
return ptIntersect;
}
if(bolVertical1==1 && bolVertical2==0) //line2 vertical, line1 not
{
//ptIntersect.x=X2;
//ptIntersect.y=m1*X2+b1;
ptIntersect.setLocation(X2, m1*X2+b1);
return ptIntersect;
}
//if either of the lines is vertical function has already returned
//so both m1 and m2 should be valid
//should always be using this ocase because the lines are neither vertical
//or horizontal and are perpendicular
if(m1 != m2)
{
x=(b2-b1)/(m1-m2); //cannot blow up
y=(m1*x+b1);
//ptIntersect.x=x;
//ptIntersect.y=y;
ptIntersect.setLocation(x, y);
return ptIntersect;
}
}
catch(Exception exc)
{
ErrorLogger.LogException(_className ,"CalcTrueIntersectDouble",
new RendererException("Failed inside CalcTrueIntersectDouble", exc));
}
return ptIntersect;
}
/**
* Gets theoretical intersection of an edge with the line connecting previous and current points.
* @param pt0
* @param pt1
* @param currentEdge the current edge of the clip area, assumed to not be vertical
* @return
*/
private static Point2D intersectPoint2(Point2D previous,
Point2D current,
Line2D currentEdge)
{
Point2D ptIntersect=null;
try
{
Point2D ll=currentEdge.getP1();
Point2D ul=currentEdge.getP2();
//no vertical client segments
if(current.getX()==previous.getX())
current.setLocation(current.getX()+1, current.getY());
double m1=( ul.getY()-ll.getY() )/( ul.getX()-ll.getX() );
double m2=( current.getY()-previous.getY() )/( current.getX()-previous.getX() );
double b1=ul.getY()-m1*ul.getX();
double b2=current.getY()-m2*current.getX();
ptIntersect=CalcTrueIntersectDouble(m1,b1,m2,b2,1,1,0,0);
}
catch (Exception exc) {
ErrorLogger.LogException(_className, "intersectPoint2",
new RendererException("Failed inside intersectPoint2", exc));
}
return ptIntersect;
}
/**
* clips array of pts against a side of the clip bounds polygon
* assumes clipBounds has no vertical or horizontal segments
* @param pts array of points to clip against the clip bounds
* @param index starting index of clipBounds for the side to clip against
* @param clipBounds a quadrilateral or a polygon array that is the clipping area
* @return the clipped array of points
*/
private static ArrayList<Point2D> clipSide(ArrayList<Point2D> pts,
int index,
ArrayList<Point2D> clipBounds)
{
ArrayList<Point2D> ptsResult=null;
try
{
Point2D pt1=new Point2D.Double(clipBounds.get(index).getX(),clipBounds.get(index).getY());//first point of clip side
Point2D pt2=new Point2D.Double(clipBounds.get(index+1).getX(),clipBounds.get(index+1).getY());//last point of clip side
Point2D clipBoundsPoint=null;//some point in the clipbounds not on the side
Point2D ptClipBoundsIntersect=null;//some point in the clipbounds not on the side
double m1=0,m2=0,b1=0,b2=0,b3=0,b4=0;
Point2D ptPreviousIntersect=null,ptCurrentIntersect=null;
int j = 0,clipBoundsQuadrant=-1,previousQuadrant=-1,currentQuadrant=-1; //quadrants relative to side
Point2D current = null, previous = null;
Point2D intersectPt = null;
Line2D edge;
ptsResult=new ArrayList();
//set some point in the array which is not in the side
//this point will be used to define which side of the clipping side the rest of the clipbounds points are on
//then it can be used to figure out whether a given point is to be clipped
//for this scheme to work it needs to be a convex clipping area
if(index==0)
{
clipBoundsPoint=new Point2D.Double(clipBounds.get(index+2).getX(),clipBounds.get(index+2).getY());
}
else if(index>1)
{
//clipBoundsPoint=clipBounds.get(index-2);
clipBoundsPoint=new Point2D.Double(clipBounds.get(index-2).getX(),clipBounds.get(index-2).getY());
}
else if(index==1)
{
//clipBoundsPoint=clipBounds.get(0);
clipBoundsPoint=new Point2D.Double(clipBounds.get(0).getX(),clipBounds.get(0).getY());
}
//no vertical segments
if(pt2.getX()==pt1.getX())
pt2.setLocation(pt2.getX()+1, pt2.getY());
if(pt2.getY()==pt1.getY())
pt2.setLocation(pt2.getX(), pt2.getY()+1);
for (j = 0; j < pts.size(); j++)
{
current = pts.get(j);
if (j == 0)
{
previous = pts.get(pts.size() - 1);
}
else
{
previous = pts.get(j - 1);
}
m1=(pt2.getY()-pt1.getY())/(pt2.getX()-pt1.getX());
m2=-1d/m1; //the slope of the line perpendicular to m1,b1
b1=pt2.getY()-m1*pt2.getX();
b2=previous.getY()-m2*previous.getX();
b3=current.getY()-m2*current.getX();
b4=clipBoundsPoint.getY()-m2*clipBoundsPoint.getX();
ptPreviousIntersect=CalcTrueIntersectDouble(m1,b1,m2,b2,1,1,0,0);
ptCurrentIntersect=CalcTrueIntersectDouble(m1,b1,m2,b3,1,1,0,0);
ptClipBoundsIntersect=CalcTrueIntersectDouble(m1,b1,m2,b4,1,1,0,0);
clipBoundsQuadrant=lineutility.GetQuadrantDouble(clipBoundsPoint.getX(), clipBoundsPoint.getY(), ptClipBoundsIntersect.getX(), ptClipBoundsIntersect.getY());
previousQuadrant=lineutility.GetQuadrantDouble(previous.getX(), previous.getY(), ptPreviousIntersect.getX(), ptPreviousIntersect.getY());
currentQuadrant=lineutility.GetQuadrantDouble(current.getX(), current.getY(), ptCurrentIntersect.getX(), ptCurrentIntersect.getY());
//case: both inside
if(previousQuadrant==clipBoundsQuadrant && currentQuadrant==clipBoundsQuadrant)
ptsResult.add(current);
else if(previousQuadrant==clipBoundsQuadrant && currentQuadrant!=clipBoundsQuadrant)//previous inside, current outside
{
edge = new Line2D.Double(pt1, pt2);
intersectPt = intersectPoint2(previous, current, edge);
if (intersectPt != null)
{
ptsResult.add(intersectPt);
}
}
else if(previousQuadrant!=clipBoundsQuadrant && currentQuadrant==clipBoundsQuadrant)//current inside, previous outside
{
edge = new Line2D.Double(pt1, pt2);
intersectPt = intersectPoint2(previous, current, edge);
if (intersectPt != null)
{
ptsResult.add(intersectPt);
}
ptsResult.add(current);
}
else if(previousQuadrant!=clipBoundsQuadrant && currentQuadrant!=clipBoundsQuadrant)
continue;
}//end for j=0 to pts.size()-1
}//end try
catch (Exception exc) {
ErrorLogger.LogException(_className, "clipSide",
new RendererException("Failed inside clipSide", exc));
}
return ptsResult;
}
/**
* for pre-clipped lines which also require fill but need the processed points
* to create the fill. This function is called after the clip, so the fill
* does not get clipped.
* @param tg
* @param shapes
*/
protected static void addAbatisFill(TGLight tg,
ArrayList<Shape2>shapes)
{
try
{
if(tg.Pixels==null ||
tg.Pixels.size()<2 ||
tg.get_FillColor()==null ||
tg.get_FillColor().getAlpha()<2 ||
shapes==null)
return;
int j=0,n=tg.Pixels.size();
Shape2 shape=null;
TGLight tg2=null;
switch(tg.get_LineType())
{
case TacticalLines.MSDZ:
double dist0=0,dist1=0,dist2=0;
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.setFillColor(tg.get_FillColor());
if(tg.Pixels != null & tg.Pixels.size()>=300)
{
dist0=Math.abs(tg.Pixels.get(0).x-tg.Pixels.get(50).x);
dist1=Math.abs(tg.Pixels.get(100).x-tg.Pixels.get(150).x);
dist2=Math.abs(tg.Pixels.get(200).x-tg.Pixels.get(250).x);
int start=-1,end=-1;
if(dist0>=dist1 && dist0>=dist2)
{
start=0;
end=99;
}
else if(dist1>=dist0 && dist1>=dist2)
{
start=100;
end=199;
}
else
{
start=200;
end=299;
}
shape.moveTo(tg.Pixels.get(start));
for(j=start;j<=end;j++)
shape.lineTo(tg.Pixels.get(j));
//shapes.add(0,shape);
}
break;
case TacticalLines.ABATIS:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.setFillColor(tg.get_FillColor());
tg2=new TGLight();
tg2.set_LineType(TacticalLines.GENERAL);
tg2.Pixels=new ArrayList();
if(tg.Pixels != null && tg.Pixels.size()>2)
{
tg2.Pixels.add(tg.Pixels.get(n-3));
tg2.Pixels.add(tg.Pixels.get(n-2));
tg2.Pixels.add(tg.Pixels.get(n-1));
tg2.Pixels.add(tg.Pixels.get(n-3));
shape.moveTo(tg2.Pixels.get(0));
for(j=1;j<tg2.Pixels.size();j++)
shape.lineTo(tg2.Pixels.get(j));
//shapes.add(shape);
}
break;
default:
return;
}//end switch
if(shapes != null)
shapes.add(0,shape);
}
catch (Exception exc) {
ErrorLogger.LogException(_className, "addAbatisFill",
new RendererException("Failed inside addAbatisFill", exc));
}
return;
}
/**
* for lines with glyphs the fill must be handled (clipped) as a separate shape.
* this function needs to be called before the clipping is done to the line
* @param tg
* @param shapes
*/
protected static ArrayList<Shape2> LinesWithFill(TGLight tg,
ArrayList<Point2D> clipBounds)
{
ArrayList<Shape2>shapes=null;
try
{
if(tg.get_FillColor()==null || tg.get_FillColor().getAlpha()<=1 ||
tg.Pixels==null || tg.Pixels.isEmpty())
return shapes;
switch(tg.get_LineType())
{
case TacticalLines.ABATIS:
case TacticalLines.SPT:
case TacticalLines.MAIN:
case TacticalLines.AAAAA:
case TacticalLines.AIRAOA:
case TacticalLines.AXAD:
case TacticalLines.AAFNT:
case TacticalLines.CATK:
case TacticalLines.CATKBYFIRE:
case TacticalLines.CORDONSEARCH:
case TacticalLines.CORDONKNOCK:
case TacticalLines.SECURE:
case TacticalLines.OCCUPY:
case TacticalLines.RETAIN:
case TacticalLines.ISOLATE:
case TacticalLines.CONVOY:
case TacticalLines.HCONVOY:
return shapes;
case TacticalLines.PAA_RECTANGULAR:
return null;
case TacticalLines.OBSFAREA:
case TacticalLines.OBSAREA:
case TacticalLines.STRONG:
case TacticalLines.ZONE:
case TacticalLines.FORT:
case TacticalLines.ENCIRCLE:
case TacticalLines.BELT:
//case TacticalLines.BELT1:
case TacticalLines.DMA:
case TacticalLines.DMAF:
case TacticalLines.ATDITCHC:
case TacticalLines.ATDITCHM:
return fillDMA(tg,clipBounds);
default:
break;
}
if(clsUtility.LinesWithFill(tg.get_LineType())==false)
return shapes;
shapes=new ArrayList();
//undo any fillcolor that might have been set for the existing shape
//because we are divorcing fill from the line
Shape2 shape=null;
//create a generic area tg from the pixels and clip it
TGLight tg2=new TGLight();
tg2.set_LineType(TacticalLines.GENERAL);
tg2.Pixels=new ArrayList();
tg2.Pixels.addAll(tg.Pixels);
closeAreaTG(tg2);
//tg2.Pixels.add(tg.Pixels.get(0));
if(clipBounds != null)
ClipPolygon(tg2,clipBounds);
if(tg2.Pixels==null || tg2.Pixels.isEmpty())
return null;
int j=0;
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.setFillColor(tg.get_FillColor());
shape.moveTo(tg2.Pixels.get(0));
for(j=1;j<tg2.Pixels.size();j++)
shape.lineTo(tg2.Pixels.get(j));
if(tg.get_FillColor() != null || tg.get_FillColor().getAlpha()>1)
{
shapes.add(shape);
}
else
return null;
}
catch (Exception exc) {
ErrorLogger.LogException(_className, "LinesWithFill",
new RendererException("Failed inside LinesWithFill", exc));
}
return shapes;
}
/**
* closes an area
* @param tg
*/
private static void closeAreaTG(TGLight tg)
{
try
{
if(tg.Pixels==null || tg.Pixels.isEmpty())
return;
POINT2 pt0=tg.Pixels.get(0);
POINT2 ptn=tg.Pixels.get(tg.Pixels.size()-1);
if(pt0.x != ptn.x || pt0.y != ptn.y)
tg.Pixels.add(pt0);
}
catch (Exception exc) {
ErrorLogger.LogException(_className, "closeAreaTG",
new RendererException("Failed inside closeAreaTG", exc));
}
return;
}
/**
* DMA, DMAF fill must be handled separately because of the feint
* @param tg
* @param clipBounds
* @return
*/
protected static ArrayList<Shape2> fillDMA(TGLight tg,
ArrayList<Point2D> clipBounds)
{
ArrayList<Shape2>shapes=new ArrayList();
try
{
switch(tg.get_LineType())
{
case TacticalLines.OBSFAREA:
case TacticalLines.OBSAREA:
case TacticalLines.STRONG:
case TacticalLines.ZONE:
case TacticalLines.FORT:
case TacticalLines.ENCIRCLE:
case TacticalLines.BELT1:
case TacticalLines.BELT:
case TacticalLines.DMA:
case TacticalLines.DMAF:
case TacticalLines.ATDITCHC:
case TacticalLines.ATDITCHM:
break;
default:
return shapes;
}
Shape2 shape=null;
//create a generic area tg from the pixels and clip it
int j=0;
TGLight tg2=new TGLight();
tg2.set_LineType(TacticalLines.GENERAL);
tg2.Pixels=new ArrayList();
//to get the original pixels size
int n=0;
// if(tg.LatLongs != null)
// n=tg.LatLongs.size();
// else
n=tg.Pixels.size();
for(j=0;j<n;j++)
tg2.Pixels.add(tg.Pixels.get(j));
closeAreaTG(tg2);
if(clipBounds != null)
ClipPolygon(tg2,clipBounds);
if(tg2.Pixels==null || tg2.Pixels.isEmpty())
return shapes;
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.setFillColor(tg.get_FillColor());
shape.moveTo(tg2.Pixels.get(0));
//original pixels do not include feint
for(j=1;j<tg2.Pixels.size();j++)
shape.lineTo(tg2.Pixels.get(j));
shapes.add(shape);
}
catch (Exception exc) {
ErrorLogger.LogException(_className, "fillDMA",
new RendererException("Failed inside fillDMA", exc));
}
return shapes;
}
private static Boolean isClosed(ArrayList<POINT2>pts)
{
boolean closed=false;
if(pts==null || pts.isEmpty())
return false;
POINT2 pt0=pts.get(0);
POINT2 ptLast=pts.get(pts.size()-1);
if(pt0.x==ptLast.x && pt0.y==ptLast.y)
closed=true;
return closed;
}
/**
*
* @param tg
* @param clipBounds polygon representing clipping area
* @return
*/
protected static ArrayList<Point2D> ClipPolygon(TGLight tg,
ArrayList<Point2D> clipBounds) {
ArrayList<Point2D> poly = new ArrayList();
try
{
//diagnostic
//Boolean isClosed = clsUtility.isClosedPolygon(tg.get_LineType());
Boolean isClosed = isClosed(tg.Pixels);
//M. Deutch commented one line 12-27-12
clipBounds=clsUtilityGE.expandPolygon(clipBounds, 20);
ArrayList polygon = clsUtilityCPOF.POINT2toPoint2D(tg.Pixels);
int j=0;
Map<String,Object>hashMap=new HashMap<String,Object>();
//int hashCode=0;
for(j=0;j<polygon.size();j++)
hashMap.put(Integer.toString(j), polygon.get(j));
//close the clipbounds if necessary
Point2D clipBoundsPtStart=clipBounds.get(0);
Point2D clipBoundsPtEnd=clipBounds.get(clipBounds.size()-1);
if(clipBoundsPtStart.getX() != clipBoundsPtEnd.getX() ||
clipBoundsPtStart.getY() != clipBoundsPtEnd.getY())
clipBounds.add(clipBoundsPtStart);
int addedLinePoints = 0;
if (isClosed)
polygon.remove(polygon.size() - 1);
else
{
//for tactical lines it always seems to work if the 0th and last points are inside the area
//add points on the edge as needed to make that happen
//Rectangle2D clipBounds2=RenderMultipoints.clsUtility.getMBR(clipBounds);
//clipBounds2.setRect(clipBounds2.getMinX()-20, clipBounds2.getMinY()-20, clipBounds2.getWidth()+40, clipBounds2.getHeight()+40);;
addedLinePoints = AddBoundaryPointsForLines(polygon, clipBounds);
}
for(j=0;j<clipBounds.size()-1;j++)
{
if(j==0)
poly=clipSide(polygon,j,clipBounds);
else
poly=clipSide(poly,j,clipBounds);
}
if (isClosed)
{
if (poly.size() > 0)
{
poly.add(poly.get(0));
}
}
else
{
switch (addedLinePoints)
{
case 0: //no points were added, do nothing
break;
case 1: //point was added to the front to make algorithm work, remove segment
if (poly.size() > 0) {
poly.remove(0);
}
if (poly.size() > 0) {
poly.remove(0);
}
break;
case 2: //point was added to the end to make algorithm work, remove segment
if (poly.size() > 0) {
poly.remove(poly.size() - 1);
}
if (poly.size() > 0) {
poly.remove(poly.size() - 1);
}
break;
case 3: //point was added to the front and end to make algorithm work, remove segments
if (poly.size() > 0) {
poly.remove(0);
}
if (poly.size() > 0) {
poly.remove(0);
}
if (poly.size() > 0) {
poly.remove(poly.size() - 1);
}
if (poly.size() > 0) {
poly.remove(poly.size() - 1);
}
break;
}
}
if (isClosed == true)
{
if (poly.size() > 2)
{
//tg.Pixels = clsUtilityCPOF.Point2DtoPOINT2(poly);
tg.Pixels = clsUtilityCPOF.Point2DtoPOINT2Mapped(poly,hashMap);
}
else
{
//poly = buildBox(clipBounds);
//tg.Pixels = clsUtilityCPOF.Point2DtoPOINT2(poly);
tg.Pixels=new ArrayList();
}
}
else
{
if (poly.size() > 1)
{
tg.Pixels = clsUtilityCPOF.Point2DtoPOINT2Mapped(poly,hashMap);
}
else
{
tg.Pixels=new ArrayList();
}
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "ClipPolygon",
new RendererException("Failed inside ClipPolygon", exc));
}
return poly;
}
}
| core/JavaRendererServer/src/main/java/RenderMultipoints/clsClipQuad.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package RenderMultipoints;
import JavaTacticalRenderer.clsUtility;
import JavaTacticalRenderer.TGLight;
import java.util.ArrayList;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.Line2D;
import java.awt.Polygon;
import ArmyC2.C2SD.Utilities.ErrorLogger;
import ArmyC2.C2SD.Utilities.RendererException;
import JavaLineArray.POINT2;
import JavaLineArray.TacticalLines;
import JavaLineArray.Shape2;
import JavaLineArray.lineutility;
import java.util.HashMap;
import java.util.Map;
/**
* Class to clip polygons
* @author Michael Deutch
*/
public class clsClipQuad {
private static String _className = "clsClipQuad";
/**
* Use the new version which takes an array for polygon clip bounds instead of rectangle
* @param polygon
* @param clipBounds
* @return
*/
private static int AddBoundaryPointsForLines(ArrayList<Point2D> polygon,
ArrayList<Point2D> clipBounds)
{
int result=0;
try
{
Point2D pt02d=polygon.get(0);
Point2D ptLast2d=polygon.get((polygon.size()-1));
POINT2 pt0=new POINT2(pt02d.getX(),pt02d.getY());
POINT2 ptLast=new POINT2(ptLast2d.getX(),ptLast2d.getY());
Point2D nearestPt=new Point2D.Double();
Polygon clipArray=new Polygon();
int j=0;
double minDist=Double.MAX_VALUE;
double dist=0;
POINT2 sidePt=new POINT2();
Boolean addToFront = false, addToEnd = false;
for(j=0;j<clipBounds.size();j++)
{
clipArray.addPoint((int)clipBounds.get(j).getX(), (int)clipBounds.get(j).getY());
}
double totalX=0,totalY=0;
int counter=0;
for(j=0;j<clipBounds.size()-1;j++)
{
totalX+=clipBounds.get(j).getX();
totalY+=clipBounds.get(j).getY();
counter++;
}
//if clipBounds is not closed add the jth point
if( clipBounds.get(0).getX()!=clipBounds.get(j).getX() ||
clipBounds.get(0).getY()!=clipBounds.get(j).getY() )
{
totalX+=clipBounds.get(j).getX();
totalY+=clipBounds.get(j).getY();
counter++;
}
double avgX=totalX/counter;
double avgY=totalY/counter;
POINT2 ptCenter=new POINT2(avgX,avgY);
POINT2 ptNear=null;
//first point outside the clip bounds
if(clipArray.contains(pt02d)==false)
{
//add nearest segment midpoint to the front
for(j=0;j<clipBounds.size();j++)
{
sidePt.x=clipBounds.get(j).getX();
sidePt.y=clipBounds.get(j).getY();
dist=lineutility.CalcDistanceDouble(pt0, sidePt);
if(dist<minDist)
{
minDist=dist;
//minDistIndex=j;
nearestPt.setLocation(sidePt.x,sidePt.y);
}
}
//move nearestPt in a bit to not get clipped
ptNear=new POINT2(nearestPt.getX(),nearestPt.getY());
ptNear=lineutility.ExtendAlongLineDouble(ptNear, ptCenter, 2);
nearestPt.setLocation(ptNear.x, ptNear.y);
polygon.add(0, nearestPt);
addToFront=true;
}
//re-initialize variables
nearestPt=new Point2D.Double();
minDist=Double.MAX_VALUE;
//last point outside the clip bounds
if(clipArray.contains(ptLast2d)==false)
{
//add nearest segment midpoint to the front
for(j=0;j<clipBounds.size();j++)
{
sidePt.x=clipBounds.get(j).getX();
sidePt.y=clipBounds.get(j).getY();
dist=lineutility.CalcDistanceDouble(ptLast, sidePt);
if(dist<minDist)
{
minDist=dist;
//minDistIndex=j;
nearestPt.setLocation(sidePt.x,sidePt.y);
}
}
//move nearestPt in a bit to not get clipped
ptNear=new POINT2(nearestPt.getX(),nearestPt.getY());
ptNear=lineutility.ExtendAlongLineDouble(ptNear, ptCenter, 2);
nearestPt.setLocation(ptNear.x, ptNear.y);
polygon.add(nearestPt);
addToEnd=true;
}
if (addToFront == false && addToEnd == false) {
result = 0;
}
else if (addToFront == true && addToEnd == false) {
result = 1;
}
else if (addToFront == false && addToEnd == true) {
result = 2;
}
else if (addToFront == true && addToEnd == true) {
result = 3;
}
}
catch (Exception exc)
{
ErrorLogger.LogException(_className, "AddBoundaryPointsForLines",
new RendererException("Failed inside AddBoundaryPointsForLines", exc));
}
return result;
}
/**
* @deprecated
* @param polygon
* @param clipBounds
* @return
*/
private static int AddBoundaryPointsForLines(ArrayList<Point2D> polygon,
Rectangle2D clipBounds) {
int result = 0;
try {
double ulx = 0, uly = 0, lrx = 0, lry = 0;
ulx = clipBounds.getMinX();
uly = clipBounds.getMinY();
lrx = clipBounds.getMaxX();
lry = clipBounds.getMaxY();
//move these inside by 10 pixels so the algoithm will treat them as inside points
Point2D ul = new Point2D.Double(ulx + 10, uly + 10);
Point2D lr = new Point2D.Double(lrx - 10, lry - 10);
Point2D pt0 = polygon.get(0);
Point2D ptn = polygon.get(polygon.size() - 1);
Boolean addToFront = false, addToEnd = false;
//add a point to the begining of the array
if (pt0.getY() < uly) //above the top clip
{
polygon.add(0, ul);
addToFront = true;
} else if (pt0.getX() < ulx) //outside the left clip
{
polygon.add(0, ul);
addToFront = true;
} else if (pt0.getX() > lrx) //outside the right clip
{
polygon.add(0, lr);
addToFront = true;
} else if (pt0.getY() > lry) //below the bottom clip
{
polygon.add(0, lr);
addToFront = true;
}
//add a point to the end of the array
if (ptn.getY() < uly) //above the top clip
{
polygon.add(ul);
addToEnd = true;
} else if (ptn.getX() < ulx) //outside the left clip
{
polygon.add(ul);
addToEnd = true;
} else if (ptn.getX() > lrx) //outside the right clip
{
polygon.add(lr);
addToEnd = true;
} else if (ptn.getY() > lry) //below the bottom clip
{
polygon.add(lr);
addToEnd = true;
}
if (addToFront == false && addToEnd == false) {
result = 0;
}
if (addToFront == true && addToEnd == false) {
result = 1;
}
if (addToFront == false && addToEnd == true) {
result = 2;
}
if (addToFront == true && addToEnd == true) {
result = 3;
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "AddBoundaryPointsForLines",
new RendererException("Failed inside AddBoundaryPointsForLines", exc));
}
return result;
}
private static Point2D CalcTrueIntersectDouble(double m1,
double b1,
double m2,
double b2,
int bolVertical1,
int bolVertical2,
double X1, //x intercept if line1 is vertical
double X2)
{
//POINT2 ptIntersect=new POINT2();
Point2D ptIntersect=new Point2D.Double(X1,X2);
try
{
//declarations
double x=0,y=0;
//end declarations
//initialize ptIntersect
//ptIntersect.x=X1;
//ptIntersect.y=X2;
if(bolVertical1==0 && bolVertical2==0) //both lines vertical
return ptIntersect;
//the following 3 if blocks are the only ways to get an intersection
if(bolVertical1==0 && bolVertical2==1) //line1 vertical, line2 not
{
//ptIntersect.x=X1;
//ptIntersect.y=m2*X1+b2;
ptIntersect.setLocation(X1, m2*X1+b2);
return ptIntersect;
}
if(bolVertical1==1 && bolVertical2==0) //line2 vertical, line1 not
{
//ptIntersect.x=X2;
//ptIntersect.y=m1*X2+b1;
ptIntersect.setLocation(X2, m1*X2+b1);
return ptIntersect;
}
//if either of the lines is vertical function has already returned
//so both m1 and m2 should be valid
//should always be using this ocase because the lines are neither vertical
//or horizontal and are perpendicular
if(m1 != m2)
{
x=(b2-b1)/(m1-m2); //cannot blow up
y=(m1*x+b1);
//ptIntersect.x=x;
//ptIntersect.y=y;
ptIntersect.setLocation(x, y);
return ptIntersect;
}
}
catch(Exception exc)
{
ErrorLogger.LogException(_className ,"CalcTrueIntersectDouble",
new RendererException("Failed inside CalcTrueIntersectDouble", exc));
}
return ptIntersect;
}
/**
* Gets theoretical intersection of an edge with the line connecting previous and current points.
* @param pt0
* @param pt1
* @param currentEdge the current edge of the clip area, assumed to not be vertical
* @return
*/
private static Point2D intersectPoint2(Point2D previous,
Point2D current,
Line2D currentEdge)
{
Point2D ptIntersect=null;
try
{
Point2D ll=currentEdge.getP1();
Point2D ul=currentEdge.getP2();
//no vertical client segments
if(current.getX()==previous.getX())
current.setLocation(current.getX()+1, current.getY());
double m1=( ul.getY()-ll.getY() )/( ul.getX()-ll.getX() );
double m2=( current.getY()-previous.getY() )/( current.getX()-previous.getX() );
double b1=ul.getY()-m1*ul.getX();
double b2=current.getY()-m2*current.getX();
ptIntersect=CalcTrueIntersectDouble(m1,b1,m2,b2,1,1,0,0);
}
catch (Exception exc) {
ErrorLogger.LogException(_className, "intersectPoint2",
new RendererException("Failed inside intersectPoint2", exc));
}
return ptIntersect;
}
/**
* clips array of pts against a side of the clip bounds polygon
* assumes clipBounds has no vertical or horizontal segments
* @param pts array of points to clip against the clip bounds
* @param index starting index of clipBounds for the side to clip against
* @param clipBounds a quadrilateral or a polygon array that is the clipping area
* @return the clipped array of points
*/
private static ArrayList<Point2D> clipSide(ArrayList<Point2D> pts,
int index,
ArrayList<Point2D> clipBounds)
{
ArrayList<Point2D> ptsResult=null;
try
{
Point2D pt1=new Point2D.Double(clipBounds.get(index).getX(),clipBounds.get(index).getY());//first point of clip side
Point2D pt2=new Point2D.Double(clipBounds.get(index+1).getX(),clipBounds.get(index+1).getY());//last point of clip side
Point2D clipBoundsPoint=null;//some point in the clipbounds not on the side
Point2D ptClipBoundsIntersect=null;//some point in the clipbounds not on the side
double m1=0,m2=0,b1=0,b2=0,b3=0,b4=0;
Point2D ptPreviousIntersect=null,ptCurrentIntersect=null;
int j = 0,clipBoundsQuadrant=-1,previousQuadrant=-1,currentQuadrant=-1; //quadrants relative to side
Point2D current = null, previous = null;
Point2D intersectPt = null;
Line2D edge;
ptsResult=new ArrayList();
//set some point in the array which is not in the side
//this point will be used to define which side of the clipping side the rest of the clipbounds points are on
//then it can be used to figure out whether a given point is to be clipped
//for this scheme to work it needs to be a convex clipping area
if(index==0)
{
clipBoundsPoint=new Point2D.Double(clipBounds.get(index+2).getX(),clipBounds.get(index+2).getY());
}
else if(index>1)
{
//clipBoundsPoint=clipBounds.get(index-2);
clipBoundsPoint=new Point2D.Double(clipBounds.get(index-2).getX(),clipBounds.get(index-2).getY());
}
else if(index==1)
{
//clipBoundsPoint=clipBounds.get(0);
clipBoundsPoint=new Point2D.Double(clipBounds.get(0).getX(),clipBounds.get(0).getY());
}
//no vertical segments
if(pt2.getX()==pt1.getX())
pt2.setLocation(pt2.getX()+1, pt2.getY());
if(pt2.getY()==pt1.getY())
pt2.setLocation(pt2.getX(), pt2.getY()+1);
for (j = 0; j < pts.size(); j++)
{
current = pts.get(j);
if (j == 0)
{
previous = pts.get(pts.size() - 1);
}
else
{
previous = pts.get(j - 1);
}
m1=(pt2.getY()-pt1.getY())/(pt2.getX()-pt1.getX());
m2=-1d/m1; //the slope of the line perpendicular to m1,b1
b1=pt2.getY()-m1*pt2.getX();
b2=previous.getY()-m2*previous.getX();
b3=current.getY()-m2*current.getX();
b4=clipBoundsPoint.getY()-m2*clipBoundsPoint.getX();
ptPreviousIntersect=CalcTrueIntersectDouble(m1,b1,m2,b2,1,1,0,0);
ptCurrentIntersect=CalcTrueIntersectDouble(m1,b1,m2,b3,1,1,0,0);
ptClipBoundsIntersect=CalcTrueIntersectDouble(m1,b1,m2,b4,1,1,0,0);
clipBoundsQuadrant=lineutility.GetQuadrantDouble(clipBoundsPoint.getX(), clipBoundsPoint.getY(), ptClipBoundsIntersect.getX(), ptClipBoundsIntersect.getY());
previousQuadrant=lineutility.GetQuadrantDouble(previous.getX(), previous.getY(), ptPreviousIntersect.getX(), ptPreviousIntersect.getY());
currentQuadrant=lineutility.GetQuadrantDouble(current.getX(), current.getY(), ptCurrentIntersect.getX(), ptCurrentIntersect.getY());
//case: both inside
if(previousQuadrant==clipBoundsQuadrant && currentQuadrant==clipBoundsQuadrant)
ptsResult.add(current);
else if(previousQuadrant==clipBoundsQuadrant && currentQuadrant!=clipBoundsQuadrant)//previous inside, current outside
{
edge = new Line2D.Double(pt1, pt2);
intersectPt = intersectPoint2(previous, current, edge);
if (intersectPt != null)
{
ptsResult.add(intersectPt);
}
}
else if(previousQuadrant!=clipBoundsQuadrant && currentQuadrant==clipBoundsQuadrant)//current inside, previous outside
{
edge = new Line2D.Double(pt1, pt2);
intersectPt = intersectPoint2(previous, current, edge);
if (intersectPt != null)
{
ptsResult.add(intersectPt);
}
ptsResult.add(current);
}
else if(previousQuadrant!=clipBoundsQuadrant && currentQuadrant!=clipBoundsQuadrant)
continue;
}//end for j=0 to pts.size()-1
}//end try
catch (Exception exc) {
ErrorLogger.LogException(_className, "clipSide",
new RendererException("Failed inside clipSide", exc));
}
return ptsResult;
}
/**
* for pre-clipped lines which also require fill but need the processed points
* to create the fill. This function is called after the clip, so the fill
* does not get clipped.
* @param tg
* @param shapes
*/
protected static void addAbatisFill(TGLight tg,
ArrayList<Shape2>shapes)
{
try
{
if(tg.Pixels==null ||
tg.Pixels.size()<2 ||
tg.get_FillColor()==null ||
tg.get_FillColor().getAlpha()<2 ||
shapes==null)
return;
int j=0,n=tg.Pixels.size();
Shape2 shape=null;
TGLight tg2=null;
switch(tg.get_LineType())
{
case TacticalLines.MSDZ:
double dist0=0,dist1=0,dist2=0;
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.setFillColor(tg.get_FillColor());
if(tg.Pixels != null & tg.Pixels.size()>=300)
{
dist0=Math.abs(tg.Pixels.get(0).x-tg.Pixels.get(50).x);
dist1=Math.abs(tg.Pixels.get(100).x-tg.Pixels.get(150).x);
dist2=Math.abs(tg.Pixels.get(200).x-tg.Pixels.get(250).x);
int start=-1,end=-1;
if(dist0>=dist1 && dist0>=dist2)
{
start=0;
end=99;
}
else if(dist1>=dist0 && dist1>=dist2)
{
start=100;
end=199;
}
else
{
start=200;
end=299;
}
shape.moveTo(tg.Pixels.get(start));
for(j=start;j<=end;j++)
shape.lineTo(tg.Pixels.get(j));
//shapes.add(0,shape);
}
break;
case TacticalLines.ABATIS:
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.setFillColor(tg.get_FillColor());
tg2=new TGLight();
tg2.set_LineType(TacticalLines.GENERAL);
tg2.Pixels=new ArrayList();
if(tg.Pixels != null && tg.Pixels.size()>2)
{
tg2.Pixels.add(tg.Pixels.get(n-3));
tg2.Pixels.add(tg.Pixels.get(n-2));
tg2.Pixels.add(tg.Pixels.get(n-1));
tg2.Pixels.add(tg.Pixels.get(n-3));
shape.moveTo(tg2.Pixels.get(0));
for(j=1;j<tg2.Pixels.size();j++)
shape.lineTo(tg2.Pixels.get(j));
//shapes.add(shape);
}
break;
default:
return;
}//end switch
if(shapes != null)
shapes.add(0,shape);
}
catch (Exception exc) {
ErrorLogger.LogException(_className, "addAbatisFill",
new RendererException("Failed inside addAbatisFill", exc));
}
return;
}
/**
* for lines with glyphs the fill must be handled (clipped) as a separate shape.
* this function needs to be called before the clipping is done to the line
* @param tg
* @param shapes
*/
protected static ArrayList<Shape2> LinesWithFill(TGLight tg,
ArrayList<Point2D> clipBounds)
{
ArrayList<Shape2>shapes=null;
try
{
if(tg.get_FillColor()==null || tg.get_FillColor().getAlpha()<=1 ||
tg.Pixels==null || tg.Pixels.isEmpty())
return shapes;
switch(tg.get_LineType())
{
case TacticalLines.ABATIS:
case TacticalLines.SPT:
case TacticalLines.MAIN:
case TacticalLines.AAAAA:
case TacticalLines.AIRAOA:
case TacticalLines.AXAD:
case TacticalLines.AAFNT:
case TacticalLines.CATK:
case TacticalLines.CATKBYFIRE:
case TacticalLines.CORDONSEARCH:
case TacticalLines.CORDONKNOCK:
case TacticalLines.SECURE:
case TacticalLines.OCCUPY:
case TacticalLines.RETAIN:
case TacticalLines.ISOLATE:
case TacticalLines.CONVOY:
case TacticalLines.HCONVOY:
return shapes;
case TacticalLines.PAA_RECTANGULAR:
return null;
case TacticalLines.OBSFAREA:
case TacticalLines.OBSAREA:
case TacticalLines.STRONG:
case TacticalLines.ZONE:
case TacticalLines.FORT:
case TacticalLines.ENCIRCLE:
case TacticalLines.BELT:
//case TacticalLines.BELT1:
case TacticalLines.DMA:
case TacticalLines.DMAF:
case TacticalLines.ATDITCHC:
case TacticalLines.ATDITCHM:
return fillDMA(tg,clipBounds);
default:
break;
}
if(clsUtility.LinesWithFill(tg.get_LineType())==false)
return shapes;
shapes=new ArrayList();
//undo any fillcolor that might have been set for the existing shape
//because we are divorcing fill from the line
Shape2 shape=null;
//create a generic area tg from the pixels and clip it
TGLight tg2=new TGLight();
tg2.set_LineType(TacticalLines.GENERAL);
tg2.Pixels=new ArrayList();
tg2.Pixels.addAll(tg.Pixels);
closeAreaTG(tg2);
//tg2.Pixels.add(tg.Pixels.get(0));
if(clipBounds != null)
ClipPolygon(tg2,clipBounds);
if(tg2.Pixels==null || tg2.Pixels.isEmpty())
return null;
int j=0;
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.setFillColor(tg.get_FillColor());
shape.moveTo(tg2.Pixels.get(0));
for(j=1;j<tg2.Pixels.size();j++)
shape.lineTo(tg2.Pixels.get(j));
if(tg.get_FillColor() != null || tg.get_FillColor().getAlpha()>1)
{
shapes.add(shape);
}
else
return null;
}
catch (Exception exc) {
ErrorLogger.LogException(_className, "LinesWithFill",
new RendererException("Failed inside LinesWithFill", exc));
}
return shapes;
}
/**
* closes an area
* @param tg
*/
private static void closeAreaTG(TGLight tg)
{
try
{
if(tg.Pixels==null || tg.Pixels.isEmpty())
return;
POINT2 pt0=tg.Pixels.get(0);
POINT2 ptn=tg.Pixels.get(tg.Pixels.size()-1);
if(pt0.x != ptn.x || pt0.y != ptn.y)
tg.Pixels.add(pt0);
}
catch (Exception exc) {
ErrorLogger.LogException(_className, "closeAreaTG",
new RendererException("Failed inside closeAreaTG", exc));
}
return;
}
/**
* DMA, DMAF fill must be handled separately because of the feint
* @param tg
* @param clipBounds
* @return
*/
protected static ArrayList<Shape2> fillDMA(TGLight tg,
ArrayList<Point2D> clipBounds)
{
ArrayList<Shape2>shapes=new ArrayList();
try
{
switch(tg.get_LineType())
{
case TacticalLines.OBSFAREA:
case TacticalLines.OBSAREA:
case TacticalLines.STRONG:
case TacticalLines.ZONE:
case TacticalLines.FORT:
case TacticalLines.ENCIRCLE:
case TacticalLines.BELT1:
case TacticalLines.BELT:
case TacticalLines.DMA:
case TacticalLines.DMAF:
case TacticalLines.ATDITCHC:
case TacticalLines.ATDITCHM:
break;
default:
return shapes;
}
Shape2 shape=null;
//create a generic area tg from the pixels and clip it
int j=0;
TGLight tg2=new TGLight();
tg2.set_LineType(TacticalLines.GENERAL);
tg2.Pixels=new ArrayList();
//to get the original pixels size
int n=0;
// if(tg.LatLongs != null)
// n=tg.LatLongs.size();
// else
n=tg.Pixels.size();
for(j=0;j<n;j++)
tg2.Pixels.add(tg.Pixels.get(j));
closeAreaTG(tg2);
if(clipBounds != null)
ClipPolygon(tg2,clipBounds);
if(tg2.Pixels==null || tg2.Pixels.isEmpty())
return shapes;
shape=new Shape2(Shape2.SHAPE_TYPE_POLYLINE);
shape.setFillColor(tg.get_FillColor());
shape.moveTo(tg2.Pixels.get(0));
//original pixels do not include feint
for(j=1;j<tg2.Pixels.size();j++)
shape.lineTo(tg2.Pixels.get(j));
shapes.add(shape);
}
catch (Exception exc) {
ErrorLogger.LogException(_className, "fillDMA",
new RendererException("Failed inside fillDMA", exc));
}
return shapes;
}
private static Boolean isClosed(ArrayList<POINT2>pts)
{
boolean closed=false;
POINT2 pt0=pts.get(0);
POINT2 ptLast=pts.get(pts.size()-1);
if(pt0.x==ptLast.x && pt0.y==ptLast.y)
closed=true;
return closed;
}
/**
*
* @param tg
* @param clipBounds polygon representing clipping area
* @return
*/
protected static ArrayList<Point2D> ClipPolygon(TGLight tg,
ArrayList<Point2D> clipBounds) {
ArrayList<Point2D> poly = new ArrayList();
try
{
//diagnostic
//Boolean isClosed = clsUtility.isClosedPolygon(tg.get_LineType());
Boolean isClosed = isClosed(tg.Pixels);
//M. Deutch commented one line 12-27-12
clipBounds=clsUtilityGE.expandPolygon(clipBounds, 20);
ArrayList polygon = clsUtilityCPOF.POINT2toPoint2D(tg.Pixels);
int j=0;
Map<String,Object>hashMap=new HashMap<String,Object>();
//int hashCode=0;
for(j=0;j<polygon.size();j++)
hashMap.put(Integer.toString(j), polygon.get(j));
//close the clipbounds if necessary
Point2D clipBoundsPtStart=clipBounds.get(0);
Point2D clipBoundsPtEnd=clipBounds.get(clipBounds.size()-1);
if(clipBoundsPtStart.getX() != clipBoundsPtEnd.getX() ||
clipBoundsPtStart.getY() != clipBoundsPtEnd.getY())
clipBounds.add(clipBoundsPtStart);
int addedLinePoints = 0;
if (isClosed)
polygon.remove(polygon.size() - 1);
else
{
//for tactical lines it always seems to work if the 0th and last points are inside the area
//add points on the edge as needed to make that happen
//Rectangle2D clipBounds2=RenderMultipoints.clsUtility.getMBR(clipBounds);
//clipBounds2.setRect(clipBounds2.getMinX()-20, clipBounds2.getMinY()-20, clipBounds2.getWidth()+40, clipBounds2.getHeight()+40);;
addedLinePoints = AddBoundaryPointsForLines(polygon, clipBounds);
}
for(j=0;j<clipBounds.size()-1;j++)
{
if(j==0)
poly=clipSide(polygon,j,clipBounds);
else
poly=clipSide(poly,j,clipBounds);
}
if (isClosed)
{
if (poly.size() > 0)
{
poly.add(poly.get(0));
}
}
else
{
switch (addedLinePoints)
{
case 0: //no points were added, do nothing
break;
case 1: //point was added to the front to make algorithm work, remove segment
if (poly.size() > 0) {
poly.remove(0);
}
if (poly.size() > 0) {
poly.remove(0);
}
break;
case 2: //point was added to the end to make algorithm work, remove segment
if (poly.size() > 0) {
poly.remove(poly.size() - 1);
}
if (poly.size() > 0) {
poly.remove(poly.size() - 1);
}
break;
case 3: //point was added to the front and end to make algorithm work, remove segments
if (poly.size() > 0) {
poly.remove(0);
}
if (poly.size() > 0) {
poly.remove(0);
}
if (poly.size() > 0) {
poly.remove(poly.size() - 1);
}
if (poly.size() > 0) {
poly.remove(poly.size() - 1);
}
break;
}
}
if (isClosed == true)
{
if (poly.size() > 2)
{
//tg.Pixels = clsUtilityCPOF.Point2DtoPOINT2(poly);
tg.Pixels = clsUtilityCPOF.Point2DtoPOINT2Mapped(poly,hashMap);
}
else
{
//poly = buildBox(clipBounds);
//tg.Pixels = clsUtilityCPOF.Point2DtoPOINT2(poly);
tg.Pixels=new ArrayList();
}
}
else
{
if (poly.size() > 1)
{
tg.Pixels = clsUtilityCPOF.Point2DtoPOINT2Mapped(poly,hashMap);
}
else
{
tg.Pixels=new ArrayList();
}
}
} catch (Exception exc) {
ErrorLogger.LogException(_className, "ClipPolygon",
new RendererException("Failed inside ClipPolygon", exc));
}
return poly;
}
}
| Fix error in the clipping function if the pixels array is empty.
| core/JavaRendererServer/src/main/java/RenderMultipoints/clsClipQuad.java | Fix error in the clipping function if the pixels array is empty. |
|
Java | apache-2.0 | 06feabe9e3e133f71dcbb9e0cc5b3233cc21a8e2 | 0 | a1vanov/ignite,chandresh-pancholi/ignite,chandresh-pancholi/ignite,ptupitsyn/ignite,NSAmelchev/ignite,xtern/ignite,daradurvs/ignite,WilliamDo/ignite,SomeFire/ignite,NSAmelchev/ignite,pperalta/ignite,irudyak/ignite,ntikhonov/ignite,samaitra/ignite,BiryukovVA/ignite,wmz7year/ignite,SharplEr/ignite,mcherkasov/ignite,WilliamDo/ignite,BiryukovVA/ignite,a1vanov/ignite,ascherbakoff/ignite,WilliamDo/ignite,ptupitsyn/ignite,WilliamDo/ignite,shroman/ignite,apache/ignite,voipp/ignite,daradurvs/ignite,SomeFire/ignite,SomeFire/ignite,dream-x/ignite,andrey-kuznetsov/ignite,vadopolski/ignite,apache/ignite,vladisav/ignite,endian675/ignite,xtern/ignite,wmz7year/ignite,samaitra/ignite,endian675/ignite,WilliamDo/ignite,alexzaitzev/ignite,ascherbakoff/ignite,ascherbakoff/ignite,rfqu/ignite,andrey-kuznetsov/ignite,vadopolski/ignite,daradurvs/ignite,vadopolski/ignite,vladisav/ignite,pperalta/ignite,apache/ignite,ptupitsyn/ignite,mcherkasov/ignite,daradurvs/ignite,nizhikov/ignite,ntikhonov/ignite,samaitra/ignite,samaitra/ignite,BiryukovVA/ignite,sk0x50/ignite,ntikhonov/ignite,sk0x50/ignite,SharplEr/ignite,nizhikov/ignite,nizhikov/ignite,ilantukh/ignite,ilantukh/ignite,SomeFire/ignite,a1vanov/ignite,alexzaitzev/ignite,ilantukh/ignite,dream-x/ignite,chandresh-pancholi/ignite,ilantukh/ignite,amirakhmedov/ignite,amirakhmedov/ignite,voipp/ignite,chandresh-pancholi/ignite,sk0x50/ignite,pperalta/ignite,irudyak/ignite,nizhikov/ignite,nizhikov/ignite,WilliamDo/ignite,shroman/ignite,shroman/ignite,StalkXT/ignite,psadusumilli/ignite,rfqu/ignite,StalkXT/ignite,mcherkasov/ignite,shroman/ignite,dream-x/ignite,nizhikov/ignite,BiryukovVA/ignite,wmz7year/ignite,alexzaitzev/ignite,chandresh-pancholi/ignite,apache/ignite,SharplEr/ignite,andrey-kuznetsov/ignite,chandresh-pancholi/ignite,psadusumilli/ignite,samaitra/ignite,nizhikov/ignite,wmz7year/ignite,daradurvs/ignite,daradurvs/ignite,alexzaitzev/ignite,chandresh-pancholi/ignite,mcherkasov/ignite,vladisav/ignite,amirakhmedov/ignite,samaitra/ignite,irudyak/ignite,rfqu/ignite,SharplEr/ignite,shroman/ignite,voipp/ignite,NSAmelchev/ignite,rfqu/ignite,andrey-kuznetsov/ignite,sk0x50/ignite,SomeFire/ignite,ptupitsyn/ignite,andrey-kuznetsov/ignite,vadopolski/ignite,a1vanov/ignite,ntikhonov/ignite,sk0x50/ignite,daradurvs/ignite,vadopolski/ignite,nizhikov/ignite,samaitra/ignite,vladisav/ignite,endian675/ignite,rfqu/ignite,StalkXT/ignite,andrey-kuznetsov/ignite,voipp/ignite,SharplEr/ignite,a1vanov/ignite,StalkXT/ignite,voipp/ignite,BiryukovVA/ignite,ptupitsyn/ignite,SharplEr/ignite,a1vanov/ignite,amirakhmedov/ignite,shroman/ignite,irudyak/ignite,ptupitsyn/ignite,rfqu/ignite,pperalta/ignite,apache/ignite,ptupitsyn/ignite,mcherkasov/ignite,StalkXT/ignite,apache/ignite,mcherkasov/ignite,psadusumilli/ignite,dream-x/ignite,alexzaitzev/ignite,xtern/ignite,SomeFire/ignite,shroman/ignite,SomeFire/ignite,chandresh-pancholi/ignite,rfqu/ignite,ascherbakoff/ignite,wmz7year/ignite,ptupitsyn/ignite,dream-x/ignite,sk0x50/ignite,ntikhonov/ignite,BiryukovVA/ignite,vladisav/ignite,psadusumilli/ignite,pperalta/ignite,WilliamDo/ignite,wmz7year/ignite,irudyak/ignite,amirakhmedov/ignite,ascherbakoff/ignite,BiryukovVA/ignite,psadusumilli/ignite,xtern/ignite,voipp/ignite,ascherbakoff/ignite,ilantukh/ignite,ptupitsyn/ignite,andrey-kuznetsov/ignite,pperalta/ignite,voipp/ignite,rfqu/ignite,vadopolski/ignite,vadopolski/ignite,pperalta/ignite,amirakhmedov/ignite,SharplEr/ignite,sk0x50/ignite,amirakhmedov/ignite,endian675/ignite,daradurvs/ignite,StalkXT/ignite,endian675/ignite,irudyak/ignite,vladisav/ignite,apache/ignite,BiryukovVA/ignite,psadusumilli/ignite,xtern/ignite,shroman/ignite,sk0x50/ignite,NSAmelchev/ignite,ilantukh/ignite,SomeFire/ignite,samaitra/ignite,endian675/ignite,SharplEr/ignite,daradurvs/ignite,dream-x/ignite,WilliamDo/ignite,ntikhonov/ignite,SomeFire/ignite,voipp/ignite,samaitra/ignite,voipp/ignite,ascherbakoff/ignite,alexzaitzev/ignite,sk0x50/ignite,amirakhmedov/ignite,daradurvs/ignite,dream-x/ignite,xtern/ignite,NSAmelchev/ignite,wmz7year/ignite,a1vanov/ignite,alexzaitzev/ignite,irudyak/ignite,endian675/ignite,vladisav/ignite,StalkXT/ignite,pperalta/ignite,irudyak/ignite,psadusumilli/ignite,shroman/ignite,SharplEr/ignite,amirakhmedov/ignite,ilantukh/ignite,ascherbakoff/ignite,BiryukovVA/ignite,samaitra/ignite,xtern/ignite,psadusumilli/ignite,andrey-kuznetsov/ignite,apache/ignite,ilantukh/ignite,xtern/ignite,ptupitsyn/ignite,NSAmelchev/ignite,apache/ignite,NSAmelchev/ignite,andrey-kuznetsov/ignite,wmz7year/ignite,ilantukh/ignite,alexzaitzev/ignite,StalkXT/ignite,vadopolski/ignite,mcherkasov/ignite,dream-x/ignite,ntikhonov/ignite,NSAmelchev/ignite,xtern/ignite,shroman/ignite,StalkXT/ignite,nizhikov/ignite,endian675/ignite,mcherkasov/ignite,ascherbakoff/ignite,vladisav/ignite,ntikhonov/ignite,BiryukovVA/ignite,andrey-kuznetsov/ignite,NSAmelchev/ignite,SomeFire/ignite,ilantukh/ignite,alexzaitzev/ignite,irudyak/ignite,chandresh-pancholi/ignite,a1vanov/ignite | /*
* 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.ignite.internal.processors.cache.database.tree;
import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.IgniteInterruptedCheckedException;
import org.apache.ignite.internal.pagemem.FullPageId;
import org.apache.ignite.internal.pagemem.Page;
import org.apache.ignite.internal.pagemem.PageIdAllocator;
import org.apache.ignite.internal.pagemem.PageMemory;
import org.apache.ignite.internal.processors.cache.database.tree.io.BPlusIO;
import org.apache.ignite.internal.processors.cache.database.tree.io.BPlusInnerIO;
import org.apache.ignite.internal.processors.cache.database.tree.io.BPlusLeafIO;
import org.apache.ignite.internal.processors.cache.database.tree.io.BPlusMetaIO;
import org.apache.ignite.internal.processors.cache.database.tree.io.PageIO;
import org.apache.ignite.internal.processors.cache.database.tree.reuse.ReuseBag;
import org.apache.ignite.internal.processors.cache.database.tree.reuse.ReuseList;
import org.apache.ignite.internal.processors.cache.database.tree.util.PageHandler;
import org.apache.ignite.internal.util.lang.GridCursor;
import org.apache.ignite.internal.util.lang.GridTreePrinter;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import static org.apache.ignite.internal.processors.cache.database.tree.util.PageHandler.readPage;
import static org.apache.ignite.internal.processors.cache.database.tree.util.PageHandler.writePage;
/**
* Abstract B+Tree.
*/
public abstract class BPlusTree<L, T extends L> {
/** */
private static final byte FALSE = 0;
/** */
private static final byte TRUE = 1;
/** */
private static final byte READY = 2;
/** */
private static final byte DONE = 3;
/** */
protected final int cacheId;
/** */
private final PageMemory pageMem;
/** */
private final ReuseList reuseList;
/** */
private final float minFill;
/** */
private final float maxFill;
/** */
private final long metaPageId;
/** */
private final AtomicLong globalRmvId = new AtomicLong(U.currentTimeMillis() * 1000_000); // TODO init from WAL?
/** */
private final GridTreePrinter<Long> treePrinter = new GridTreePrinter<Long>() {
/** */
private boolean keys = true;
@Override protected List<Long> getChildren(Long pageId) {
if (pageId == null || pageId == 0L)
return null;
try (Page page = page(pageId)) {
ByteBuffer buf = page.getForRead();
try {
BPlusIO io = io(buf);
if (io.isLeaf())
return null;
List<Long> res;
int cnt = io.getCount(buf);
assert cnt >= 0: cnt;
if (cnt > 0) {
res = new ArrayList<>(cnt + 1);
for (int i = 0; i < cnt; i++)
res.add(inner(io).getLeft(buf, i));
res.add(inner(io).getRight(buf, cnt - 1));
}
else {
long left = inner(io).getLeft(buf, 0);
res = left == 0 ? Collections.<Long>emptyList() : Collections.singletonList(left);
}
return res;
}
finally {
page.releaseRead();
}
}
catch (IgniteCheckedException e) {
throw new IllegalStateException(e);
}
}
@Override protected String formatTreeNode(Long pageId) {
if (pageId == null)
return ">NPE<";
if (pageId == 0L)
return "<Zero>";
try (Page page = page(pageId)) {
ByteBuffer buf = page.getForRead();
try {
BPlusIO<L> io = io(buf);
return printPage(io, buf, keys);
}
finally {
page.releaseRead();
}
}
catch (IgniteCheckedException e) {
throw new IllegalStateException(e);
}
}
};
/** */
private final PageHandler<Get> search = new GetPageHandler<Get>() {
@Override public int run0(Page page, ByteBuffer buf, BPlusIO<L> io, Get g, int lvl)
throws IgniteCheckedException {
boolean needBackIfRouting = g.backId != 0;
g.backId = 0; // Usually we'll go left down and don't need it.
int cnt = io.getCount(buf);
int idx = findInsertionPoint(io, buf, cnt, g.row);
boolean found = idx >= 0;
if (found) { // Found exact match.
if (g.found(io, buf, idx, lvl))
return Get.FOUND;
assert !io.isLeaf();
// Else we need to reach leaf page, go left down.
}
else {
idx = -idx - 1;
// If we are on the right edge, then check for expected forward page and retry of it does match.
// It means that concurrent split happened. This invariant is referred as `triangle`.
if (idx == cnt && io.getForward(buf) != g.fwdId)
return Get.RETRY;
if (g.notFound(io, buf, idx, lvl)) // No way down, stop here.
return Get.NOT_FOUND;
assert !io.isLeaf();
assert lvl > 0 : lvl;
}
// If idx == cnt then we go right down, else left down.
g.pageId = inner(io).getLeft(buf, idx);
// If we see the tree in consistent state, then our right down page must be forward for our left down page.
if (idx < cnt)
g.fwdId = inner(io).getRight(buf, idx);
else {
assert idx == cnt;
// Here child's forward is unknown to us (we either go right or it is an empty "routing" page),
// need to ask our forward about the child's forward (it must be leftmost child of our forward page).
// This is ok from the locking standpoint because we take all locks in the forward direction.
long fwdId = io.getForward(buf);
g.fwdId = fwdId == 0 ? 0 : getChild(fwdId, false);
if (cnt != 0) // It is not a routing page and we are going to the right, can get backId here.
g.backId = inner(io).getLeft(buf, cnt - 1);
else if (needBackIfRouting) {
// Can't get backId here because of possible deadlock and it is only needed for remove operation.
return Remove.GO_DOWN_X;
}
}
return Get.GO_DOWN;
}
};
/** */
private final PageHandler<Put> replace = new GetPageHandler<Put>() {
@Override public int run0(Page page, ByteBuffer buf, BPlusIO<L> io, Put p, int lvl)
throws IgniteCheckedException {
assert p.btmLvl == 0 : "split is impossible with replace";
int cnt = io.getCount(buf);
int idx = findInsertionPoint(io, buf, cnt, p.row);
if (idx < 0) { // Not found, split or merge happened.
long fwdId = io.getForward(buf);
assert fwdId != 0;
p.pageId = fwdId;
return Put.RETRY;
}
// Replace link at idx with new one.
// Need to read link here because `p.finish()` will clear row.
L newRow = p.row;
if (io.isLeaf()) { // Get old row in leaf page to reduce contention at upper level.
assert p.oldRow == null;
assert io.canGetRow();
p.oldRow = getRow(io, buf, idx);
p.finish();
// We can't erase data page here because it can be referred from other indexes.
}
io.store(buf, idx, newRow);
return Put.FOUND;
}
};
/** */
private final PageHandler<Put> insert = new GetPageHandler<Put>() {
@Override public int run0(Page page, ByteBuffer buf, BPlusIO<L> io, Put p, int lvl)
throws IgniteCheckedException {
assert p.btmLvl == lvl: "we must always insert at the bottom level: " + p.btmLvl + " " + lvl;
int cnt = io.getCount(buf);
int idx = findInsertionPoint(io, buf, cnt, p.row);
assert idx < 0: "Duplicate row in index.";
idx = -idx - 1;
// Possible split or merge.
if (idx == cnt && io.getForward(buf) != p.fwdId)
return Put.RETRY;
// Do insert.
L moveUpRow = insert(p.bag, p.meta, io, buf, p.row, idx, p.rightId, lvl);
// Check if split happened.
if (moveUpRow != null) {
p.btmLvl++; // Get high.
p.row = moveUpRow;
// Here `forward` can't be concurrently removed because we keep `tail` which is the only
// page who knows about the `forward` page, because it was just produced by split.
p.rightId = io.getForward(buf);
p.tail(page);
assert p.rightId != 0;
}
else
p.finish();
return Put.FOUND;
}
};
/** */
private final PageHandler<Remove> removeFromLeaf = new GetPageHandler<Remove>() {
@Override public int run0(Page leaf, ByteBuffer buf, BPlusIO<L> io, Remove r, int lvl)
throws IgniteCheckedException {
assert lvl == 0: lvl;
assert r.removed == null;
assert io.isLeaf();
assert io.canGetRow();
int cnt = io.getCount(buf);
int idx = findInsertionPoint(io, buf, cnt, r.row);
if (idx < 0) {
if (!r.ceil) // We've found exact match on search but now it's gone.
return Remove.RETRY;
idx = -idx - 1;
if (idx == cnt) // We can not remove ceiling row here.
return Remove.NOT_FOUND;
assert idx < cnt;
}
r.removed = getRow(io, buf, idx);
r.doRemove(io, buf, cnt, idx);
if (r.needReplaceInner == TRUE) {
// We increment remove ID in write lock on leaf page, thus it is guaranteed that
// any successor will get greater value than he had read at the beginning of the operation.
// Thus he is guaranteed to do a retry from root. Since inner replace takes locks on the whole branch
// and releases the locks only when the inner key is updated and the successor saw the updated removeId,
// then after retry from root, he will see updated inner key.
io.setRemoveId(buf, globalRmvId.incrementAndGet());
}
// We may need to replace inner key or want to merge this leaf with sibling after the remove -> keep lock.
if (r.needReplaceInner == TRUE ||
// We need to make sure that we have back or forward to be able to merge.
((r.fwdId != 0 || r.backId != 0) && mayMerge(cnt - 1, io.getMaxCount(buf)))) {
if (cnt == 1) // It was the last item.
r.needMergeEmptyBranch = TRUE;
// If we have backId then we've already locked back page, nothing to do here.
if (r.fwdId != 0 && r.backId == 0)
r.lockForward(0);
r.addTail(leaf, buf, io, 0, Tail.EXACT, -1);
}
return Remove.FOUND;
}
};
/** */
private final PageHandler<Remove> lockBackAndRemoveFromLeaf = new GetPageHandler<Remove>() {
@Override protected int run0(Page back, ByteBuffer buf, BPlusIO<L> io, Remove r, int lvl)
throws IgniteCheckedException {
// Check that we have consistent view of the world.
if (io.getForward(buf) != r.pageId)
return Remove.RETRY;
// Correct locking order: from back to forward.
int res = r.doRemoveFromLeaf();
// Keep locks on back and leaf pages for subsequent merges.
if (res == Remove.FOUND && r.tail != null)
r.addTail(back, buf, io, lvl, Tail.BACK, -1);
return res;
}
};
/** */
private final PageHandler<Remove> lockBackAndTail = new GetPageHandler<Remove>() {
@Override public int run0(Page back, ByteBuffer buf, BPlusIO<L> io, Remove r, int lvl)
throws IgniteCheckedException {
// Check that we have consistent view of the world.
if (io.getForward(buf) != r.pageId)
return Remove.RETRY;
// Correct locking order: from back to forward.
int res = r.doLockTail(lvl);
if (res == Remove.FOUND)
r.addTail(back, buf, io, lvl, Tail.BACK, -1);
return res;
}
};
/** */
private final PageHandler<Remove> lockTailForward = new GetPageHandler<Remove>() {
@Override protected int run0(Page page, ByteBuffer buf, BPlusIO<L> io, Remove r, int lvl)
throws IgniteCheckedException {
r.addTail(page, buf, io, lvl, Tail.FORWARD, -1);
return Remove.FOUND;
}
};
/** */
private final PageHandler<Remove> lockTail = new GetPageHandler<Remove>() {
@Override public int run0(Page page, ByteBuffer buf, BPlusIO<L> io, Remove r, int lvl)
throws IgniteCheckedException {
assert lvl > 0: lvl; // We are not at the bottom.
int cnt = io.getCount(buf);
int idx = findInsertionPoint(io, buf, cnt, r.row);
boolean found = idx >= 0;
if (found) {
if (io.canGetRow()) {
// We can not miss the inner value on down move because of `triangle` invariant, thus it must be TRUE.
assert r.needReplaceInner == TRUE : r.needReplaceInner;
assert idx <= Short.MAX_VALUE : idx;
r.innerIdx = (short)idx;
r.needReplaceInner = READY;
}
}
else {
idx = -idx - 1;
// Check that we have a correct view of the world.
if (idx == cnt && io.getForward(buf) != r.fwdId)
return Remove.RETRY;
}
// Check that we have a correct view of the world.
if (lvl != 0 && inner(io).getLeft(buf, idx) != r.getTail(lvl - 1).page.id()) {
assert !found;
return Remove.RETRY;
}
// We don't have a back page, need to lock our forward and become a back for it.
// If found then we are on inner replacement page, it will be a top parent, no need to lock forward.
if (!found && r.fwdId != 0 && r.backId == 0)
r.lockForward(lvl);
r.addTail(page, buf, io, lvl, Tail.EXACT, idx);
return Remove.FOUND;
}
};
/** */
private final PageHandler<Long> updateFirst = new PageHandler<Long>() {
@Override public int run(Page page, ByteBuffer buf, Long pageId, int lvl) throws IgniteCheckedException {
assert pageId != null;
BPlusMetaIO io = BPlusMetaIO.VERSIONS.forPage(buf);
assert io.getLevelsCount(buf) > lvl;
if (pageId == 0) {
assert lvl == io.getRootLevel(buf); // Can drop only root.
io.setLevelsCount(buf, lvl); // Decrease tree height.
}
else
io.setFirstPageId(buf, lvl, pageId);
return TRUE;
}
};
/** */
private final PageHandler<Long> newRoot = new PageHandler<Long>() {
@Override public int run(Page page, ByteBuffer buf, Long rootPageId, int lvl) throws IgniteCheckedException {
assert rootPageId != null;
BPlusMetaIO io = BPlusMetaIO.VERSIONS.forPage(buf);
assert lvl == io.getLevelsCount(buf);
io.setLevelsCount(buf, lvl + 1);
io.setFirstPageId(buf, lvl, rootPageId);
return TRUE;
}
};
/**
* @param cacheId Cache ID.
* @param pageMem Page memory.
* @param metaPageId Meta page ID.
* @param reuseList Reuse list.
* @throws IgniteCheckedException If failed.
*/
public BPlusTree(int cacheId, PageMemory pageMem, FullPageId metaPageId, ReuseList reuseList)
throws IgniteCheckedException {
// TODO make configurable: 0 <= minFill <= maxFill <= 1
minFill = 0f; // Testing worst case when merge happens only on empty page.
maxFill = 0f; // Avoiding random effects on testing.
assert pageMem != null;
this.pageMem = pageMem;
this.cacheId = cacheId;
this.metaPageId = metaPageId.pageId();
this.reuseList = reuseList;
}
/**
* @return Cache ID.
*/
public int getCacheId() {
return cacheId;
}
/**
* @throws IgniteCheckedException If failed.
*/
protected void initNew() throws IgniteCheckedException {
try (Page meta = page(metaPageId)) {
ByteBuffer buf = meta.getForInitialWrite();
BPlusMetaIO io = BPlusMetaIO.VERSIONS.latest();
io.initNewPage(buf, metaPageId);
try (Page root = allocatePage(null)) {
latestLeafIO().initNewPage(root.getForInitialWrite(), root.id());
io.setLevelsCount(buf, 1);
io.setFirstPageId(buf, 0, root.id());
}
}
}
/**
* @return Root level.
*/
private int getRootLevel(Page meta) {
ByteBuffer buf = meta.getForRead();
try {
return BPlusMetaIO.VERSIONS.forPage(buf).getRootLevel(buf);
}
finally {
meta.releaseRead();
}
}
/**
* @param meta Meta page.
* @param lvl Level, if {@code 0} then it is a bottom level, if negative then root.
* @return Page ID.
*/
private long getFirstPageId(Page meta, int lvl) {
ByteBuffer buf = meta.getForRead();
try {
BPlusMetaIO io = BPlusMetaIO.VERSIONS.forPage(buf);
if (lvl < 0)
lvl = io.getRootLevel(buf);
if (lvl >= io.getLevelsCount(buf))
return 0;
return io.getFirstPageId(buf, lvl);
}
finally {
meta.releaseRead();
}
}
/**
* @param upper Upper bound.
* @return Cursor.
*/
private GridCursor<T> findLowerUnbounded(L upper) throws IgniteCheckedException {
ForwardCursor cursor = new ForwardCursor(upper);
long firstPageId;
try (Page meta = page(metaPageId)) {
firstPageId = getFirstPageId(meta, 0); // Level 0 is always at the bottom.
}
try (Page first = page(firstPageId)) {
ByteBuffer buf = first.getForRead();
try {
cursor.bootstrap(buf, 0);
}
finally {
first.releaseRead();
}
}
return cursor;
}
/**
* @param lower Lower bound.
* @param upper Upper bound.
* @return Cursor.
* @throws IgniteCheckedException If failed.
*/
public final GridCursor<T> find(L lower, L upper) throws IgniteCheckedException {
if (lower == null)
return findLowerUnbounded(upper);
GetCursor g = new GetCursor(lower, upper);
doFind(g);
return g.cursor;
}
/**
* @param row Lookup row for exact match.
* @return Found row.
*/
@SuppressWarnings("unchecked")
public final T findOne(L row) throws IgniteCheckedException {
GetOne g = new GetOne(row);
doFind(g);
return (T)g.row;
}
/**
* @param g Get.
*/
private void doFind(Get g) throws IgniteCheckedException {
try {
for (;;) { // Go down with retries.
g.init();
switch (findDown(g, g.rootId, 0L, g.rootLvl)) {
case Get.RETRY:
case Get.RETRY_ROOT:
checkInterrupted();
continue;
default:
return;
}
}
}
finally {
g.releaseMeta();
}
}
/**
* @param g Get.
* @param pageId Page ID.
* @param fwdId Expected forward page ID.
* @param lvl Level.
* @return Result code.
* @throws IgniteCheckedException If failed.
*/
private int findDown(final Get g, final long pageId, final long fwdId, final int lvl)
throws IgniteCheckedException {
Page page = page(pageId);
try {
for (;;) {
// Init args.
g.pageId = pageId;
g.fwdId = fwdId;
int res = readPage(page, search, g, lvl, Get.RETRY);
switch (res) {
case Get.GO_DOWN:
case Get.GO_DOWN_X:
assert g.pageId != pageId;
assert g.fwdId != fwdId || fwdId == 0;
// Go down recursively.
res = findDown(g, g.pageId, g.fwdId, lvl - 1);
switch (res) {
case Get.RETRY:
checkInterrupted();
continue; // The child page got splitted, need to reread our page.
default:
return res;
}
case Get.NOT_FOUND:
assert lvl == 0: lvl;
g.row = null; // Mark not found result.
return res;
default:
return res;
}
}
}
finally {
if (g.canRelease(page, lvl))
page.close();
}
}
/**
* For debug.
*
* @return Tree as {@link String}.
*/
@SuppressWarnings("unused")
public String printTree() {
long rootPageId;
try (Page meta = page(metaPageId)) {
rootPageId = getFirstPageId(meta, -1);
}
catch (IgniteCheckedException e) {
throw new IllegalStateException(e);
}
return treePrinter.print(rootPageId);
}
/**
* @param io IO.
* @param buf Buffer.
* @param keys Keys.
* @return String.
* @throws IgniteCheckedException If failed.
*/
private String printPage(BPlusIO<L> io, ByteBuffer buf, boolean keys) throws IgniteCheckedException {
StringBuilder b = new StringBuilder();
b.append(formatPageId(PageIO.getPageId(buf)));
b.append(" [ ");
b.append(io.isLeaf() ? "L " : "I ");
int cnt = io.getCount(buf);
long fwdId = io.getForward(buf);
b.append("cnt=").append(cnt).append(' ');
b.append("fwd=").append(formatPageId(fwdId)).append(' ');
if (!io.isLeaf()) {
b.append("lm=").append(inner(io).getLeft(buf, 0)).append(' ');
if (cnt > 0)
b.append("rm=").append(inner(io).getRight(buf, cnt - 1)).append(' ');
}
if (keys)
b.append("keys=").append(printPageKeys(io, buf)).append(' ');
b.append(']');
return b.toString();
}
/**
* @param io IO.
* @param buf Buffer.
* @return Keys as String.
* @throws IgniteCheckedException If failed.
*/
private String printPageKeys(BPlusIO<L> io, ByteBuffer buf) throws IgniteCheckedException {
int cnt = io.getCount(buf);
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0; i < cnt; i++) {
if (i != 0)
b.append(',');
b.append(io.canGetRow() ? getRow(io, buf, i) : io.getLookupRow(this, buf, i));
}
b.append(']');
return b.toString();
}
/**
* @param x Long.
* @return String.
*/
private static String formatPageId(long x) {
return Long.toString(x); //'x' + Long.toHexString(x).toUpperCase();
}
/**
* Check if interrupted.
* @throws IgniteInterruptedCheckedException If interrupted.
*/
private static void checkInterrupted() throws IgniteInterruptedCheckedException {
if (Thread.currentThread().isInterrupted())
throw new IgniteInterruptedCheckedException("Interrupted.");
}
/**
* @param row Lookup row.
* @param bag Reuse bag.
* @return Removed row.
* @throws IgniteCheckedException If failed.
*/
public final T removeCeil(L row, ReuseBag bag) throws IgniteCheckedException {
assert row != null;
return doRemove(row, true, bag);
}
/**
* @param row Lookup row.
* @return Removed row.
* @throws IgniteCheckedException If failed.
*/
public final T remove(L row) throws IgniteCheckedException {
assert row != null;
return doRemove(row, false, null);
}
/**
* @param row Lookup row.
* @param ceil If we can remove ceil row when we can not find exact.
* @param bag Reuse bag.
* @return Removed row.
* @throws IgniteCheckedException If failed.
*/
private T doRemove(L row, boolean ceil, ReuseBag bag) throws IgniteCheckedException {
Remove r = new Remove(row, ceil, bag);
try {
for (;;) {
r.init();
switch (removeDown(r, r.rootId, 0L, 0L, r.rootLvl)) {
case Remove.RETRY:
case Remove.RETRY_ROOT:
checkInterrupted();
continue;
default:
if (!r.isFinished())
r.finishTail();
assert r.isFinished();
return r.removed;
}
}
}
finally {
r.releaseTail();
r.releaseMeta();
r.reuseFreePages();
}
}
/**
* @param r Remove operation.
* @param pageId Page ID.
* @param backId Expected backward page ID if we are going to the right.
* @param fwdId Expected forward page ID.
* @param lvl Level.
* @return Result code.
* @throws IgniteCheckedException If failed.
*/
private int removeDown(final Remove r, final long pageId, final long backId, final long fwdId, final int lvl)
throws IgniteCheckedException {
assert lvl >= 0 : lvl;
if (r.isTail(pageId, lvl))
return Remove.FOUND; // We've already locked this page, so return that we are ok.
final Page page = page(pageId);
try {
for (;;) {
// Init args.
r.pageId = pageId;
r.fwdId = fwdId;
r.backId = backId;
int res = readPage(page, search, r, lvl, Remove.RETRY);
switch (res) {
case Remove.GO_DOWN_X:
// We need to get backId here for our page, it must be the last child of our back.
r.backId = getChild(backId, true);
// Intentional fallthrough.
case Remove.GO_DOWN:
res = removeDown(r, r.pageId, r.backId, r.fwdId, lvl - 1);
switch (res) {
case Remove.RETRY:
checkInterrupted();
continue;
case Remove.RETRY_ROOT:
return res;
}
if (!r.isFinished() && !r.finishTail())
return r.lockTail(page, backId, fwdId, lvl);
return res;
case Remove.NOT_FOUND:
// We are at the bottom.
assert lvl == 0: lvl;
if (!r.ceil) {
r.finish();
return res;
}
// Intentional fallthrough for ceiling remove.
case Remove.FOUND:
// We must be at the bottom here, just need to remove row from the current page.
assert lvl == 0 : lvl;
assert r.removed == null;
res = r.removeFromLeaf(page, backId, fwdId);
if (res == Remove.NOT_FOUND) {
assert r.ceil: "must be a retry if not a ceiling remove";
r.finish();
}
else if (res == Remove.FOUND && r.tail == null) {
// Finish if we don't need to do any merges.
r.finish();
}
return res;
default:
return res;
}
}
}
finally {
r.page = null;
if (r.canRelease(page, lvl))
page.close();
}
}
/**
* @param cnt Count.
* @param cap Capacity.
* @return {@code true} If may merge.
*/
private boolean mayMerge(int cnt, int cap) {
int minCnt = (int)(minFill * cap);
if (cnt <= minCnt) {
assert cnt == 0; // TODO remove
return true;
}
assert cnt > 0;
int maxCnt = (int)(maxFill * cap);
if (cnt > maxCnt)
return false;
assert false; // TODO remove
// Randomization is for smoothing worst case scenarios. Probability of merge attempt
// is proportional to free space in our page (discounted on fill factor).
return randomInt(maxCnt - minCnt) >= cnt - minCnt;
}
/**
* @param max Max.
* @return Random value from {@code 0} (inclusive) to the given max value (exclusive).
*/
public int randomInt(int max) {
return ThreadLocalRandom.current().nextInt(max);
}
/**
* @return Root level.
* @throws IgniteCheckedException If failed.
*/
public final int rootLevel() throws IgniteCheckedException {
try (Page meta = page(metaPageId)) {
return getRootLevel(meta);
}
}
/**
* TODO may produce wrong results on concurrent access
*
* @return Size.
* @throws IgniteCheckedException If failed.
*/
public final long size() throws IgniteCheckedException {
long cnt = 0;
long pageId;
try (Page meta = page(metaPageId)) {
pageId = getFirstPageId(meta, 0); // Level 0 is always at the bottom.
}
BPlusIO<L> io = null;
while (pageId != 0) {
try (Page page = page(pageId)) {
ByteBuffer buf = page.getForRead();
try {
if (io == null) {
io = io(buf);
assert io.isLeaf();
}
cnt += io.getCount(buf);
pageId = io.getForward(buf);
}
finally {
page.releaseRead();
}
}
}
return cnt;
}
/**
* @param row Row.
* @return Old row.
* @throws IgniteCheckedException If failed.
*/
public final T put(T row) throws IgniteCheckedException {
return put(row, null);
}
/**
* @param row Row.
* @param bag Reuse bag.
* @return Old row.
* @throws IgniteCheckedException If failed.
*/
public final T put(T row, ReuseBag bag) throws IgniteCheckedException {
Put p = new Put(row, bag);
try {
for (;;) { // Go down with retries.
p.init();
switch (putDown(p, p.rootId, 0L, p.rootLvl)) {
case Put.RETRY:
case Put.RETRY_ROOT:
checkInterrupted();
continue;
default:
assert p.isFinished();
return p.oldRow;
}
}
}
finally {
p.releaseMeta();
}
}
/**
* @param io IO.
* @param buf Splitting buffer.
* @param fwdBuf Forward buffer.
* @param idx Insertion index.
* @return {@code true} The middle index was shifted to the right.
* @throws IgniteCheckedException If failed.
*/
private boolean splitPage(BPlusIO io, ByteBuffer buf, ByteBuffer fwdBuf, int idx)
throws IgniteCheckedException {
int cnt = io.getCount(buf);
int mid = cnt >>> 1;
boolean res = false;
if (idx > mid) { // If insertion is going to be to the forward page, keep more in the back page.
mid++;
res = true;
}
cnt -= mid;
io.copyItems(buf, fwdBuf, mid, 0, cnt, true);
// Setup counts.
io.setCount(fwdBuf, cnt);
io.setCount(buf, mid);
// Setup forward-backward refs.
io.setForward(fwdBuf, io.getForward(buf));
io.setForward(buf, PageIO.getPageId(fwdBuf));
return res;
}
/**
* @param io IO.
* @param buf Buffer.
* @param row Row.
* @param idx Index.
* @param rightId Right page ID.
* @throws IgniteCheckedException If failed.
*/
private void insertSimple(BPlusIO<L> io, ByteBuffer buf, L row, int idx, long rightId)
throws IgniteCheckedException {
int cnt = io.getCount(buf);
// Move right all the greater elements to make a free slot for a new row link.
io.copyItems(buf, buf, idx, idx + 1, cnt - idx, false);
io.setCount(buf, cnt + 1);
io.store(buf, idx, row);
if (!io.isLeaf()) // Setup reference to the right page on split.
inner(io).setRight(buf, idx, rightId);
}
/**
* @param bag Reuse bag.
* @param meta Meta page.
* @param io IO.
* @param buf Buffer.
* @param row Row.
* @param idx Index.
* @param rightId Right page ID after split.
* @param lvl Level.
* @return Move up row.
* @throws IgniteCheckedException If failed.
*/
private L insertWithSplit(ReuseBag bag, Page meta, BPlusIO<L> io, final ByteBuffer buf, L row,
int idx, long rightId, int lvl) throws IgniteCheckedException {
try (Page fwd = allocatePage(bag)) {
// Need to check this before the actual split, because after the split we will have new forward page here.
boolean hadFwd = io.getForward(buf) != 0;
ByteBuffer fwdBuf = fwd.getForInitialWrite();
io.initNewPage(fwdBuf, fwd.id());
boolean midShift = splitPage(io, buf, fwdBuf, idx);
// Do insert.
int cnt = io.getCount(buf);
if (idx < cnt || (idx == cnt && !midShift)) { // Insert into back page.
insertSimple(io, buf, row, idx, rightId);
// Fix leftmost child of forward page, because newly inserted row will go up.
if (idx == cnt && !io.isLeaf())
inner(io).setLeft(fwdBuf, 0, rightId);
}
else // Insert into newly allocated forward page.
insertSimple(io, fwdBuf, row, idx - cnt, rightId);
// Do move up.
cnt = io.getCount(buf);
L moveUpRow = io.getLookupRow(this, buf, cnt - 1); // Last item from backward row goes up.
if (!io.isLeaf()) // Leaf pages must contain all the links, inner pages remove moveUpLink.
io.setCount(buf, cnt - 1);
if (!hadFwd && lvl == getRootLevel(meta)) { // We are splitting root.
long newRootId;
try (Page newRoot = allocatePage(bag)) {
newRootId = newRoot.id();
if (io.isLeaf())
io = latestInnerIO();
ByteBuffer newRootBuf = newRoot.getForInitialWrite();
io.initNewPage(newRootBuf, newRoot.id());
io.setCount(newRootBuf, 1);
inner(io).setLeft(newRootBuf, 0, PageIO.getPageId(buf));
io.store(newRootBuf, 0, moveUpRow);
inner(io).setRight(newRootBuf, 0, fwd.id());
}
int res = writePage(meta, newRoot, newRootId, lvl + 1, FALSE);
assert res == TRUE : "failed to update meta page";
return null; // We've just moved link up to root, nothing to return here.
}
// Regular split.
return moveUpRow;
}
}
/**
* @param bag Reuse bag.
* @param meta Meta page.
* @param io IO.
* @param buf Buffer.
* @param row Row.
* @param idx Index.
* @param rightId Right ID.
* @param lvl Level.
* @return Move up row.
* @throws IgniteCheckedException If failed.
*/
private L insert(ReuseBag bag, Page meta, BPlusIO<L> io, ByteBuffer buf, L row, int idx, long rightId, int lvl)
throws IgniteCheckedException {
int maxCnt = io.getMaxCount(buf);
int cnt = io.getCount(buf);
if (cnt == maxCnt) // Need to split page.
return insertWithSplit(bag, meta, io, buf, row, idx, rightId, lvl);
insertSimple(io, buf, row, idx, rightId);
return null;
}
/**
* @param page Page.
*/
private static void writeUnlockAndClose(Page page) {
assert page != null;
try {
page.releaseWrite(true);
}
finally {
page.close();
}
}
/**
* @param pageId Inner page ID.
* @param last If {@code true}, then get the last, else get the first child page.
* @return Child page ID.
*/
private long getChild(long pageId, boolean last) throws IgniteCheckedException {
try (Page page = page(pageId)) {
assert page != null : "we've locked back page, forward can't be merged";
ByteBuffer buf = page.getForRead();
try {
BPlusIO<L> io = io(buf);
// Count can be 0 here if it is a routing page, in this case we have single child.
int idx = last ? io.getCount(buf) : 0;
// getLeft(cnt) is the same as getRight(cnt - 1)
long res = inner(io).getLeft(buf, idx);
assert res != 0: "inner page with no route down: " + page.fullId();
return res;
}
finally {
page.releaseRead();
}
}
}
/**
* @param p Put.
* @param pageId Page ID.
* @param fwdId Expected forward page ID.
* @param lvl Level.
* @return Result code.
* @throws IgniteCheckedException If failed.
*/
private int putDown(final Put p, final long pageId, final long fwdId, final int lvl)
throws IgniteCheckedException {
assert lvl >= 0 : lvl;
final Page page = page(pageId);
try {
for (;;) {
// Init args.
p.pageId = pageId;
p.fwdId = fwdId;
int res = readPage(page, search, p, lvl, Put.RETRY);
switch (res) {
case Put.GO_DOWN:
case Put.GO_DOWN_X:
assert lvl > 0 : lvl;
assert p.pageId != pageId;
assert p.fwdId != fwdId || fwdId == 0;
// Need to replace key in inner page. There is no race because we keep tail lock after split.
if (p.needReplaceInner == TRUE) {
p.needReplaceInner = FALSE; // Protect from retries.
res = writePage(page, replace, p, lvl, Put.RETRY);
if (res != Put.FOUND)
return res; // Need to retry.
p.needReplaceInner = DONE; // We can have only single matching inner key.
}
// Go down recursively.
res = putDown(p, p.pageId, p.fwdId, lvl - 1);
if (res == Put.RETRY_ROOT || p.isFinished())
return res;
if (res == Put.RETRY)
checkInterrupted();
continue; // We have to insert split row to this level or it is a retry.
case Put.FOUND: // Do replace.
assert lvl == 0 : "This replace can happen only at the bottom level.";
// Init args.
p.pageId = pageId;
p.fwdId = fwdId;
return writePage(page, replace, p, lvl, Put.RETRY);
case Put.NOT_FOUND: // Do insert.
assert lvl == p.btmLvl : "must insert at the bottom level";
assert p.needReplaceInner == FALSE: p.needReplaceInner + " " + lvl;
// Init args.
p.pageId = pageId;
p.fwdId = fwdId;
return writePage(page, insert, p, lvl, Put.RETRY);
default:
return res;
}
}
}
finally{
if (p.canRelease(page, lvl))
page.close();
}
}
/**
* Get operation.
*/
private abstract class Get {
/** */
static final int GO_DOWN = 1;
/** */
static final int GO_DOWN_X = 2;
/** */
static final int FOUND = 5;
/** */
static final int NOT_FOUND = 6;
/** */
static final int RETRY = 8;
/** */
static final int RETRY_ROOT = 9;
/** */
long rmvId;
/** Starting point root level. May be outdated. Must be modified only in {@link Get#init()}. */
int rootLvl;
/** Starting point root ID. May be outdated. Must be modified only in {@link Get#init()}. */
long rootId;
/** Meta page. Initialized by {@link Get#init()}, released by {@link Get#releaseMeta()}. */
Page meta;
/** */
L row;
/** In/Out parameter: Page ID. */
long pageId;
/** In/Out parameter: expected forward page ID. */
long fwdId;
/** In/Out parameter: in case of right turn this field will contain backward page ID for the child. */
long backId;
/**
* @param row Row.
*/
public Get(L row) {
assert row != null;
this.row = row;
}
/**
* Initialize operation.
*
* !!! Symmetrically with this method must be called {@link Get#releaseMeta()} in {@code finally} block.
*
* @throws IgniteCheckedException If failed.
*/
final void init() throws IgniteCheckedException {
if (meta == null)
meta = page(metaPageId);
int rootLvl;
long rootId;
ByteBuffer buf = meta.getForRead();
try {
BPlusMetaIO io = BPlusMetaIO.VERSIONS.forPage(buf);
rootLvl = io.getRootLevel(buf);
rootId = io.getFirstPageId(buf, rootLvl);
}
finally {
meta.releaseRead();
}
restartFromRoot(rootId, rootLvl, globalRmvId.get());
}
/**
* @param rootId Root page ID.
* @param rootLvl Root level.
* @param rmvId Remove ID to be afraid of.
*/
final void restartFromRoot(long rootId, int rootLvl, long rmvId) {
this.rootId = rootId;
this.rootLvl = rootLvl;
this.rmvId = rmvId;
}
/**
* @param io IO.
* @param buf Buffer.
* @param idx Index of found entry.
* @param lvl Level.
* @return {@code true} If we need to stop.
* @throws IgniteCheckedException If failed.
*/
abstract boolean found(BPlusIO<L> io, ByteBuffer buf, int idx, int lvl) throws IgniteCheckedException;
/**
* @param io IO.
* @param buf Buffer.
* @param idx Insertion point.
* @param lvl Level.
* @return {@code true} If we need to stop.
* @throws IgniteCheckedException If failed.
*/
boolean notFound(BPlusIO<L> io, ByteBuffer buf, int idx, int lvl) throws IgniteCheckedException {
assert lvl >= 0;
return lvl == 0; // We are not at the bottom.
}
/**
* Release meta page.
*/
final void releaseMeta() {
if (meta != null) {
meta.close();
meta = null;
}
}
/**
* @param page Page.
* @param lvl Level.
* @return {@code true} If we can release the given page.
*/
boolean canRelease(Page page, int lvl) {
return page != null;
}
}
/**
* Get a single entry.
*/
private final class GetOne extends Get {
/**
* @param row Row.
*/
private GetOne(L row) {
super(row);
}
/** {@inheritDoc} */
@Override boolean found(BPlusIO<L> io, ByteBuffer buf, int idx, int lvl) throws IgniteCheckedException {
if (!io.canGetRow()) {
assert !io.isLeaf();
return false;
}
row = getRow(io, buf, idx);
return true;
}
}
/**
* Get a cursor for range.
*/
private final class GetCursor extends Get {
/** */
ForwardCursor cursor;
/**
* @param lower Lower bound.
* @param upper Upper bound.
*/
private GetCursor(L lower, L upper) {
super(lower);
cursor = new ForwardCursor(upper);
}
/** {@inheritDoc} */
@Override boolean found(BPlusIO<L> io, ByteBuffer buf, int idx, int lvl) throws IgniteCheckedException {
if (!io.isLeaf())
return false;
cursor.bootstrap(buf, idx);
return true;
}
/** {@inheritDoc} */
@Override boolean notFound(BPlusIO<L> io, ByteBuffer buf, int idx, int lvl) throws IgniteCheckedException {
assert lvl >= 0 : lvl;
if (lvl != 0)
return false;
assert io.isLeaf();
cursor.bootstrap(buf, idx);
return true;
}
}
/**
* Put operation.
*/
private final class Put extends Get {
/** Right child page ID for split row. */
long rightId;
/** Replaced row if any. */
T oldRow;
/**
* This page is kept locked after split until insert to the upper level will not be finished.
* It is needed because split row will be "in flight" and if we'll release tail, remove on
* split row may fail.
*/
Page tail;
/**
* Bottom level for insertion (insert can't go deeper). Will be incremented on split on each level.
*/
short btmLvl;
/** */
byte needReplaceInner = FALSE;
/** */
ReuseBag bag;
/**
* @param row Row.
* @param bag Reuse bag.
*/
private Put(T row, ReuseBag bag) {
super(row);
this.bag = bag;
}
/** {@inheritDoc} */
@Override boolean found(BPlusIO<L> io, ByteBuffer buf, int idx, int lvl) throws IgniteCheckedException {
if (io.isLeaf())
return true;
// If we can get full row from the inner page, we must do inner replace to update full row info here.
if (io.canGetRow() && needReplaceInner == FALSE)
needReplaceInner = TRUE;
return false;
}
/** {@inheritDoc} */
@Override boolean notFound(BPlusIO<L> io, ByteBuffer buf, int idx, int lvl) throws IgniteCheckedException {
assert btmLvl >= 0 : btmLvl;
assert lvl >= btmLvl : lvl;
return lvl == btmLvl;
}
/**
* @param tail Tail lock.
*/
private void tail(Page tail) {
if (this.tail != null)
writeUnlockAndClose(this.tail);
this.tail = tail;
}
/** {@inheritDoc} */
@Override boolean canRelease(Page page, int lvl) {
return page != null && tail != page;
}
/**
* Finish put.
*/
private void finish() {
row = null;
rightId = 0;
tail(null);
}
/**
* @return {@code true} If finished.
*/
private boolean isFinished() {
return row == null;
}
}
/**
* Remove operation.
*/
private final class Remove extends Get implements ReuseBag {
/** */
boolean ceil;
/** We may need to lock part of the tree branch from the bottom to up for multiple levels. */
Tail<L> tail;
/** */
byte needReplaceInner = FALSE;
/** */
byte needMergeEmptyBranch = FALSE;
/** Removed row. */
T removed;
/** Current page. */
Page page;
/** */
short innerIdx = Short.MIN_VALUE;
/** */
Object freePages;
/** */
ReuseBag bag;
/**
* @param row Row.
* @param ceil If we can remove ceil row when we can not find exact.
*/
private Remove(L row, boolean ceil, ReuseBag bag) {
super(row);
this.ceil = ceil;
this.bag = bag;
}
/**
* @return Reuse bag.
*/
private ReuseBag bag() {
return bag != null ? bag : this;
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public FullPageId pollFreePage() {
assert bag == null;
if (freePages == null)
return null;
if (freePages.getClass() == ArrayDeque.class)
return ((ArrayDeque<FullPageId>)freePages).poll();
FullPageId res = (FullPageId)freePages;
freePages = null;
return res;
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public void addFreePage(FullPageId pageId) {
assert pageId != null;
assert bag == null;
if (freePages == null)
freePages = pageId;
else {
ArrayDeque<Object> queue;
if (freePages.getClass() == ArrayDeque.class)
queue = (ArrayDeque<Object>)freePages;
else {
assert freePages instanceof FullPageId;
queue = new ArrayDeque<>();
queue.add(freePages);
freePages = queue;
}
queue.add(pageId);
}
}
/** {@inheritDoc} */
@Override boolean found(BPlusIO<L> io, ByteBuffer buf, int idx, int lvl) throws IgniteCheckedException {
if (io.isLeaf())
return true;
// If we can get full row from the inner page, we must do inner replace to update full row info here.
if (io.canGetRow() && needReplaceInner == FALSE)
needReplaceInner = TRUE;
return false;
}
/** {@inheritDoc} */
@Override boolean notFound(BPlusIO<L> io, ByteBuffer buf, int idx, int lvl) throws IgniteCheckedException {
if (io.isLeaf()) {
assert tail == null;
return true;
}
return false;
}
/**
* Finish the operation.
*/
private void finish() {
assert tail == null;
row = null;
}
/**
* @throws IgniteCheckedException If failed.
*/
private void mergeEmptyBranch() throws IgniteCheckedException {
assert needMergeEmptyBranch == TRUE;
Tail<L> t = tail;
assert t.getCount() > 0;
// Find empty branch beginning.
for (Tail<L> t0 = t.down; t0 != null; t0 = t0.down) {
assert t0.type == Tail.EXACT: t0.type;
if (t0.getCount() != 0)
t = t0;
}
while (t.lvl != 0) { // If we've found empty branch, merge it top down.
boolean res = merge(t);
assert res: needMergeEmptyBranch;
if (needMergeEmptyBranch == TRUE)
needMergeEmptyBranch = READY; // Need to mark that we've already done the first iteration.
t = t.down;
}
assert t.lvl == 0: t.lvl;
}
/**
* @param t Tail.
* @return {@code true} If merged successfully or end reached.
* @throws IgniteCheckedException If failed.
*/
private boolean mergeBottomUp(Tail<L> t) throws IgniteCheckedException {
assert needMergeEmptyBranch == FALSE || needMergeEmptyBranch == DONE: needMergeEmptyBranch;
if (t.down == null)
return true;
if (t.down.sibling == null) // We've merged something there.
return false;
return mergeBottomUp(t.down) && merge(t);
}
/**
* Process tail and finish.
*
* @return {@code false} If failed to finish and we need to lock more pages up.
* @throws IgniteCheckedException If failed.
*/
private boolean finishTail() throws IgniteCheckedException {
assert !isFinished();
assert tail.type == Tail.EXACT;
boolean mergedBranch = false;
if (needMergeEmptyBranch == TRUE) {
// We can't merge empty branch if tail in routing page.
if (tail.down == null || tail.getCount() == 0)
return false; // Lock the whole branch up to the first non-empty.
mergeEmptyBranch();
mergedBranch = true;
needMergeEmptyBranch = DONE;
}
mergeBottomUp(tail);
if (needReplaceInner == READY) {
// If we've merged empty branch right now, then the inner key was dropped.
if (!mergedBranch)
replaceInner(); // Replace inner key with new max key for the left subtree.
needReplaceInner = DONE;
}
else if (needReplaceInner == TRUE)
return false; // Lock the whole branch up to the inner key page.
if (tail.getCount() == 0 && tail.lvl != 0 && getRootLevel(meta) == tail.lvl) {
// Free root if it became empty after merge.
freePage(tail.page, tail.buf, tail.io, tail.lvl, false);
}
else if (tail.sibling != null && tail.getCount() + tail.sibling.getCount() < tail.io.getMaxCount(tail.buf)) {
// Release everything lower than tail, we've already merged this path.
doReleaseTail(tail.down);
tail.down = null;
return false; // Lock and merge one level more.
}
releaseTail();
finish();
return true;
}
/**
* @param leaf Leaf page.
* @param backId Back page ID.
* @param fwdId Forward ID.
* @return Result code.
* @throws IgniteCheckedException If failed.
*/
private int removeFromLeaf(Page leaf, long backId, long fwdId) throws IgniteCheckedException {
// Init parameters.
this.pageId = leaf.id();
this.page = leaf;
this.backId = backId;
this.fwdId = fwdId;
if (backId == 0)
return doRemoveFromLeaf();
// Lock back page before the remove, we'll need it for merges.
Page back = page(backId);
try {
return writePage(back, lockBackAndRemoveFromLeaf, this, 0, Remove.RETRY);
}
finally {
if (canRelease(back, 0))
back.close();
}
}
/**
* @return Result code.
* @throws IgniteCheckedException If failed.
*/
private int doRemoveFromLeaf() throws IgniteCheckedException {
assert page != null;
return writePage(page, removeFromLeaf, this, 0, Remove.RETRY);
}
/**
* @param lvl Level.
* @return Result code.
* @throws IgniteCheckedException If failed.
*/
private int doLockTail(int lvl) throws IgniteCheckedException {
assert page != null;
return writePage(page, lockTail, this, lvl, Remove.RETRY);
}
/**
* @param page Page.
* @param backId Back page ID.
* @param fwdId Expected forward page ID.
* @param lvl Level.
* @return Result code.
* @throws IgniteCheckedException If failed.
*/
private int lockTail(Page page, long backId, long fwdId, int lvl) throws IgniteCheckedException {
assert tail != null;
// Init parameters for the handlers.
this.pageId = page.id();
this.page = page;
this.fwdId = fwdId;
this.backId = backId;
if (backId == 0) // Back page ID is provided only when the last move was to the right.
return doLockTail(lvl);
Page back = page(backId);
try {
return writePage(back, lockBackAndTail, this, lvl, Remove.RETRY);
}
finally {
if (canRelease(back, lvl))
back.close();
}
}
/**
* @param lvl Level.
* @throws IgniteCheckedException If failed.
*/
private void lockForward(int lvl) throws IgniteCheckedException {
assert fwdId != 0;
assert backId == 0;
int res = writePage(page(fwdId), lockTailForward, this, lvl, Remove.RETRY);
// Must always be called from lock on back page, thus we should never fail here.
assert res == Remove.FOUND: res;
}
/**
* @param io IO.
* @param buf Buffer.
* @param cnt Count.
* @param idx Index to remove.
* @throws IgniteCheckedException If failed.
*/
private void doRemove(BPlusIO io, ByteBuffer buf, int cnt, int idx)
throws IgniteCheckedException {
assert cnt > 0: cnt;
assert idx >= 0 && idx < cnt: idx + " " + cnt;
cnt--;
io.copyItems(buf, buf, idx + 1, idx, cnt - idx, false);
io.setCount(buf, cnt);
}
/**
* @param prnt Parent tail.
* @param left Left child tail.
* @param right Right child tail.
* @return {@code true} If merged successfully.
* @throws IgniteCheckedException If failed.
*/
private boolean doMerge(Tail<L> prnt, Tail<L> left, Tail<L> right)
throws IgniteCheckedException {
assert right.io == left.io; // Otherwise incompatible.
assert left.io.getForward(left.buf) == right.page.id();
int prntCnt = prnt.getCount();
int leftCnt = left.getCount();
int rightCnt = right.getCount();
assert prntCnt > 0 || needMergeEmptyBranch == READY: prntCnt;
int newCnt = leftCnt + rightCnt;
boolean emptyBranch = needMergeEmptyBranch == TRUE || needMergeEmptyBranch == READY;
// Need to move down split key in inner pages. For empty branch merge parent key will be just dropped.
if (left.lvl != 0 && !emptyBranch)
newCnt++;
if (newCnt > left.io.getMaxCount(left.buf)) {
assert !emptyBranch;
return false;
}
left.io.setCount(left.buf, newCnt);
// Move down split key in inner pages.
if (left.lvl != 0 && !emptyBranch) {
int prntIdx = prnt.idx;
if (prntIdx == prntCnt) // It was a right turn.
prntIdx--;
// We can be sure that we have enough free space to store split key here,
// because we've done remove already and did not release child locks.
left.io.store(left.buf, leftCnt, prnt.io, prnt.buf, prntIdx);
leftCnt++;
}
left.io.copyItems(right.buf, left.buf, 0, leftCnt, rightCnt, !emptyBranch);
left.io.setForward(left.buf, right.io.getForward(right.buf));
// Fix index for the right move: remove last item.
int prntIdx = prnt.idx == prntCnt ? prntCnt - 1 : prnt.idx;
// Remove split key from parent. If we ar emerging empty branch then remove only on the top iteration.
if (needMergeEmptyBranch != READY)
doRemove(prnt.io, prnt.buf, prntCnt, prntIdx);
// Forward page is now empty and has no links, can free and release it right away.
freePage(right.page, right.buf, right.io, right.lvl, true);
return true;
}
/**
* @param page Page.
* @param buf Buffer.
* @param io IO.
* @param lvl Level.
* @param release Release write lock and release page.
* @throws IgniteCheckedException If failed.
*/
@SuppressWarnings("unchecked")
private void freePage(Page page, ByteBuffer buf, BPlusIO io, int lvl, boolean release)
throws IgniteCheckedException {
if (getFirstPageId(meta, lvl) == page.id()) {
// This logic will handle root as well.
long fwdId = io.getForward(buf);
writePage(meta, updateFirst, fwdId, lvl, FALSE);
}
// Mark removed.
io.setRemoveId(buf, Long.MAX_VALUE);
if (release)
writeUnlockAndClose(page);
bag().addFreePage(page.fullId());
}
/**
* @throws IgniteCheckedException If failed.
*/
@SuppressWarnings("unchecked")
private void reuseFreePages() throws IgniteCheckedException {
// If we have a bag, then it will be processed at the upper level.
if (reuseList != null && bag == null)
reuseList.add(BPlusTree.this, this);
}
/**
* @throws IgniteCheckedException If failed.
*/
private void replaceInner() throws IgniteCheckedException {
assert needReplaceInner == READY: needReplaceInner;
assert tail.lvl > 0: "leaf";
assert innerIdx >= 0: innerIdx;
Tail<L> leaf = getTail(0);
Tail<L> inner = tail;
assert inner.type == Tail.EXACT: inner.type;
int innerCnt = inner.getCount();
int leafCnt = leaf.getCount();
assert leafCnt > 0: leafCnt; // Leaf must be merged at this point already if it was empty.
if (innerIdx < innerCnt) {
// Update inner key with the new biggest key of left subtree.
inner.io.store(inner.buf, innerIdx, leaf.io, leaf.buf, leafCnt - 1);
leaf.io.setRemoveId(leaf.buf, globalRmvId.get());
}
else {
// If after leaf merge parent have lost inner key, we don't need to update it anymore.
assert innerIdx == innerCnt;
assert inner(inner.io).getLeft(inner.buf, innerIdx) == leaf.page.id();
}
}
/**
* @param prnt Parent for merge.
* @return {@code true} If merged, {@code false} if not (because of insufficient space or empty parent).
* @throws IgniteCheckedException If failed.
*/
private boolean merge(Tail<L> prnt) throws IgniteCheckedException {
// If we are merging empty branch this is acceptable because even if we merge
// two routing pages, one of them is effectively dropped in this merge, so just
// keep a single routing page.
if (prnt.getCount() == 0 && needMergeEmptyBranch != READY)
return false; // Parent is an empty routing page, child forward page will have another parent.
Tail<L> right = prnt.down;
Tail<L> left = right.sibling;
assert right.type == Tail.EXACT;
assert left != null: "we must have a partner to merge with";
if (left.type != Tail.BACK) { // Flip if it was actually FORWARD but not BACK.
assert left.type == Tail.FORWARD: left.type;
left = right;
right = right.sibling;
}
assert right.io == left.io: "must always be the same"; // Otherwise can be not compatible.
if (!doMerge(prnt, left, right))
return false;
// left from BACK becomes EXACT.
if (left.type == Tail.BACK) {
assert left.sibling == null;
left.down = right.down;
left.type = Tail.EXACT;
prnt.down = left;
}
else { // left is already EXACT.
assert left.type == Tail.EXACT: left.type;
left.sibling = null;
}
return true;
}
/**
* @return {@code true} If finished.
*/
private boolean isFinished() {
return row == null;
}
/**
* Release pages for all locked levels at the tail.
*/
private void releaseTail() {
doReleaseTail(tail);
tail = null;
}
/**
* @param t Tail.
*/
private void doReleaseTail(Tail<L> t) {
while (t != null) {
writeUnlockAndClose(t.page);
if (t.sibling != null)
writeUnlockAndClose(t.sibling.page);
t = t.down;
}
}
/** {@inheritDoc} */
@Override boolean canRelease(Page page, int lvl) {
return page != null && !isTail(page.id(), lvl);
}
/**
* @param pageId Page ID.
* @param lvl Level.
* @return {@code true} If the given page is in tail.
*/
private boolean isTail(long pageId, int lvl) {
Tail t = tail;
while (t != null) {
if (t.lvl < lvl)
return false;
if (t.lvl == lvl) {
if (t.page.id() == pageId)
return true;
t = t.sibling;
return t != null && t.page.id() == pageId;
}
t = t.down;
}
return false;
}
/**
* @param page Page.
* @param buf Buffer.
* @param io IO.
* @param lvl Level.
* @param type Type.
* @param idx Insertion index or negative flag describing if the page is primary in this tail branch.
*/
private void addTail(Page page, ByteBuffer buf, BPlusIO<L> io, int lvl, byte type, int idx) {
Tail<L> t = new Tail<>(page, buf, io, type, lvl, idx);
if (tail == null)
tail = t;
else if (tail.lvl == lvl) { // Add on the same level.
assert tail.sibling == null; // Only two siblings on a single level.
if (type == Tail.EXACT) {
assert tail.type != Tail.EXACT;
if (tail.down != null) { // Take down from sibling, EXACT must own down link.
t.down = tail.down;
tail.down = null;
}
t.sibling = tail;
tail = t;
}
else {
assert tail.type == Tail.EXACT: tail.type;
tail.sibling = t;
}
}
else if (tail.lvl == lvl - 1) { // Add on top of existing level.
t.down = tail;
tail = t;
}
else
throw new IllegalStateException();
}
/**
* @param lvl Level.
* @return Tail of {@link Tail#EXACT} type at the given level.
*/
private Tail<L> getTail(int lvl) {
assert tail != null;
assert lvl >= 0 && lvl <= tail.lvl: lvl;
Tail<L> t = tail;
while (t.lvl != lvl)
t = t.down;
assert t.type == Tail.EXACT: t.type; // All the down links must be of EXACT type.
return t;
}
}
/**
* Tail for remove.
*/
private static class Tail<L> {
/** */
static final byte BACK = 0;
/** */
static final byte EXACT = 1;
/** */
static final byte FORWARD = 2;
/** */
final Page page;
/** */
final ByteBuffer buf;
/** */
final BPlusIO<L> io;
/** */
byte type;
/** */
final byte lvl;
/** */
final short idx;
/** Only {@link #EXACT} tail can have either {@link #BACK} or {@link #FORWARD} sibling.*/
Tail<L> sibling;
/** Only {@link #EXACT} tail can point to {@link #EXACT} tail of lower level. */
Tail<L> down;
/**
* @param page Write locked page.
* @param buf Buffer.
* @param io IO.
* @param type Type.
* @param lvl Level.
* @param idx Insertion index.
*/
private Tail(Page page, ByteBuffer buf, BPlusIO<L> io, byte type, int lvl, int idx) {
assert type == BACK || type == EXACT || type == FORWARD: type;
assert idx == -1 || (idx >= 0 && idx <= Short.MAX_VALUE): idx ;
assert lvl >= 0 && lvl <= Byte.MAX_VALUE: lvl;
assert page != null;
this.page = page;
this.buf = buf;
this.io = io;
this.type = type;
this.lvl = (byte)lvl;
this.idx = (short)idx;
}
/**
* @return Count.
*/
private int getCount() {
return io.getCount(buf);
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(Tail.class, this, "pageId", page.id(), "cnt", getCount(), "lvl", lvl, "sibling", sibling);
}
}
/**
* @param io IO.
* @param buf Buffer.
* @param cnt Row count.
* @param row Lookup row.
* @return Insertion point as in {@link Arrays#binarySearch(Object[], Object, Comparator)}.
*/
private int findInsertionPoint(BPlusIO<L> io, ByteBuffer buf, int cnt, L row)
throws IgniteCheckedException {
assert row != null;
int low = 0;
int high = cnt - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
int cmp = compare(io, buf, mid, row);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid; // found
}
return -(low + 1); // not found
}
/**
* @param buf Buffer.
* @return IO.
*/
private BPlusIO<L> io(ByteBuffer buf) {
assert buf != null;
int type = PageIO.getType(buf);
int ver = PageIO.getVersion(buf);
return io(type, ver);
}
/**
* @param io IO.
* @return Inner page IO.
*/
private static <L> BPlusInnerIO<L> inner(BPlusIO<L> io) {
assert !io.isLeaf();
return (BPlusInnerIO<L>)io;
}
/**
* @param pageId Page ID.
* @return Page.
* @throws IgniteCheckedException If failed.
*/
private Page page(long pageId) throws IgniteCheckedException {
return pageMem.page(new FullPageId(pageId, cacheId));
}
/**
* @param bag Reuse bag.
* @return Allocated page.
*/
private Page allocatePage(ReuseBag bag) throws IgniteCheckedException {
FullPageId pageId = bag != null ? bag.pollFreePage() : null;
if (pageId == null && reuseList != null)
pageId = reuseList.take(this, bag);
if (pageId == null)
pageId = pageMem.allocatePage(cacheId, -1, PageIdAllocator.FLAG_IDX);
return pageMem.page(pageId);
}
/**
* @param type Page type.
* @param ver Page version.
* @return IO.
*/
protected abstract BPlusIO<L> io(int type, int ver);
/**
* @return Latest version of inner page IO.
*/
protected abstract BPlusInnerIO<L> latestInnerIO();
/**
* @return Latest version of leaf page IO.
*/
protected abstract BPlusLeafIO<L> latestLeafIO();
/**
* @param buf Buffer.
* @param idx Index of row in the given buffer.
* @param row Lookup row.
* @return Comparison result as in {@link Comparator#compare(Object, Object)}.
* @throws IgniteCheckedException If failed.
*/
protected abstract int compare(BPlusIO<L> io, ByteBuffer buf, int idx, L row) throws IgniteCheckedException;
/**
* This method can be called only if {@link BPlusIO#canGetRow()} returns {@code true}.
*
* @param io IO.
* @param buf Buffer.
* @param idx Index.
* @return Full data row.
* @throws IgniteCheckedException If failed.
*/
protected abstract T getRow(BPlusIO<L> io, ByteBuffer buf, int idx) throws IgniteCheckedException;
/**
* Forward cursor.
*/
protected class ForwardCursor implements GridCursor<T> {
/** */
private List<T> rows;
/** */
private int row;
/** */
private Page page;
/** */
private ByteBuffer buf;
/** */
private final L upperBound;
/**
* @param upperBound Upper bound.
*/
protected ForwardCursor(L upperBound) {
this.upperBound = upperBound;
}
/**
* @param buf Buffer.
* @param startIdx Start index.
*/
void bootstrap(ByteBuffer buf, int startIdx) throws IgniteCheckedException {
assert buf != null;
row = -1;
this.buf = buf;
fillFromBuffer(startIdx);
}
/**
* @param startIdx Start index.
*/
private boolean fillFromBuffer(int startIdx) throws IgniteCheckedException {
if (buf == null)
return false;
for (;;) {
BPlusIO<L> io = io(buf);
assert io.isLeaf();
assert io.canGetRow();
int cnt = io.getCount(buf);
long fwdId = io.getForward(buf);
if (cnt > 0) {
if (upperBound != null) {
int cmp = compare(io, buf, cnt - 1, upperBound);
if (cmp > 0) {
int idx = findInsertionPoint(io, buf, cnt, upperBound);
cnt = idx < 0 ? -idx : idx + 1;
fwdId = 0; // The End.
}
}
}
if (cnt > startIdx) {
if (rows == null)
rows = new ArrayList<>();
for (int i = startIdx; i < cnt; i++)
rows.add(getRow(io, buf, i));
}
Page prevPage = page;
if (fwdId != 0) { // Lock next page.
page = page(fwdId);
buf = page.getForRead();
}
else { // Clear.
page = null;
buf = null;
}
if (prevPage != null) { // Release previous page.
try {
prevPage.releaseRead();
}
finally {
prevPage.close();
}
}
if (F.isEmpty(rows)) {
if (buf == null)
return false;
continue;
}
return true;
}
}
/** {@inheritDoc} */
@Override public boolean next() throws IgniteCheckedException {
if (rows == null)
return false;
if (++row < rows.size())
return true;
row = 0;
rows.clear();
return fillFromBuffer(0);
}
/** {@inheritDoc} */
@Override public T get() {
return rows.get(row);
}
}
/**
* Page handler for basic {@link Get} operation.
*/
private abstract class GetPageHandler<G extends Get> extends PageHandler<G> {
/** {@inheritDoc} */
@Override public final int run(Page page, ByteBuffer buf, G g, int lvl) throws IgniteCheckedException {
BPlusIO<L> io = io(buf);
// In case of intersection with inner replace remove operation
// we need to restart our operation from the root.
if (g.rmvId < io.getRemoveId(buf))
return Get.RETRY_ROOT;
return run0(page, buf, io, g, lvl);
}
/**
* @param page Page.
* @param buf Buffer.
* @param io IO.
* @param g Operation.
* @param lvl Level.
* @return Result code.
* @throws IgniteCheckedException If failed.
*/
protected abstract int run0(Page page, ByteBuffer buf, BPlusIO<L> io, G g, int lvl)
throws IgniteCheckedException;
/** {@inheritDoc} */
@Override public final boolean releaseAfterWrite(Page page, G g, int lvl) {
return g.canRelease(page, lvl);
}
}
}
| modules/core/src/main/java/org/apache/ignite/internal/processors/cache/database/tree/BPlusTree.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.ignite.internal.processors.cache.database.tree;
import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.IgniteInterruptedCheckedException;
import org.apache.ignite.internal.pagemem.FullPageId;
import org.apache.ignite.internal.pagemem.Page;
import org.apache.ignite.internal.pagemem.PageIdAllocator;
import org.apache.ignite.internal.pagemem.PageMemory;
import org.apache.ignite.internal.processors.cache.database.tree.io.BPlusIO;
import org.apache.ignite.internal.processors.cache.database.tree.io.BPlusInnerIO;
import org.apache.ignite.internal.processors.cache.database.tree.io.BPlusLeafIO;
import org.apache.ignite.internal.processors.cache.database.tree.io.BPlusMetaIO;
import org.apache.ignite.internal.processors.cache.database.tree.io.PageIO;
import org.apache.ignite.internal.processors.cache.database.tree.reuse.ReuseBag;
import org.apache.ignite.internal.processors.cache.database.tree.reuse.ReuseList;
import org.apache.ignite.internal.processors.cache.database.tree.util.PageHandler;
import org.apache.ignite.internal.util.lang.GridCursor;
import org.apache.ignite.internal.util.lang.GridTreePrinter;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import static org.apache.ignite.internal.processors.cache.database.tree.util.PageHandler.readPage;
import static org.apache.ignite.internal.processors.cache.database.tree.util.PageHandler.writePage;
/**
* Abstract B+Tree.
*/
public abstract class BPlusTree<L, T extends L> {
/** */
private static final byte FALSE = 0;
/** */
private static final byte TRUE = 1;
/** */
private static final byte READY = 2;
/** */
private static final byte DONE = 3;
/** */
protected final int cacheId;
/** */
private final PageMemory pageMem;
/** */
private final ReuseList reuseList;
/** */
private final float minFill;
/** */
private final float maxFill;
/** */
private final long metaPageId;
/** */
private final AtomicLong globalRmvId = new AtomicLong(U.currentTimeMillis() * 1000_000); // TODO init from WAL?
/** */
private final GridTreePrinter<Long> treePrinter = new GridTreePrinter<Long>() {
/** */
private boolean keys = true;
@Override protected List<Long> getChildren(Long pageId) {
if (pageId == null || pageId == 0L)
return null;
try (Page page = page(pageId)) {
ByteBuffer buf = page.getForRead();
try {
BPlusIO io = io(buf);
if (io.isLeaf())
return null;
List<Long> res;
int cnt = io.getCount(buf);
assert cnt >= 0: cnt;
if (cnt > 0) {
res = new ArrayList<>(cnt + 1);
for (int i = 0; i < cnt; i++)
res.add(inner(io).getLeft(buf, i));
res.add(inner(io).getRight(buf, cnt - 1));
}
else {
long left = inner(io).getLeft(buf, 0);
res = left == 0 ? Collections.<Long>emptyList() : Collections.singletonList(left);
}
return res;
}
finally {
page.releaseRead();
}
}
catch (IgniteCheckedException e) {
throw new IllegalStateException(e);
}
}
@Override protected String formatTreeNode(Long pageId) {
if (pageId == null)
return ">NPE<";
if (pageId == 0L)
return "<Zero>";
try (Page page = page(pageId)) {
ByteBuffer buf = page.getForRead();
try {
BPlusIO<L> io = io(buf);
return printPage(io, buf, keys);
}
finally {
page.releaseRead();
}
}
catch (IgniteCheckedException e) {
throw new IllegalStateException(e);
}
}
};
/** */
private final PageHandler<Get> search = new GetPageHandler<Get>() {
@Override public int run0(Page page, ByteBuffer buf, BPlusIO<L> io, Get g, int lvl)
throws IgniteCheckedException {
boolean needBackIfRouting = g.backId != 0;
g.backId = 0; // Usually we'll go left down and don't need it.
int cnt = io.getCount(buf);
int idx = findInsertionPoint(io, buf, cnt, g.row);
boolean found = idx >= 0;
if (found) { // Found exact match.
if (g.found(io, buf, idx, lvl))
return Get.FOUND;
assert !io.isLeaf();
// Else we need to reach leaf page, go left down.
}
else {
idx = -idx - 1;
// If we are on the right edge, then check for expected forward page and retry of it does match.
// It means that concurrent split happened. This invariant is referred as `triangle`.
if (idx == cnt && io.getForward(buf) != g.fwdId)
return Get.RETRY;
if (g.notFound(io, buf, idx, lvl)) // No way down, stop here.
return Get.NOT_FOUND;
assert !io.isLeaf();
assert lvl > 0 : lvl;
}
// If idx == cnt then we go right down, else left down.
g.pageId = inner(io).getLeft(buf, idx);
// If we see the tree in consistent state, then our right down page must be forward for our left down page.
if (idx < cnt)
g.fwdId = inner(io).getRight(buf, idx);
else {
assert idx == cnt;
// Here child's forward is unknown to us (we either go right or it is an empty "routing" page),
// need to ask our forward about the child's forward (it must be leftmost child of our forward page).
// This is ok from the locking standpoint because we take all locks in the forward direction.
long fwdId = io.getForward(buf);
g.fwdId = fwdId == 0 ? 0 : getChild(fwdId, false);
if (cnt != 0) // It is not a routing page and we are going to the right, can get backId here.
g.backId = inner(io).getLeft(buf, cnt - 1);
else if (needBackIfRouting) {
// Can't get backId here because of possible deadlock and it is only needed for remove operation.
return Remove.GO_DOWN_X;
}
}
return Get.GO_DOWN;
}
};
/** */
private final PageHandler<Put> replace = new GetPageHandler<Put>() {
@Override public int run0(Page page, ByteBuffer buf, BPlusIO<L> io, Put p, int lvl)
throws IgniteCheckedException {
assert p.btmLvl == 0 : "split is impossible with replace";
int cnt = io.getCount(buf);
int idx = findInsertionPoint(io, buf, cnt, p.row);
if (idx < 0) { // Not found, split or merge happened.
long fwdId = io.getForward(buf);
assert fwdId != 0;
p.pageId = fwdId;
return Put.RETRY;
}
// Replace link at idx with new one.
// Need to read link here because `p.finish()` will clear row.
L newRow = p.row;
if (io.isLeaf()) { // Get old row in leaf page to reduce contention at upper level.
assert p.oldRow == null;
assert io.canGetRow();
p.oldRow = getRow(io, buf, idx);
p.finish();
// We can't erase data page here because it can be referred from other indexes.
}
io.store(buf, idx, newRow);
return Put.FOUND;
}
};
/** */
private final PageHandler<Put> insert = new GetPageHandler<Put>() {
@Override public int run0(Page page, ByteBuffer buf, BPlusIO<L> io, Put p, int lvl)
throws IgniteCheckedException {
assert p.btmLvl == lvl: "we must always insert at the bottom level: " + p.btmLvl + " " + lvl;
int cnt = io.getCount(buf);
int idx = findInsertionPoint(io, buf, cnt, p.row);
assert idx < 0: "Duplicate row in index.";
idx = -idx - 1;
// Possible split or merge.
if (idx == cnt && io.getForward(buf) != p.fwdId)
return Put.RETRY;
// Do insert.
L moveUpRow = insert(p.bag, p.meta, io, buf, p.row, idx, p.rightId, lvl);
// Check if split happened.
if (moveUpRow != null) {
p.btmLvl++; // Get high.
p.row = moveUpRow;
// Here `forward` can't be concurrently removed because we keep `tail` which is the only
// page who knows about the `forward` page, because it was just produced by split.
p.rightId = io.getForward(buf);
p.tail(page);
assert p.rightId != 0;
}
else
p.finish();
return Put.FOUND;
}
};
/** */
private final PageHandler<Remove> removeFromLeaf = new GetPageHandler<Remove>() {
@Override public int run0(Page leaf, ByteBuffer buf, BPlusIO<L> io, Remove r, int lvl)
throws IgniteCheckedException {
assert lvl == 0: lvl;
assert r.removed == null;
assert io.isLeaf();
assert io.canGetRow();
int cnt = io.getCount(buf);
int idx = findInsertionPoint(io, buf, cnt, r.row);
if (idx < 0) {
if (!r.ceil) // We've found exact match on search but now it's gone.
return Remove.RETRY;
idx = -idx - 1;
if (idx == cnt) // We can not remove ceiling row here.
return Remove.NOT_FOUND;
assert idx < cnt;
}
r.removed = getRow(io, buf, idx);
r.doRemove(io, buf, cnt, idx);
if (r.needReplaceInner == TRUE) {
// We increment remove ID in write lock on leaf page, thus it is guaranteed that
// any successor will get greater value than he had read at the beginning of the operation.
// Thus he is guaranteed to do a retry from root. Since inner replace takes locks on the whole branch
// and releases the locks only when the inner key is updated and the successor saw the updated removeId,
// then after retry from root, he will see updated inner key.
io.setRemoveId(buf, globalRmvId.incrementAndGet());
}
// We may need to replace inner key or want to merge this leaf with sibling after the remove -> keep lock.
if (r.needReplaceInner == TRUE ||
// We need to make sure that we have back or forward to be able to merge.
((r.fwdId != 0 || r.backId != 0) && mayMerge(cnt - 1, io.getMaxCount(buf)))) {
if (cnt == 1) // It was the last item.
r.needMergeEmptyBranch = TRUE;
// If we have backId then we've already locked back page, nothing to do here.
if (r.fwdId != 0 && r.backId == 0)
r.lockForward(0);
r.addTail(leaf, buf, io, 0, Tail.EXACT, -1);
}
return Remove.FOUND;
}
};
/** */
private final PageHandler<Remove> lockBackAndRemoveFromLeaf = new GetPageHandler<Remove>() {
@Override protected int run0(Page back, ByteBuffer buf, BPlusIO<L> io, Remove r, int lvl)
throws IgniteCheckedException {
// Check that we have consistent view of the world.
if (io.getForward(buf) != r.pageId)
return Remove.RETRY;
// Correct locking order: from back to forward.
int res = r.doRemoveFromLeaf();
// Keep locks on back and leaf pages for subsequent merges.
if (res == Remove.FOUND && r.tail != null)
r.addTail(back, buf, io, lvl, Tail.BACK, -1);
return res;
}
};
/** */
private final PageHandler<Remove> lockBackAndTail = new GetPageHandler<Remove>() {
@Override public int run0(Page back, ByteBuffer buf, BPlusIO<L> io, Remove r, int lvl)
throws IgniteCheckedException {
// Check that we have consistent view of the world.
if (io.getForward(buf) != r.pageId)
return Remove.RETRY;
// Correct locking order: from back to forward.
int res = r.doLockTail(lvl);
if (res == Remove.FOUND)
r.addTail(back, buf, io, lvl, Tail.BACK, -1);
return res;
}
};
/** */
private final PageHandler<Remove> lockTailForward = new GetPageHandler<Remove>() {
@Override protected int run0(Page page, ByteBuffer buf, BPlusIO<L> io, Remove r, int lvl)
throws IgniteCheckedException {
r.addTail(page, buf, io, lvl, Tail.FORWARD, -1);
return Remove.FOUND;
}
};
/** */
private final PageHandler<Remove> lockTail = new GetPageHandler<Remove>() {
@Override public int run0(Page page, ByteBuffer buf, BPlusIO<L> io, Remove r, int lvl)
throws IgniteCheckedException {
assert lvl > 0: lvl; // We are not at the bottom.
int cnt = io.getCount(buf);
int idx = findInsertionPoint(io, buf, cnt, r.row);
boolean found = idx >= 0;
if (found) {
if (io.canGetRow()) {
// We can not miss the inner value on down move because of `triangle` invariant, thus it must be TRUE.
assert r.needReplaceInner == TRUE : r.needReplaceInner;
assert idx <= Short.MAX_VALUE : idx;
r.innerIdx = (short)idx;
r.needReplaceInner = READY;
}
}
else {
idx = -idx - 1;
// Check that we have a correct view of the world.
if (idx == cnt && io.getForward(buf) != r.fwdId)
return Remove.RETRY;
}
// Check that we have a correct view of the world.
if (lvl != 0 && inner(io).getLeft(buf, idx) != r.getTail(lvl - 1).page.id()) {
assert !found;
return Remove.RETRY;
}
// We don't have a back page, need to lock our forward and become a back for it.
// If found then we are on inner replacement page, it will be a top parent, no need to lock forward.
if (!found && r.fwdId != 0 && r.backId == 0)
r.lockForward(lvl);
r.addTail(page, buf, io, lvl, Tail.EXACT, idx);
return Remove.FOUND;
}
};
/** */
private final PageHandler<Long> updateFirst = new PageHandler<Long>() {
@Override public int run(Page page, ByteBuffer buf, Long pageId, int lvl) throws IgniteCheckedException {
assert pageId != null;
BPlusMetaIO io = BPlusMetaIO.VERSIONS.forPage(buf);
assert io.getLevelsCount(buf) > lvl;
if (pageId == 0) {
assert lvl == io.getRootLevel(buf); // Can drop only root.
io.setLevelsCount(buf, lvl); // Decrease tree height.
}
else
io.setFirstPageId(buf, lvl, pageId);
return TRUE;
}
};
/** */
private final PageHandler<Long> newRoot = new PageHandler<Long>() {
@Override public int run(Page page, ByteBuffer buf, Long rootPageId, int lvl) throws IgniteCheckedException {
assert rootPageId != null;
BPlusMetaIO io = BPlusMetaIO.VERSIONS.forPage(buf);
assert lvl == io.getLevelsCount(buf);
io.setLevelsCount(buf, lvl + 1);
io.setFirstPageId(buf, lvl, rootPageId);
return TRUE;
}
};
/**
* @param cacheId Cache ID.
* @param pageMem Page memory.
* @param metaPageId Meta page ID.
* @param reuseList Reuse list.
* @throws IgniteCheckedException If failed.
*/
public BPlusTree(int cacheId, PageMemory pageMem, FullPageId metaPageId, ReuseList reuseList)
throws IgniteCheckedException {
// TODO make configurable: 0 <= minFill <= maxFill <= 1
minFill = 0f; // Testing worst case when merge happens only on empty page.
maxFill = 0f; // Avoiding random effects on testing.
assert pageMem != null;
this.pageMem = pageMem;
this.cacheId = cacheId;
this.metaPageId = metaPageId.pageId();
this.reuseList = reuseList;
}
/**
* @return Cache ID.
*/
public int getCacheId() {
return cacheId;
}
/**
* @throws IgniteCheckedException If failed.
*/
protected void initNew() throws IgniteCheckedException {
try (Page meta = page(metaPageId)) {
ByteBuffer buf = meta.getForInitialWrite();
BPlusMetaIO io = BPlusMetaIO.VERSIONS.latest();
io.initNewPage(buf, metaPageId);
try (Page root = allocatePage(null)) {
latestLeafIO().initNewPage(root.getForInitialWrite(), root.id());
io.setLevelsCount(buf, 1);
io.setFirstPageId(buf, 0, root.id());
}
}
}
/**
* @return Root level.
*/
private int getRootLevel(Page meta) {
ByteBuffer buf = meta.getForRead();
try {
return BPlusMetaIO.VERSIONS.forPage(buf).getRootLevel(buf);
}
finally {
meta.releaseRead();
}
}
/**
* @param meta Meta page.
* @param lvl Level, if {@code 0} then it is a bottom level, if negative then root.
* @return Page ID.
*/
private long getFirstPageId(Page meta, int lvl) {
ByteBuffer buf = meta.getForRead();
try {
BPlusMetaIO io = BPlusMetaIO.VERSIONS.forPage(buf);
if (lvl < 0)
lvl = io.getRootLevel(buf);
if (lvl >= io.getLevelsCount(buf))
return 0;
return io.getFirstPageId(buf, lvl);
}
finally {
meta.releaseRead();
}
}
/**
* @param upper Upper bound.
* @return Cursor.
*/
private GridCursor<T> findLowerUnbounded(L upper) throws IgniteCheckedException {
ForwardCursor cursor = new ForwardCursor(upper);
long firstPageId;
try (Page meta = page(metaPageId)) {
firstPageId = getFirstPageId(meta, 0); // Level 0 is always at the bottom.
}
try (Page first = page(firstPageId)) {
ByteBuffer buf = first.getForRead();
try {
cursor.bootstrap(buf, 0);
}
finally {
first.releaseRead();
}
}
return cursor;
}
/**
* @param lower Lower bound.
* @param upper Upper bound.
* @return Cursor.
* @throws IgniteCheckedException If failed.
*/
public final GridCursor<T> find(L lower, L upper) throws IgniteCheckedException {
if (lower == null)
return findLowerUnbounded(upper);
GetCursor g = new GetCursor(lower, upper);
doFind(g);
return g.cursor;
}
/**
* @param row Lookup row for exact match.
* @return Found row.
*/
@SuppressWarnings("unchecked")
public final T findOne(L row) throws IgniteCheckedException {
GetOne g = new GetOne(row);
doFind(g);
return (T)g.row;
}
/**
* @param g Get.
*/
private void doFind(Get g) throws IgniteCheckedException {
try {
for (;;) { // Go down with retries.
g.init();
switch (findDown(g, g.rootId, 0L, g.rootLvl)) {
case Get.RETRY:
case Get.RETRY_ROOT:
checkInterrupted();
continue;
default:
return;
}
}
}
finally {
g.releaseMeta();
}
}
/**
* @param g Get.
* @param pageId Page ID.
* @param fwdId Expected forward page ID.
* @param lvl Level.
* @return Result code.
* @throws IgniteCheckedException If failed.
*/
private int findDown(final Get g, final long pageId, final long fwdId, final int lvl)
throws IgniteCheckedException {
Page page = page(pageId);
try {
for (;;) {
// Init args.
g.pageId = pageId;
g.fwdId = fwdId;
int res = readPage(page, search, g, lvl, Get.RETRY);
switch (res) {
case Get.GO_DOWN:
case Get.GO_DOWN_X:
assert g.pageId != pageId;
assert g.fwdId != fwdId || fwdId == 0;
// Go down recursively.
res = findDown(g, g.pageId, g.fwdId, lvl - 1);
switch (res) {
case Get.RETRY:
checkInterrupted();
continue; // The child page got splitted, need to reread our page.
default:
return res;
}
case Get.NOT_FOUND:
assert lvl == 0: lvl;
g.row = null; // Mark not found result.
return res;
default:
return res;
}
}
}
finally {
if (g.canRelease(page, lvl))
page.close();
}
}
/**
* For debug.
*
* @return Tree as {@link String}.
*/
@SuppressWarnings("unused")
public String printTree() {
long rootPageId;
try (Page meta = page(metaPageId)) {
rootPageId = getFirstPageId(meta, -1);
}
catch (IgniteCheckedException e) {
throw new IllegalStateException(e);
}
return treePrinter.print(rootPageId);
}
/**
* @param io IO.
* @param buf Buffer.
* @param keys Keys.
* @return String.
* @throws IgniteCheckedException If failed.
*/
private String printPage(BPlusIO<L> io, ByteBuffer buf, boolean keys) throws IgniteCheckedException {
StringBuilder b = new StringBuilder();
b.append(formatPageId(PageIO.getPageId(buf)));
b.append(" [ ");
b.append(io.isLeaf() ? "L " : "I ");
int cnt = io.getCount(buf);
long fwdId = io.getForward(buf);
b.append("cnt=").append(cnt).append(' ');
b.append("fwd=").append(formatPageId(fwdId)).append(' ');
if (!io.isLeaf()) {
b.append("lm=").append(inner(io).getLeft(buf, 0)).append(' ');
if (cnt > 0)
b.append("rm=").append(inner(io).getRight(buf, cnt - 1)).append(' ');
}
if (keys)
b.append("keys=").append(printPageKeys(io, buf)).append(' ');
b.append(']');
return b.toString();
}
/**
* @param io IO.
* @param buf Buffer.
* @return Keys as String.
* @throws IgniteCheckedException If failed.
*/
private String printPageKeys(BPlusIO<L> io, ByteBuffer buf) throws IgniteCheckedException {
int cnt = io.getCount(buf);
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0; i < cnt; i++) {
if (i != 0)
b.append(',');
b.append(io.canGetRow() ? getRow(io, buf, i) : io.getLookupRow(this, buf, i));
}
b.append(']');
return b.toString();
}
/**
* @param x Long.
* @return String.
*/
private static String formatPageId(long x) {
return Long.toString(x); //'x' + Long.toHexString(x).toUpperCase();
}
/**
* Check if interrupted.
* @throws IgniteInterruptedCheckedException If interrupted.
*/
private static void checkInterrupted() throws IgniteInterruptedCheckedException {
if (Thread.currentThread().isInterrupted())
throw new IgniteInterruptedCheckedException("Interrupted.");
}
/**
* @param row Lookup row.
* @param bag Reuse bag.
* @return Removed row.
* @throws IgniteCheckedException If failed.
*/
public final T removeCeil(L row, ReuseBag bag) throws IgniteCheckedException {
assert row != null;
return doRemove(row, true, bag);
}
/**
* @param row Lookup row.
* @return Removed row.
* @throws IgniteCheckedException If failed.
*/
public final T remove(L row) throws IgniteCheckedException {
assert row != null;
return doRemove(row, false, null);
}
/**
* @param row Lookup row.
* @param ceil If we can remove ceil row when we can not find exact.
* @param bag Reuse bag.
* @return Removed row.
* @throws IgniteCheckedException If failed.
*/
private T doRemove(L row, boolean ceil, ReuseBag bag) throws IgniteCheckedException {
Remove r = new Remove(row, ceil, bag);
try {
for (;;) {
r.init();
switch (removeDown(r, r.rootId, 0L, 0L, r.rootLvl)) {
case Remove.RETRY:
case Remove.RETRY_ROOT:
checkInterrupted();
continue;
default:
if (!r.isFinished())
r.finishTail();
assert r.isFinished();
return r.removed;
}
}
}
finally {
r.releaseTail();
r.releaseMeta();
r.reuseFreePages();
}
}
/**
* @param r Remove operation.
* @param pageId Page ID.
* @param backId Expected backward page ID if we are going to the right.
* @param fwdId Expected forward page ID.
* @param lvl Level.
* @return Result code.
* @throws IgniteCheckedException If failed.
*/
private int removeDown(final Remove r, final long pageId, final long backId, final long fwdId, final int lvl)
throws IgniteCheckedException {
assert lvl >= 0 : lvl;
if (r.isTail(pageId, lvl))
return Remove.FOUND; // We've already locked this page, so return that we are ok.
final Page page = page(pageId);
try {
for (;;) {
// Init args.
r.pageId = pageId;
r.fwdId = fwdId;
r.backId = backId;
int res = readPage(page, search, r, lvl, Remove.RETRY);
switch (res) {
case Remove.GO_DOWN_X:
// We need to get backId here for our page, it must be the last child of our back.
r.backId = getChild(backId, true);
// Intentional fallthrough.
case Remove.GO_DOWN:
res = removeDown(r, r.pageId, r.backId, r.fwdId, lvl - 1);
switch (res) {
case Remove.RETRY:
checkInterrupted();
continue;
case Remove.RETRY_ROOT:
return res;
}
if (!r.isFinished() && !r.finishTail())
return r.lockTail(page, backId, fwdId, lvl);
return res;
case Remove.NOT_FOUND:
// We are at the bottom.
assert lvl == 0: lvl;
if (!r.ceil) {
r.finish();
return res;
}
// Intentional fallthrough for ceiling remove.
case Remove.FOUND:
// We must be at the bottom here, just need to remove row from the current page.
assert lvl == 0 : lvl;
assert r.removed == null;
res = r.removeFromLeaf(page, backId, fwdId);
if (res == Remove.NOT_FOUND) {
assert r.ceil: "must be a retry if not a ceiling remove";
r.finish();
}
else if (res == Remove.FOUND && r.tail == null) {
// Finish if we don't need to do any merges.
r.finish();
}
return res;
default:
return res;
}
}
}
finally {
r.page = null;
if (r.canRelease(page, lvl))
page.close();
}
}
/**
* @param cnt Count.
* @param cap Capacity.
* @return {@code true} If may merge.
*/
private boolean mayMerge(int cnt, int cap) {
int minCnt = (int)(minFill * cap);
if (cnt <= minCnt) {
assert cnt == 0; // TODO remove
return true;
}
assert cnt > 0;
int maxCnt = (int)(maxFill * cap);
if (cnt > maxCnt)
return false;
assert false; // TODO remove
// Randomization is for smoothing worst case scenarios. Probability of merge attempt
// is proportional to free space in our page (discounted on fill factor).
return randomInt(maxCnt - minCnt) >= cnt - minCnt;
}
/**
* @param max Max.
* @return Random value from {@code 0} (inclusive) to the given max value (exclusive).
*/
public int randomInt(int max) {
return ThreadLocalRandom.current().nextInt(max);
}
/**
* @return Root level.
* @throws IgniteCheckedException If failed.
*/
public final int rootLevel() throws IgniteCheckedException {
try (Page meta = page(metaPageId)) {
return getRootLevel(meta);
}
}
/**
* TODO may produce wrong results on concurrent access
*
* @return Size.
* @throws IgniteCheckedException If failed.
*/
public final long size() throws IgniteCheckedException {
long cnt = 0;
long pageId;
try (Page meta = page(metaPageId)) {
pageId = getFirstPageId(meta, 0); // Level 0 is always at the bottom.
}
BPlusIO<L> io = null;
while (pageId != 0) {
try (Page page = page(pageId)) {
ByteBuffer buf = page.getForRead();
try {
if (io == null) {
io = io(buf);
assert io.isLeaf();
}
cnt += io.getCount(buf);
pageId = io.getForward(buf);
}
finally {
page.releaseRead();
}
}
}
return cnt;
}
/**
* @param row Row.
* @return Old row.
* @throws IgniteCheckedException If failed.
*/
public final T put(T row) throws IgniteCheckedException {
return put(row, null);
}
/**
* @param row Row.
* @param bag Reuse bag.
* @return Old row.
* @throws IgniteCheckedException If failed.
*/
public final T put(T row, ReuseBag bag) throws IgniteCheckedException {
Put p = new Put(row, bag);
try {
for (;;) { // Go down with retries.
p.init();
switch (putDown(p, p.rootId, 0L, p.rootLvl)) {
case Put.RETRY:
case Put.RETRY_ROOT:
checkInterrupted();
continue;
default:
assert p.isFinished();
return p.oldRow;
}
}
}
finally {
p.releaseMeta();
}
}
/**
* @param io IO.
* @param buf Splitting buffer.
* @param fwdBuf Forward buffer.
* @param idx Insertion index.
* @return {@code true} The middle index was shifted to the right.
* @throws IgniteCheckedException If failed.
*/
private boolean splitPage(BPlusIO io, ByteBuffer buf, ByteBuffer fwdBuf, int idx)
throws IgniteCheckedException {
int cnt = io.getCount(buf);
int mid = cnt >>> 1;
boolean res = false;
if (idx > mid) { // If insertion is going to be to the forward page, keep more in the back page.
mid++;
res = true;
}
cnt -= mid;
io.copyItems(buf, fwdBuf, mid, 0, cnt, true);
// Setup counts.
io.setCount(fwdBuf, cnt);
io.setCount(buf, mid);
// Setup forward-backward refs.
io.setForward(fwdBuf, io.getForward(buf));
io.setForward(buf, PageIO.getPageId(fwdBuf));
return res;
}
/**
* @param io IO.
* @param buf Buffer.
* @param row Row.
* @param idx Index.
* @param rightId Right page ID.
* @throws IgniteCheckedException If failed.
*/
private void insertSimple(BPlusIO<L> io, ByteBuffer buf, L row, int idx, long rightId)
throws IgniteCheckedException {
int cnt = io.getCount(buf);
// Move right all the greater elements to make a free slot for a new row link.
io.copyItems(buf, buf, idx, idx + 1, cnt - idx, false);
io.setCount(buf, cnt + 1);
io.store(buf, idx, row);
if (!io.isLeaf()) // Setup reference to the right page on split.
inner(io).setRight(buf, idx, rightId);
}
/**
* @param bag Reuse bag.
* @param meta Meta page.
* @param io IO.
* @param buf Buffer.
* @param row Row.
* @param idx Index.
* @param rightId Right page ID after split.
* @param lvl Level.
* @return Move up row.
* @throws IgniteCheckedException If failed.
*/
private L insertWithSplit(ReuseBag bag, Page meta, BPlusIO<L> io, final ByteBuffer buf, L row,
int idx, long rightId, int lvl) throws IgniteCheckedException {
try (Page fwd = allocatePage(bag)) {
// Need to check this before the actual split, because after the split we will have new forward page here.
boolean hadFwd = io.getForward(buf) != 0;
ByteBuffer fwdBuf = fwd.getForInitialWrite();
io.initNewPage(fwdBuf, fwd.id());
boolean midShift = splitPage(io, buf, fwdBuf, idx);
// Do insert.
int cnt = io.getCount(buf);
if (idx < cnt || (idx == cnt && !midShift)) { // Insert into back page.
insertSimple(io, buf, row, idx, rightId);
// Fix leftmost child of forward page, because newly inserted row will go up.
if (idx == cnt && !io.isLeaf())
inner(io).setLeft(fwdBuf, 0, rightId);
}
else // Insert into newly allocated forward page.
insertSimple(io, fwdBuf, row, idx - cnt, rightId);
// Do move up.
cnt = io.getCount(buf);
L moveUpRow = io.getLookupRow(this, buf, cnt - 1); // Last item from backward row goes up.
if (!io.isLeaf()) // Leaf pages must contain all the links, inner pages remove moveUpLink.
io.setCount(buf, cnt - 1);
if (!hadFwd && lvl == getRootLevel(meta)) { // We are splitting root.
long newRootId;
try (Page newRoot = allocatePage(bag)) {
newRootId = newRoot.id();
if (io.isLeaf())
io = latestInnerIO();
ByteBuffer newRootBuf = newRoot.getForInitialWrite();
io.initNewPage(newRootBuf, newRoot.id());
io.setCount(newRootBuf, 1);
inner(io).setLeft(newRootBuf, 0, PageIO.getPageId(buf));
io.store(newRootBuf, 0, moveUpRow);
inner(io).setRight(newRootBuf, 0, fwd.id());
}
int res = writePage(meta, newRoot, newRootId, lvl + 1, FALSE);
assert res == TRUE : "failed to update meta page";
return null; // We've just moved link up to root, nothing to return here.
}
// Regular split.
return moveUpRow;
}
}
/**
* @param bag Reuse bag.
* @param meta Meta page.
* @param io IO.
* @param buf Buffer.
* @param row Row.
* @param idx Index.
* @param rightId Right ID.
* @param lvl Level.
* @return Move up row.
* @throws IgniteCheckedException If failed.
*/
private L insert(ReuseBag bag, Page meta, BPlusIO<L> io, ByteBuffer buf, L row, int idx, long rightId, int lvl)
throws IgniteCheckedException {
int maxCnt = io.getMaxCount(buf);
int cnt = io.getCount(buf);
if (cnt == maxCnt) // Need to split page.
return insertWithSplit(bag, meta, io, buf, row, idx, rightId, lvl);
insertSimple(io, buf, row, idx, rightId);
return null;
}
/**
* @param page Page.
*/
private static void writeUnlockAndClose(Page page) {
assert page != null;
try {
page.releaseWrite(true);
}
finally {
page.close();
}
}
/**
* @param pageId Inner page ID.
* @param last If {@code true}, then get the last, else get the first child page.
* @return Child page ID.
*/
private long getChild(long pageId, boolean last) throws IgniteCheckedException {
try (Page page = page(pageId)) {
assert page != null : "we've locked back page, forward can't be merged";
ByteBuffer buf = page.getForRead();
try {
BPlusIO<L> io = io(buf);
// Count can be 0 here if it is a routing page, in this case we have single child.
int idx = last ? io.getCount(buf) : 0;
// getLeft(cnt) is the same as getRight(cnt - 1)
long res = inner(io).getLeft(buf, idx);
assert res != 0: "inner page with no route down: " + page.fullId();
return res;
}
finally {
page.releaseRead();
}
}
}
/**
* @param p Put.
* @param pageId Page ID.
* @param fwdId Expected forward page ID.
* @param lvl Level.
* @return Result code.
* @throws IgniteCheckedException If failed.
*/
private int putDown(final Put p, final long pageId, final long fwdId, final int lvl)
throws IgniteCheckedException {
assert lvl >= 0 : lvl;
final Page page = page(pageId);
try {
for (;;) {
// Init args.
p.pageId = pageId;
p.fwdId = fwdId;
int res = readPage(page, search, p, lvl, Put.RETRY);
switch (res) {
case Put.GO_DOWN:
case Put.GO_DOWN_X:
assert lvl > 0 : lvl;
assert p.pageId != pageId;
assert p.fwdId != fwdId || fwdId == 0;
// Need to replace key in inner page. There is no race because we keep tail lock after split.
if (p.needReplaceInner == TRUE) {
p.needReplaceInner = FALSE; // Protect from retries.
res = writePage(page, replace, p, lvl, Put.RETRY);
if (res != Put.FOUND)
return res; // Need to retry.
p.needReplaceInner = DONE; // We can have only single matching inner key.
}
// Go down recursively.
res = putDown(p, p.pageId, p.fwdId, lvl - 1);
if (res == Put.RETRY_ROOT || p.isFinished())
return res;
if (res == Put.RETRY)
checkInterrupted();
continue; // We have to insert split row to this level or it is a retry.
case Put.FOUND: // Do replace.
assert lvl == 0 : "This replace can happen only at the bottom level.";
// Init args.
p.pageId = pageId;
p.fwdId = fwdId;
return writePage(page, replace, p, lvl, Put.RETRY);
case Put.NOT_FOUND: // Do insert.
assert lvl == p.btmLvl : "must insert at the bottom level";
assert p.needReplaceInner == FALSE: p.needReplaceInner + " " + lvl;
// Init args.
p.pageId = pageId;
p.fwdId = fwdId;
return writePage(page, insert, p, lvl, Put.RETRY);
default:
return res;
}
}
}
finally{
if (p.canRelease(page, lvl))
page.close();
}
}
/**
* Get operation.
*/
private abstract class Get {
/** */
static final int GO_DOWN = 1;
/** */
static final int GO_DOWN_X = 2;
/** */
static final int FOUND = 5;
/** */
static final int NOT_FOUND = 6;
/** */
static final int RETRY = 8;
/** */
static final int RETRY_ROOT = 9;
/** */
long rmvId;
/** Starting point root level. May be outdated. Must be modified only in {@link Get#init()}. */
int rootLvl;
/** Starting point root ID. May be outdated. Must be modified only in {@link Get#init()}. */
long rootId;
/** Meta page. Initialized by {@link Get#init()}, released by {@link Get#releaseMeta()}. */
Page meta;
/** */
L row;
/** In/Out parameter: Page ID. */
long pageId;
/** In/Out parameter: expected forward page ID. */
long fwdId;
/** In/Out parameter: in case of right turn this field will contain backward page ID for the child. */
long backId;
/**
* @param row Row.
*/
public Get(L row) {
assert row != null;
this.row = row;
}
/**
* Initialize operation.
*
* !!! Symmetrically with this method must be called {@link Get#releaseMeta()} in {@code finally} block.
*
* @throws IgniteCheckedException If failed.
*/
final void init() throws IgniteCheckedException {
if (meta == null)
meta = page(metaPageId);
int rootLvl;
long rootId;
ByteBuffer buf = meta.getForRead();
try {
BPlusMetaIO io = BPlusMetaIO.VERSIONS.forPage(buf);
rootLvl = io.getRootLevel(buf);
rootId = io.getFirstPageId(buf, rootLvl);
}
finally {
meta.releaseRead();
}
restartFromRoot(rootId, rootLvl, globalRmvId.get());
}
/**
* @param rootId Root page ID.
* @param rootLvl Root level.
* @param rmvId Remove ID to be afraid of.
*/
final void restartFromRoot(long rootId, int rootLvl, long rmvId) {
this.rootId = rootId;
this.rootLvl = rootLvl;
this.rmvId = rmvId;
}
/**
* @param io IO.
* @param buf Buffer.
* @param idx Index of found entry.
* @param lvl Level.
* @return {@code true} If we need to stop.
* @throws IgniteCheckedException If failed.
*/
abstract boolean found(BPlusIO<L> io, ByteBuffer buf, int idx, int lvl) throws IgniteCheckedException;
/**
* @param io IO.
* @param buf Buffer.
* @param idx Insertion point.
* @param lvl Level.
* @return {@code true} If we need to stop.
* @throws IgniteCheckedException If failed.
*/
boolean notFound(BPlusIO<L> io, ByteBuffer buf, int idx, int lvl) throws IgniteCheckedException {
assert lvl >= 0;
return lvl == 0; // We are not at the bottom.
}
/**
* Release meta page.
*/
final void releaseMeta() {
if (meta != null) {
meta.close();
meta = null;
}
}
/**
* @param page Page.
* @param lvl Level.
* @return {@code true} If we can release the given page.
*/
boolean canRelease(Page page, int lvl) {
return page != null;
}
}
/**
* Get a single entry.
*/
private final class GetOne extends Get {
/**
* @param row Row.
*/
private GetOne(L row) {
super(row);
}
/** {@inheritDoc} */
@Override boolean found(BPlusIO<L> io, ByteBuffer buf, int idx, int lvl) throws IgniteCheckedException {
if (!io.canGetRow()) {
assert !io.isLeaf();
return false;
}
row = getRow(io, buf, idx);
return true;
}
}
/**
* Get a cursor for range.
*/
private final class GetCursor extends Get {
/** */
ForwardCursor cursor;
/**
* @param lower Lower bound.
* @param upper Upper bound.
*/
private GetCursor(L lower, L upper) {
super(lower);
cursor = new ForwardCursor(upper);
}
/** {@inheritDoc} */
@Override boolean found(BPlusIO<L> io, ByteBuffer buf, int idx, int lvl) throws IgniteCheckedException {
if (!io.isLeaf())
return false;
cursor.bootstrap(buf, idx);
return true;
}
/** {@inheritDoc} */
@Override boolean notFound(BPlusIO<L> io, ByteBuffer buf, int idx, int lvl) throws IgniteCheckedException {
assert lvl >= 0 : lvl;
if (lvl != 0)
return false;
assert io.isLeaf();
cursor.bootstrap(buf, idx);
return true;
}
}
/**
* Put operation.
*/
private final class Put extends Get {
/** Right child page ID for split row. */
long rightId;
/** Replaced row if any. */
T oldRow;
/**
* This page is kept locked after split until insert to the upper level will not be finished.
* It is needed because split row will be "in flight" and if we'll release tail, remove on
* split row may fail.
*/
Page tail;
/**
* Bottom level for insertion (insert can't go deeper). Will be incremented on split on each level.
*/
short btmLvl;
/** */
byte needReplaceInner = FALSE;
/** */
ReuseBag bag;
/**
* @param row Row.
* @param bag Reuse bag.
*/
private Put(T row, ReuseBag bag) {
super(row);
this.bag = bag;
}
/** {@inheritDoc} */
@Override boolean found(BPlusIO<L> io, ByteBuffer buf, int idx, int lvl) throws IgniteCheckedException {
if (io.isLeaf())
return true;
// If we can get full row from the inner page, we must do inner replace to update full row info here.
if (io.canGetRow() && needReplaceInner == FALSE)
needReplaceInner = TRUE;
return false;
}
/** {@inheritDoc} */
@Override boolean notFound(BPlusIO<L> io, ByteBuffer buf, int idx, int lvl) throws IgniteCheckedException {
assert btmLvl >= 0 : btmLvl;
assert lvl >= btmLvl : lvl;
return lvl == btmLvl;
}
/**
* @param tail Tail lock.
*/
private void tail(Page tail) {
if (this.tail != null)
writeUnlockAndClose(this.tail);
this.tail = tail;
}
/** {@inheritDoc} */
@Override boolean canRelease(Page page, int lvl) {
return page != null && tail != page;
}
/**
* Finish put.
*/
private void finish() {
row = null;
rightId = 0;
tail(null);
}
/**
* @return {@code true} If finished.
*/
private boolean isFinished() {
return row == null;
}
}
/**
* Remove operation.
*/
private final class Remove extends Get implements ReuseBag {
/** */
boolean ceil;
/** We may need to lock part of the tree branch from the bottom to up for multiple levels. */
Tail<L> tail;
/** */
byte needReplaceInner = FALSE;
/** */
byte needMergeEmptyBranch = FALSE;
/** Removed row. */
T removed;
/** Current page. */
Page page;
/** */
short innerIdx = Short.MIN_VALUE;
/** */
Object freePages;
/** */
ReuseBag bag;
/**
* @param row Row.
* @param ceil If we can remove ceil row when we can not find exact.
*/
private Remove(L row, boolean ceil, ReuseBag bag) {
super(row);
this.ceil = ceil;
this.bag = bag;
}
/**
* @return Reuse bag.
*/
private ReuseBag bag() {
return bag != null ? bag : this;
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public FullPageId pollFreePage() {
assert bag == null;
if (freePages == null)
return null;
if (freePages.getClass() == ArrayDeque.class)
return ((ArrayDeque<FullPageId>)freePages).poll();
FullPageId res = (FullPageId)freePages;
freePages = null;
return res;
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public void addFreePage(FullPageId pageId) {
assert pageId != null;
assert bag == null;
if (freePages == null)
freePages = pageId;
else {
ArrayDeque<Object> queue;
if (freePages.getClass() == ArrayDeque.class)
queue = (ArrayDeque<Object>)freePages;
else {
assert freePages instanceof FullPageId;
queue = new ArrayDeque<>();
queue.add(freePages);
freePages = queue;
}
queue.add(pageId);
}
}
/** {@inheritDoc} */
@Override boolean found(BPlusIO<L> io, ByteBuffer buf, int idx, int lvl) throws IgniteCheckedException {
if (io.isLeaf())
return true;
// If we can get full row from the inner page, we must do inner replace to update full row info here.
if (io.canGetRow() && needReplaceInner == FALSE)
needReplaceInner = TRUE;
return false;
}
/** {@inheritDoc} */
@Override boolean notFound(BPlusIO<L> io, ByteBuffer buf, int idx, int lvl) throws IgniteCheckedException {
if (io.isLeaf()) {
assert tail == null;
return true;
}
return false;
}
/**
* Finish the operation.
*/
private void finish() {
assert tail == null;
row = null;
}
/**
* @throws IgniteCheckedException If failed.
*/
private void mergeEmptyBranch() throws IgniteCheckedException {
assert needMergeEmptyBranch == TRUE;
Tail<L> t = tail;
assert t.getCount() > 0;
// Find empty branch beginning.
for (Tail<L> t0 = t.down; t0 != null; t0 = t0.down) {
assert t0.type == Tail.EXACT: t0.type;
if (t0.getCount() != 0)
t = t0;
}
while (t.lvl != 0) { // If we've found empty branch, merge it top down.
boolean res = merge(t);
assert res: needMergeEmptyBranch;
if (needMergeEmptyBranch == TRUE)
needMergeEmptyBranch = READY; // Need to mark that we've already done the first iteration.
t = t.down;
}
assert t.lvl == 0: t.lvl;
}
/**
* @param t Tail.
* @return {@code true} If merged successfully or end reached.
* @throws IgniteCheckedException If failed.
*/
private boolean mergeBottomUp(Tail<L> t) throws IgniteCheckedException {
assert needMergeEmptyBranch == FALSE || needMergeEmptyBranch == DONE: needMergeEmptyBranch;
if (t.down == null)
return true;
if (t.down.sibling == null) // We've merged something there.
return false;
return mergeBottomUp(t.down) && merge(t);
}
/**
* Process tail and finish.
*
* @return {@code false} If failed to finish and we need to lock more pages up.
* @throws IgniteCheckedException If failed.
*/
private boolean finishTail() throws IgniteCheckedException {
assert !isFinished();
assert tail.type == Tail.EXACT;
boolean mergedBranch = false;
if (needMergeEmptyBranch == TRUE) {
// We can't merge empty branch if tail in routing page.
if (tail.down == null || tail.getCount() == 0)
return false; // Lock the whole branch up to the first non-empty.
mergeEmptyBranch();
mergedBranch = true;
needMergeEmptyBranch = DONE;
}
mergeBottomUp(tail);
if (needReplaceInner == READY) {
// If we've merged empty branch right now, then the inner key was dropped.
if (!mergedBranch)
replaceInner(); // Replace inner key with new max key for the left subtree.
needReplaceInner = DONE;
}
else if (needReplaceInner == TRUE)
return false; // Lock the whole branch up to the inner key page.
if (tail.getCount() == 0 && tail.lvl != 0 && getRootLevel(meta) == tail.lvl) {
// Free root if it became empty after merge.
freePage(tail.page, tail.buf, tail.io, tail.lvl, false);
}
else if (tail.sibling != null && tail.getCount() + tail.sibling.getCount() < tail.io.getMaxCount(tail.buf)) {
// Release everything lower than tail, we've already merged this path.
doReleaseTail(tail.down);
tail.down = null;
return false; // Lock and merge one level more.
}
releaseTail();
finish();
return true;
}
/**
* @param leaf Leaf page.
* @param backId Back page ID.
* @param fwdId Forward ID.
* @return Result code.
* @throws IgniteCheckedException If failed.
*/
private int removeFromLeaf(Page leaf, long backId, long fwdId) throws IgniteCheckedException {
// Init parameters.
this.pageId = leaf.id();
this.page = leaf;
this.backId = backId;
this.fwdId = fwdId;
if (backId == 0)
return doRemoveFromLeaf();
// Lock back page before the remove, we'll need it for merges.
Page back = page(backId);
try {
return writePage(back, lockBackAndRemoveFromLeaf, this, 0, Remove.RETRY);
}
finally {
if (canRelease(back, 0))
back.close();
}
}
/**
* @return Result code.
* @throws IgniteCheckedException If failed.
*/
private int doRemoveFromLeaf() throws IgniteCheckedException {
assert page != null;
return writePage(page, removeFromLeaf, this, 0, Remove.RETRY);
}
/**
* @param lvl Level.
* @return Result code.
* @throws IgniteCheckedException If failed.
*/
private int doLockTail(int lvl) throws IgniteCheckedException {
assert page != null;
return writePage(page, lockTail, this, lvl, Remove.RETRY);
}
/**
* @param page Page.
* @param backId Back page ID.
* @param fwdId Expected forward page ID.
* @param lvl Level.
* @return Result code.
* @throws IgniteCheckedException If failed.
*/
private int lockTail(Page page, long backId, long fwdId, int lvl) throws IgniteCheckedException {
assert tail != null;
// Init parameters for the handlers.
this.pageId = page.id();
this.page = page;
this.fwdId = fwdId;
this.backId = backId;
if (backId == 0) // Back page ID is provided only when the last move was to the right.
return doLockTail(lvl);
Page back = page(backId);
try {
return writePage(back, lockBackAndTail, this, lvl, Remove.RETRY);
}
finally {
if (canRelease(back, lvl))
back.close();
}
}
/**
* @param lvl Level.
* @throws IgniteCheckedException If failed.
*/
private void lockForward(int lvl) throws IgniteCheckedException {
assert fwdId != 0;
assert backId == 0;
int res = writePage(page(fwdId), lockTailForward, this, lvl, Remove.RETRY);
// Must always be called from lock on back page, thus we should never fail here.
assert res == Remove.FOUND: res;
}
/**
* @param io IO.
* @param buf Buffer.
* @param cnt Count.
* @param idx Index to remove.
* @throws IgniteCheckedException If failed.
*/
private void doRemove(BPlusIO io, ByteBuffer buf, int cnt, int idx)
throws IgniteCheckedException {
assert cnt > 0: cnt;
assert idx >= 0 && idx < cnt: idx + " " + cnt;
cnt--;
io.copyItems(buf, buf, idx + 1, idx, cnt - idx, false);
io.setCount(buf, cnt);
}
/**
* @param prnt Parent tail.
* @param left Left child tail.
* @param right Right child tail.
* @return {@code true} If merged successfully.
* @throws IgniteCheckedException If failed.
*/
private boolean doMerge(Tail<L> prnt, Tail<L> left, Tail<L> right)
throws IgniteCheckedException {
assert right.io == left.io; // Otherwise incompatible.
assert left.io.getForward(left.buf) == right.page.id();
int prntCnt = prnt.getCount();
int leftCnt = left.getCount();
int rightCnt = right.getCount();
assert prntCnt > 0 || needMergeEmptyBranch == READY: prntCnt;
int newCnt = leftCnt + rightCnt;
boolean emptyBranch = needMergeEmptyBranch == TRUE || needMergeEmptyBranch == READY;
// Need to move down split key in inner pages. For empty branch merge parent key will be just dropped.
if (left.lvl != 0 && !emptyBranch)
newCnt++;
if (newCnt > left.io.getMaxCount(left.buf)) {
assert !emptyBranch;
return false;
}
left.io.setCount(left.buf, newCnt);
// Move down split key in inner pages.
if (left.lvl != 0 && !emptyBranch) {
int prntIdx = prnt.idx;
if (prntIdx == prntCnt) // It was a right turn.
prntIdx--;
// We can be sure that we have enough free space to store split key here,
// because we've done remove already and did not release child locks.
left.io.store(left.buf, leftCnt, prnt.io, prnt.buf, prntIdx);
leftCnt++;
}
left.io.copyItems(right.buf, left.buf, 0, leftCnt, rightCnt, !emptyBranch);
left.io.setForward(left.buf, right.io.getForward(right.buf));
// Fix index for the right move: remove last item.
int prntIdx = prnt.idx == prntCnt ? prntCnt - 1 : prnt.idx;
// Remove split key from parent. If we ar emerging empty branch then remove only on the top iteration.
if (needMergeEmptyBranch != READY)
doRemove(prnt.io, prnt.buf, prntCnt, prntIdx);
// Forward page is now empty and has no links, can free and release it right away.
freePage(right.page, right.buf, right.io, right.lvl, true);
return true;
}
/**
* @param page Page.
* @param buf Buffer.
* @param io IO.
* @param lvl Level.
* @param release Release write lock and release page.
* @throws IgniteCheckedException If failed.
*/
@SuppressWarnings("unchecked")
private void freePage(Page page, ByteBuffer buf, BPlusIO io, int lvl, boolean release)
throws IgniteCheckedException {
if (getFirstPageId(meta, lvl) == page.id()) {
// This logic will handle root as well.
long fwdId = io.getForward(buf);
writePage(meta, updateFirst, fwdId, lvl, FALSE);
}
// Mark removed.
io.setRemoveId(buf, Long.MAX_VALUE);
if (release)
writeUnlockAndClose(page);
bag().addFreePage(page.fullId());
}
/**
* @throws IgniteCheckedException If failed.
*/
@SuppressWarnings("unchecked")
private void reuseFreePages() throws IgniteCheckedException {
// If we have a bag, then it will be processed at the upper level.
if (reuseList != null && bag == null)
reuseList.add(BPlusTree.this, this);
}
/**
* @throws IgniteCheckedException If failed.
*/
private void replaceInner() throws IgniteCheckedException {
assert needReplaceInner == READY: needReplaceInner;
assert tail.lvl > 0: "leaf";
assert innerIdx >= 0: innerIdx;
Tail<L> leaf = getTail(0);
Tail<L> inner = tail;
assert inner.type == Tail.EXACT: inner.type;
int innerCnt = inner.getCount();
int leafCnt = leaf.getCount();
assert leafCnt > 0: leafCnt; // Leaf must be merged at this point already if it was empty.
if (innerIdx < innerCnt) {
// Update inner key with the new biggest key of left subtree.
inner.io.store(inner.buf, innerIdx, leaf.io, leaf.buf, leafCnt - 1);
leaf.io.setRemoveId(leaf.buf, globalRmvId.get());
}
else {
// If after leaf merge parent have lost inner key, we don't need to update it anymore.
assert innerIdx == innerCnt;
assert inner(inner.io).getLeft(inner.buf, innerIdx) == leaf.page.id();
}
}
/**
* @param prnt Parent for merge.
* @return {@code true} If merged, {@code false} if not (because of insufficient space or empty parent).
* @throws IgniteCheckedException If failed.
*/
private boolean merge(Tail<L> prnt) throws IgniteCheckedException {
// If we are merging empty branch this is acceptable because even if we merge
// two routing pages, one of them is effectively dropped in this merge, so just
// keep a single routing page.
if (prnt.getCount() == 0 && needMergeEmptyBranch != READY)
return false; // Parent is an empty routing page, child forward page will have another parent.
Tail<L> right = prnt.down;
Tail<L> left = right.sibling;
assert right.type == Tail.EXACT;
assert left != null: "we must have a partner to merge with";
if (left.type != Tail.BACK) { // Flip if it was actually FORWARD but not BACK.
assert left.type == Tail.FORWARD: left.type;
left = right;
right = right.sibling;
}
assert right.io == left.io: "must always be the same"; // Otherwise can be not compatible.
if (!doMerge(prnt, left, right))
return false;
// left from BACK becomes EXACT.
if (left.type == Tail.BACK) {
assert left.sibling == null;
left.down = right.down;
left.type = Tail.EXACT;
prnt.down = left;
}
else { // left is already EXACT.
assert left.type == Tail.EXACT: left.type;
left.sibling = null;
}
return true;
}
/**
* @return {@code true} If finished.
*/
private boolean isFinished() {
return row == null;
}
/**
* Release pages for all locked levels at the tail.
*/
private void releaseTail() {
doReleaseTail(tail);
tail = null;
}
/**
* @param t Tail.
*/
private void doReleaseTail(Tail<L> t) {
while (t != null) {
writeUnlockAndClose(t.page);
if (t.sibling != null)
writeUnlockAndClose(t.sibling.page);
t = t.down;
}
}
/** {@inheritDoc} */
@Override boolean canRelease(Page page, int lvl) {
return page != null && !isTail(page.id(), lvl);
}
/**
* @param pageId Page ID.
* @param lvl Level.
* @return {@code true} If the given page is in tail.
*/
private boolean isTail(long pageId, int lvl) {
Tail t = tail;
while (t != null) {
if (t.lvl < lvl)
return false;
if (t.lvl == lvl) {
if (t.page.id() == pageId)
return true;
t = t.sibling;
return t != null && t.page.id() == pageId;
}
t = t.down;
}
return false;
}
/**
* @param page Page.
* @param buf Buffer.
* @param io IO.
* @param lvl Level.
* @param type Type.
* @param idx Insertion index or negative flag describing if the page is primary in this tail branch.
*/
private void addTail(Page page, ByteBuffer buf, BPlusIO<L> io, int lvl, byte type, int idx) {
Tail<L> t = new Tail<>(page, buf, io, type, lvl, idx);
if (tail == null)
tail = t;
else if (tail.lvl == lvl) { // Add on the same level.
assert tail.sibling == null; // Only two siblings on a single level.
if (type == Tail.EXACT) {
assert tail.type != Tail.EXACT;
if (tail.down != null) { // Take down from sibling, EXACT must own down link.
t.down = tail.down;
tail.down = null;
}
t.sibling = tail;
tail = t;
}
else {
assert tail.type == Tail.EXACT: tail.type;
tail.sibling = t;
}
}
else if (tail.lvl == lvl - 1) { // Add on top of existing level.
t.down = tail;
tail = t;
}
else
throw new IllegalStateException();
}
/**
* @param lvl Level.
* @return Tail of {@link Tail#EXACT} type at the given level.
*/
private Tail<L> getTail(int lvl) {
assert tail != null;
assert lvl >= 0 && lvl <= tail.lvl: lvl;
Tail<L> t = tail;
while (t.lvl != lvl)
t = t.down;
assert t.type == Tail.EXACT: t.type; // All the down links must be of EXACT type.
return t;
}
}
/**
* Tail for remove.
*/
private static class Tail<L> {
/** */
static final byte BACK = 0;
/** */
static final byte EXACT = 1;
/** */
static final byte FORWARD = 2;
/** */
final Page page;
/** */
final ByteBuffer buf;
/** */
final BPlusIO<L> io;
/** */
byte type;
/** */
final byte lvl;
/** */
final short idx;
/** Only {@link #EXACT} tail can have either {@link #BACK} or {@link #FORWARD} sibling.*/
Tail<L> sibling;
/** Only {@link #EXACT} tail can point to {@link #EXACT} tail of lower level. */
Tail<L> down;
/**
* @param page Write locked page.
* @param buf Buffer.
* @param io IO.
* @param type Type.
* @param lvl Level.
* @param idx Insertion index.
*/
private Tail(Page page, ByteBuffer buf, BPlusIO<L> io, byte type, int lvl, int idx) {
assert type == BACK || type == EXACT || type == FORWARD: type;
assert idx == -1 || (idx >= 0 && idx <= Short.MAX_VALUE): idx ;
assert lvl >= 0 && lvl <= Byte.MAX_VALUE: lvl;
assert page != null;
this.page = page;
this.buf = buf;
this.io = io;
this.type = type;
this.lvl = (byte)lvl;
this.idx = (short)idx;
}
/**
* @return Count.
*/
private int getCount() {
return io.getCount(buf);
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(Tail.class, this, "pageId", page.id(), "cnt", getCount(), "lvl", lvl, "sibling", sibling);
}
}
/**
* @param io IO.
* @param buf Buffer.
* @param cnt Row count.
* @param row Lookup row.
* @return Insertion point as in {@link Arrays#binarySearch(Object[], Object, Comparator)}.
*/
private int findInsertionPoint(BPlusIO<L> io, ByteBuffer buf, int cnt, L row)
throws IgniteCheckedException {
assert row != null;
int low = 0;
int high = cnt - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
int cmp = compare(io, buf, mid, row);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid; // found
}
return -(low + 1); // not found
}
/**
* @param buf Buffer.
* @return IO.
*/
private BPlusIO<L> io(ByteBuffer buf) {
assert buf != null;
int type = PageIO.getType(buf);
int ver = PageIO.getVersion(buf);
return io(type, ver);
}
/**
* @param io IO.
* @return Inner page IO.
*/
private static <L> BPlusInnerIO<L> inner(BPlusIO<L> io) {
assert !io.isLeaf();
return (BPlusInnerIO<L>)io;
}
/**
* @param pageId Page ID.
* @return Page.
* @throws IgniteCheckedException If failed.
*/
private Page page(long pageId) throws IgniteCheckedException {
return pageMem.page(new FullPageId(pageId, cacheId));
}
/**
* @param bag Reuse bag.
* @return Allocated page.
*/
private Page allocatePage(ReuseBag bag) throws IgniteCheckedException {
FullPageId pageId = bag != null ? bag.pollFreePage() : null;
if (pageId == null && reuseList != null)
pageId = reuseList.take(this, bag);
if (pageId == null)
pageId = pageMem.allocatePage(cacheId, -1, PageIdAllocator.FLAG_IDX);
return pageMem.page(pageId);
}
/**
* @param type Page type.
* @param ver Page version.
* @return IO.
*/
protected abstract BPlusIO<L> io(int type, int ver);
/**
* @return Latest version of inner page IO.
*/
protected abstract BPlusInnerIO<L> latestInnerIO();
/**
* @return Latest version of leaf page IO.
*/
protected abstract BPlusLeafIO<L> latestLeafIO();
/**
* @param buf Buffer.
* @param idx Index of row in the given buffer.
* @param row Lookup row.
* @return Comparison result as in {@link Comparator#compare(Object, Object)}.
* @throws IgniteCheckedException If failed.
*/
protected abstract int compare(BPlusIO<L> io, ByteBuffer buf, int idx, L row) throws IgniteCheckedException;
/**
* This method can be called only if {@link BPlusIO#canGetRow()} returns {@code true}.
*
* @param io IO.
* @param buf Buffer.
* @param idx Index.
* @return Full data row.
* @throws IgniteCheckedException If failed.
*/
protected abstract T getRow(BPlusIO<L> io, ByteBuffer buf, int idx) throws IgniteCheckedException;
/**
* Forward cursor.
*/
protected class ForwardCursor implements GridCursor<T> {
/** */
private List<T> rows;
/** */
private int row;
/** */
private Page page;
/** */
private ByteBuffer buf;
/** */
private final L upperBound;
/**
* @param upperBound Upper bound.
*/
protected ForwardCursor(L upperBound) {
this.upperBound = upperBound;
}
/**
* @param buf Buffer.
* @param startIdx Start index.
*/
void bootstrap(ByteBuffer buf, int startIdx) throws IgniteCheckedException {
assert buf != null;
row = -1;
this.buf = buf;
fillFromBuffer(startIdx);
}
/**
* @param startIdx Start index.
*/
private boolean fillFromBuffer(int startIdx) throws IgniteCheckedException {
if (buf == null)
return false;
for (;;) {
BPlusIO<L> io = io(buf);
assert io.isLeaf();
assert io.canGetRow();
int cnt = io.getCount(buf);
long fwdId = io.getForward(buf);
if (cnt > 0) {
if (upperBound != null) {
int cmp = compare(io, buf, cnt - 1, upperBound);
if (cmp > 0) {
cnt = findInsertionPoint(io, buf, cnt, upperBound) + 1;
fwdId = 0; // The End.
}
}
}
if (cnt > startIdx) {
if (rows == null)
rows = new ArrayList<>();
for (int i = startIdx; i < cnt; i++)
rows.add(getRow(io, buf, i));
}
Page prevPage = page;
if (fwdId != 0) { // Lock next page.
page = page(fwdId);
buf = page.getForRead();
}
else { // Clear.
page = null;
buf = null;
}
if (prevPage != null) { // Release previous page.
try {
prevPage.releaseRead();
}
finally {
prevPage.close();
}
}
if (F.isEmpty(rows)) {
if (buf == null)
return false;
continue;
}
return true;
}
}
/** {@inheritDoc} */
@Override public boolean next() throws IgniteCheckedException {
if (rows == null)
return false;
if (++row < rows.size())
return true;
row = 0;
rows.clear();
return fillFromBuffer(0);
}
/** {@inheritDoc} */
@Override public T get() {
return rows.get(row);
}
}
/**
* Page handler for basic {@link Get} operation.
*/
private abstract class GetPageHandler<G extends Get> extends PageHandler<G> {
/** {@inheritDoc} */
@Override public final int run(Page page, ByteBuffer buf, G g, int lvl) throws IgniteCheckedException {
BPlusIO<L> io = io(buf);
// In case of intersection with inner replace remove operation
// we need to restart our operation from the root.
if (g.rmvId < io.getRemoveId(buf))
return Get.RETRY_ROOT;
return run0(page, buf, io, g, lvl);
}
/**
* @param page Page.
* @param buf Buffer.
* @param io IO.
* @param g Operation.
* @param lvl Level.
* @return Result code.
* @throws IgniteCheckedException If failed.
*/
protected abstract int run0(Page page, ByteBuffer buf, BPlusIO<L> io, G g, int lvl)
throws IgniteCheckedException;
/** {@inheritDoc} */
@Override public final boolean releaseAfterWrite(Page page, G g, int lvl) {
return g.canRelease(page, lvl);
}
}
}
| ignite-db - cursor fix
| modules/core/src/main/java/org/apache/ignite/internal/processors/cache/database/tree/BPlusTree.java | ignite-db - cursor fix |
|
Java | apache-2.0 | a01ee55d621e44350a8057599602db6ac4a27cc8 | 0 | AArhin/head,AArhin/head,jpodeszwik/mifos,AArhin/head,maduhu/head,vorburger/mifos-head,jpodeszwik/mifos,maduhu/head,maduhu/head,maduhu/head,maduhu/head,maduhu/mifos-head,maduhu/mifos-head,vorburger/mifos-head,maduhu/mifos-head,jpodeszwik/mifos,maduhu/mifos-head,AArhin/head,vorburger/mifos-head,AArhin/head,maduhu/mifos-head,vorburger/mifos-head,jpodeszwik/mifos | /*
* Copyright (c) 2005-2010 Grameen Foundation USA
* 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.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.accounts.productdefinition.business;
import java.sql.Connection;
import junit.framework.Assert;
import org.hibernate.Session;
import org.mifos.application.master.business.InterestTypesEntity;
import org.mifos.framework.MifosIntegrationTestCase;
import org.mifos.framework.hibernate.helper.StaticHibernateUtil;
import org.mifos.framework.persistence.TestDatabase;
public class AddInterestCalcRuleIntegrationTest extends MifosIntegrationTestCase {
Connection connection;
public AddInterestCalcRuleIntegrationTest() throws Exception {
super();
connection = StaticHibernateUtil.getSessionTL().connection();
connection.setAutoCommit(true);
}
public void testValidateLookupValueKeyTest() throws Exception {
String validKey = "InterestTypes-DecliningBalance";
String format = "InterestTypes-";
Assert.assertTrue(AddInterestCalcRule.validateLookupValueKey(format, validKey));
String invalidKey = "DecliningBalance";
Assert.assertFalse(AddInterestCalcRule.validateLookupValueKey(format, invalidKey));
}
public void testConstructor() throws Exception {
short newRuleId = 2555;
short categoryId = 1;
String description = "DecliningBalance";
AddInterestCalcRule upgrade = null;
String invalidKey = "DecliningBalance";
try {
// use invalid lookup key format
upgrade = new AddInterestCalcRule(newRuleId,
categoryId, invalidKey, description);
} catch (Exception e) {
Assert.assertEquals(e.getMessage(), AddInterestCalcRule.wrongLookupValueKeyFormat);
}
String goodKey = "InterestTypes-NewDecliningBalance";
// use valid constructor and valid key
upgrade = new AddInterestCalcRule(newRuleId, categoryId,
goodKey, description);
try {
Session session = StaticHibernateUtil.getSessionTL();
upgrade.upgrade(connection);
InterestTypesEntity entity = (InterestTypesEntity) session.get(InterestTypesEntity.class, newRuleId);
Assert.assertEquals(goodKey, entity.getLookUpValue().getLookUpName());
} finally {
TestDatabase.resetMySQLDatabase();
}
}
}
| application/src/test/java/org/mifos/accounts/productdefinition/business/AddInterestCalcRuleIntegrationTest.java | /*
* Copyright (c) 2005-2010 Grameen Foundation USA
* 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.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.accounts.productdefinition.business;
import static org.mifos.framework.util.helpers.TestObjectFactory.TEST_LOCALE;
import java.sql.Connection;
import junit.framework.Assert;
import org.hibernate.Session;
import org.mifos.application.master.business.InterestTypesEntity;
import org.mifos.framework.MifosIntegrationTestCase;
import org.mifos.framework.hibernate.helper.StaticHibernateUtil;
import org.mifos.framework.persistence.TestDatabase;
public class AddInterestCalcRuleIntegrationTest extends MifosIntegrationTestCase {
Connection connection;
public AddInterestCalcRuleIntegrationTest() throws Exception {
super();
connection.setAutoCommit(true);
}
public void testValidateLookupValueKeyTest() throws Exception {
String validKey = "InterestTypes-DecliningBalance";
String format = "InterestTypes-";
Assert.assertTrue(AddInterestCalcRule.validateLookupValueKey(format, validKey));
String invalidKey = "DecliningBalance";
Assert.assertFalse(AddInterestCalcRule.validateLookupValueKey(format, invalidKey));
}
public void testConstructor() throws Exception {
short newRuleId = 2555;
short categoryId = 1;
String description = "DecliningBalance";
AddInterestCalcRule upgrade = null;
String invalidKey = "DecliningBalance";
try {
// use invalid lookup key format
upgrade = new AddInterestCalcRule(newRuleId,
categoryId, invalidKey, description);
} catch (Exception e) {
Assert.assertEquals(e.getMessage(), AddInterestCalcRule.wrongLookupValueKeyFormat);
}
String goodKey = "InterestTypes-NewDecliningBalance";
// use valid constructor and valid key
upgrade = new AddInterestCalcRule(newRuleId, categoryId,
goodKey, description);
try {
Session session = StaticHibernateUtil.getSessionTL();
upgrade.upgrade(connection);
InterestTypesEntity entity = (InterestTypesEntity) session.get(InterestTypesEntity.class, newRuleId);
Assert.assertEquals(goodKey, entity.getLookUpValue().getLookUpName());
} finally {
TestDatabase.resetMySQLDatabase();
}
}
}
| (WIP) MIFOS-3999 Build and deploy issues on nonSequentialDatabaseUpgrades branch
fixed missing initialisation of connection object
| application/src/test/java/org/mifos/accounts/productdefinition/business/AddInterestCalcRuleIntegrationTest.java | (WIP) MIFOS-3999 Build and deploy issues on nonSequentialDatabaseUpgrades branch |
|
Java | apache-2.0 | 9086abefa1e9f3c1317b50e4f1d988e890989397 | 0 | EBISPOT/goci,EBISPOT/goci,EBISPOT/goci,EBISPOT/goci,EBISPOT/goci,EBISPOT/goci | package uk.ac.ebi.spot.goci.component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import uk.ac.ebi.spot.goci.model.SnpLookupJson;
import uk.ac.ebi.spot.goci.utils.RestUrlBuilder;
import javax.validation.constraints.NotNull;
import java.util.HashSet;
import java.util.Set;
/**
* Created by Emma on 22/04/16.
*
* @author emma
* <p>
* Checks a SNP identifier is valid using standard Spring mechanism to consume a RESTful service
*/
@Service
public class SnpValidationChecks {
@NotNull @Value("${mapping.snp_lookup_endpoint}")
private String endpoint;
private final Logger log = LoggerFactory.getLogger(getClass());
protected Logger getLog() {
return log;
}
private RestUrlBuilder restUrlBuilder;
@Autowired
public SnpValidationChecks(RestUrlBuilder restUrlBuilder) {
this.restUrlBuilder = restUrlBuilder;
}
/**
* Check gene name returns a response
*
* @param snp Snp identifier to check
* @return Error message
*/
public String checkSnpIdentifierIsValid(String snp) {
String error = null;
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();
// Add the Jackson message converter
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
try {
String response = restTemplate.getForObject(restUrlBuilder.createUrl(getEndpoint(), snp), String.class);
}
// The query returns a 400 error if response returns an error
catch (Exception e) {
error = "SNP identifier ".concat(snp).concat(" is not valid");
getLog().error("Checking SNP identifier failed", e);
}
return error;
}
/**
* Get the chromosome a SNP resides on
*
* @param snp Snp identifier to check
* @return Set of all SNP chromosome names
*/
public Set<String> getSnpLocations(String snp) {
Set<String> snpChromosomeNames = new HashSet<>();
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();
// Add the Jackson message converter
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
SnpLookupJson snpLookupJson = new SnpLookupJson();
try {
snpLookupJson =
restTemplate.getForObject(restUrlBuilder.createUrl(getEndpoint(), snp), SnpLookupJson.class);
snpLookupJson.getMappings().forEach(snpMappingsJson -> {
snpChromosomeNames.add(snpMappingsJson.getSeq_region_name());
});
}
// The query returns a 400 error if response returns an error
catch (Exception e) {
getLog().error("Getting locations for SNP ".concat(snp).concat("failed"), e);
}
return snpChromosomeNames;
}
public String getEndpoint() {
return endpoint;
}
} | goci-data-services/goci-data-validation-services/src/main/java/uk/ac/ebi/spot/goci/component/SnpValidationChecks.java | package uk.ac.ebi.spot.goci.component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import uk.ac.ebi.spot.goci.model.SnpLookupJson;
import uk.ac.ebi.spot.goci.utils.RestUrlBuilder;
import javax.validation.constraints.NotNull;
import java.util.HashSet;
import java.util.Set;
/**
* Created by Emma on 22/04/16.
*
* @author emma
* <p>
* Checks a SNP identifier is valid using standard Spring mechanism to consume a RESTful service
*/
@Service
public class SnpValidationChecks {
@NotNull @Value("${mapping.snp_lookup_endpoint}")
private String endpoint;
private final Logger log = LoggerFactory.getLogger(getClass());
protected Logger getLog() {
return log;
}
private RestUrlBuilder restUrlBuilder;
@Autowired
public SnpValidationChecks(RestUrlBuilder restUrlBuilder) {
this.restUrlBuilder = restUrlBuilder;
}
/**
* Check gene name returns a response
*
* @param snp Snp identifier to check
* @return Error message
*/
public String checkSnpIdentifierIsValid(String snp) {
String error = null;
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();
// Add the Jackson message converter
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
try {
String response = restTemplate.getForObject(restUrlBuilder.createUrl(getEndpoint(), snp), String.class);
}
// The query returns a 400 error if response returns an error
catch (Exception e) {
error = "SNP identifier ".concat(snp).concat(" is not valid");
getLog().error("Checking SNP identifier failed", e);
}
return error;
}
/**
* Get the chromosome a SNP resides on
*
* @param snp Snp identifier to check
* @return Error message
*/
public Set<String> getSnpLocations(String snp) {
Set<String> snpChromosomeNames = new HashSet<>();
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();
// Add the Jackson message converter
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
SnpLookupJson snpLookupJson = new SnpLookupJson();
try {
snpLookupJson =
restTemplate.getForObject(restUrlBuilder.createUrl(getEndpoint(), snp), SnpLookupJson.class);
snpLookupJson.getMappings().forEach(snpMappingsJson -> {
snpChromosomeNames.add(snpMappingsJson.getSeq_region_name());
});
}
// The query returns a 400 error if response returns an error
catch (Exception e) {
getLog().error("Getting locations for SNP ".concat(snp).concat("failed"), e);
}
return snpChromosomeNames;
}
public String getEndpoint() {
return endpoint;
}
} | Update to comment
| goci-data-services/goci-data-validation-services/src/main/java/uk/ac/ebi/spot/goci/component/SnpValidationChecks.java | Update to comment |
|
Java | apache-2.0 | f42f28700a9c47e24c066c06fd875a99ce4add87 | 0 | DevStreet/FinanceAnalytics,jeorme/OG-Platform,nssales/OG-Platform,jerome79/OG-Platform,jerome79/OG-Platform,McLeodMoores/starling,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,codeaudit/OG-Platform,ChinaQuants/OG-Platform,nssales/OG-Platform,ChinaQuants/OG-Platform,nssales/OG-Platform,DevStreet/FinanceAnalytics,codeaudit/OG-Platform,McLeodMoores/starling,McLeodMoores/starling,ChinaQuants/OG-Platform,ChinaQuants/OG-Platform,jeorme/OG-Platform,DevStreet/FinanceAnalytics,jerome79/OG-Platform,jeorme/OG-Platform,jerome79/OG-Platform,McLeodMoores/starling,nssales/OG-Platform,codeaudit/OG-Platform,jeorme/OG-Platform | /**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.examples.simulated.web;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* Placeholder REST resource for portfolio upload in the examples project. The upload depends on Bloomberg
* data and therefore isn't available in Examples-Simulated but the upload button in the UI is still there. This class
* prevents an ugly 404 error if the user tries to upload a portfolio.
*/
@Path("portfolioupload")
public class PortfolioLoaderUnavailableResource {
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
public Response portfolioLoaderUnavailable() {
return Response.ok("Portfolio upload requires Bloomberg data \nPlease see Examples-Bloomberg").build();
}
}
| examples/examples-simulated/src/main/java/com/opengamma/examples/simulated/web/PortfolioLoaderUnavailableResource.java | /**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.examples.simulated.web;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* Placeholder REST resource for portfolio upload in the examples project. The upload depends on Bloomberg
* data and therefore isn't available in Examples-Simulated but the upload button in the UI is still there. This class
* prevents an ugly 404 error if the user tries to upload a portfolio.
*/
@Path("portfolioupload")
public class PortfolioLoaderUnavailableResource {
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
public Response portfolioLoaderUnavailable() {
return Response.ok("Portfolio upload requires Bloomberg data \nPlease see OG-BloombergExamples").build();
}
}
| [PLAT-3406] Maven - Fix references to OG-BloombergExample
| examples/examples-simulated/src/main/java/com/opengamma/examples/simulated/web/PortfolioLoaderUnavailableResource.java | [PLAT-3406] Maven - Fix references to OG-BloombergExample |
|
Java | apache-2.0 | f6041aba1968fee29a702605bb524c65c7593df9 | 0 | gchq/stroom,gchq/stroom,gchq/stroom,gchq/stroom,gchq/stroom,gchq/stroom | package stroom.statistics.impl.sql.search;
import stroom.dashboard.expression.v1.FieldIndexMap;
import stroom.dashboard.expression.v1.Val;
import stroom.dashboard.expression.v1.ValDouble;
import stroom.dashboard.expression.v1.ValLong;
import stroom.dashboard.expression.v1.ValNull;
import stroom.dashboard.expression.v1.ValString;
import stroom.statistics.impl.sql.PreparedStatementUtil;
import stroom.statistics.impl.sql.SQLStatisticConstants;
import stroom.statistics.impl.sql.SQLStatisticNames;
import stroom.statistics.impl.sql.SQLStatisticsDbConnProvider;
import stroom.statistics.impl.sql.SqlBuilder;
import stroom.statistics.impl.sql.rollup.RollUpBitMask;
import stroom.statistics.impl.sql.shared.StatisticStoreDoc;
import stroom.statistics.impl.sql.shared.StatisticType;
import stroom.task.api.TaskContext;
import stroom.task.api.TaskContextFactory;
import stroom.util.logging.LambdaLogger;
import stroom.util.logging.LambdaLoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import io.reactivex.Flowable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
@SuppressWarnings("unused")
//called by DI
//TODO rename to StatisticsDatabaseSearchServiceImpl
class StatisticsSearchServiceImpl implements StatisticsSearchService {
private static final Logger LOGGER = LoggerFactory.getLogger(StatisticsSearchServiceImpl.class);
private static final LambdaLogger LAMBDA_LOGGER = LambdaLoggerFactory.getLogger(StatisticsSearchServiceImpl.class);
private static final String KEY_TABLE_ALIAS = "K";
private static final String VALUE_TABLE_ALIAS = "V";
private static final String ALIASED_TIME_MS_COL = VALUE_TABLE_ALIAS + "." + SQLStatisticNames.TIME_MS;
private static final String ALIASED_PRECISION_COL = VALUE_TABLE_ALIAS + "." + SQLStatisticNames.PRECISION;
private static final String ALIASED_COUNT_COL = VALUE_TABLE_ALIAS + "." + SQLStatisticNames.COUNT;
private static final String ALIASED_VALUE_COL = VALUE_TABLE_ALIAS + "." + SQLStatisticNames.VALUE;
private final SQLStatisticsDbConnProvider SQLStatisticsDbConnProvider;
private final SearchConfig searchConfig;
private final TaskContextFactory taskContextFactory;
//defines how the entity fields relate to the table columns
private static final Map<String, List<String>> STATIC_FIELDS_TO_COLUMNS_MAP = ImmutableMap.<String, List<String>>builder()
.put(StatisticStoreDoc.FIELD_NAME_DATE_TIME, Collections.singletonList(ALIASED_TIME_MS_COL))
.put(StatisticStoreDoc.FIELD_NAME_PRECISION_MS, Collections.singletonList(ALIASED_PRECISION_COL))
.put(StatisticStoreDoc.FIELD_NAME_COUNT, Collections.singletonList(ALIASED_COUNT_COL))
.put(StatisticStoreDoc.FIELD_NAME_VALUE, Arrays.asList(ALIASED_COUNT_COL, ALIASED_VALUE_COL))
.build();
@SuppressWarnings("unused") // Called by DI
@Inject
StatisticsSearchServiceImpl(final SQLStatisticsDbConnProvider SQLStatisticsDbConnProvider,
final SearchConfig searchConfig,
final TaskContextFactory taskContextFactory) {
this.SQLStatisticsDbConnProvider = SQLStatisticsDbConnProvider;
this.searchConfig = searchConfig;
this.taskContextFactory = taskContextFactory;
}
@Override
public Flowable<Val[]> search(final TaskContext parentTaskContext,
final StatisticStoreDoc statisticStoreEntity,
final FindEventCriteria criteria,
final FieldIndexMap fieldIndexMap) {
List<String> selectCols = getSelectColumns(statisticStoreEntity, fieldIndexMap);
SqlBuilder sql = buildSql(statisticStoreEntity, criteria, fieldIndexMap);
// build a mapper function to convert a resultSet row into a String[] based on the fields
// required by all coprocessors
Function<ResultSet, Val[]> resultSetMapper = buildResultSetMapper(fieldIndexMap, statisticStoreEntity);
// the query will not be executed until somebody subscribes to the flowable
return getFlowableQueryResults(parentTaskContext, sql, resultSetMapper);
}
private List<String> getSelectColumns(final StatisticStoreDoc statisticStoreEntity,
final FieldIndexMap fieldIndexMap) {
//assemble a map of how fields map to 1-* select cols
//get all the static field mappings
final Map<String, List<String>> fieldToColumnsMap = new HashMap<>(STATIC_FIELDS_TO_COLUMNS_MAP);
//now add in all the dynamic tag field mappings
statisticStoreEntity.getFieldNames().forEach(tagField ->
fieldToColumnsMap.computeIfAbsent(tagField, k -> new ArrayList<>())
.add(KEY_TABLE_ALIAS + "." + SQLStatisticNames.NAME));
//now map the fields in use to a distinct list of columns
return fieldToColumnsMap.entrySet().stream()
.flatMap(entry ->
entry.getValue().stream()
.map(colName ->
getOptFieldIndexPosition(fieldIndexMap, entry.getKey())
.map(val -> colName))
.filter(Optional::isPresent)
.map(Optional::get))
.distinct()
.collect(Collectors.toList());
}
/**
* Construct the sql select for the query's criteria
*/
private SqlBuilder buildSql(final StatisticStoreDoc statisticStoreEntity,
final FindEventCriteria criteria,
final FieldIndexMap fieldIndexMap) {
/**
* SQL for testing querying the stat/tag names
* <p>
* create table test (name varchar(255)) ENGINE=InnoDB DEFAULT
* CHARSET=latin1;
* <p>
* insert into test values ('StatName1');
* <p>
* insert into test values ('StatName2¬Tag1¬Val1¬Tag2¬Val2');
* <p>
* insert into test values ('StatName2¬Tag2¬Val2¬Tag1¬Val1');
* <p>
* select * from test where name REGEXP '^StatName1(¬|$)';
* <p>
* select * from test where name REGEXP '¬Tag1¬Val1(¬|$)';
*/
final RollUpBitMask rollUpBitMask = buildRollUpBitMaskFromCriteria(criteria, statisticStoreEntity);
final String statNameWithMask = statisticStoreEntity.getName() + rollUpBitMask.asHexString();
SqlBuilder sql = new SqlBuilder();
sql.append("SELECT ");
String selectColsStr = getSelectColumns(statisticStoreEntity, fieldIndexMap).stream()
.collect(Collectors.joining(", "));
sql.append(selectColsStr);
// join to key table
sql.append(" FROM " + SQLStatisticNames.SQL_STATISTIC_KEY_TABLE_NAME + " K");
sql.join(SQLStatisticNames.SQL_STATISTIC_VALUE_TABLE_NAME,
"V",
"K",
SQLStatisticNames.ID,
"V",
SQLStatisticNames.SQL_STATISTIC_KEY_FOREIGN_KEY);
// do a like on the name first so we can hit the index before doing the slow regex matches
sql.append(" WHERE K." + SQLStatisticNames.NAME + " LIKE ");
sql.arg(statNameWithMask + "%");
// exact match on the stat name bit of the key
sql.append(" AND K." + SQLStatisticNames.NAME + " REGEXP ");
sql.arg("^" + statNameWithMask + "(" + SQLStatisticConstants.NAME_SEPARATOR + "|$)");
// add the time bounds
sql.append(" AND V." + SQLStatisticNames.TIME_MS + " >= ");
sql.arg(criteria.getPeriod().getFromMs());
sql.append(" AND V." + SQLStatisticNames.TIME_MS + " < ");
sql.arg(criteria.getPeriod().getToMs());
// now add the query terms
SQLTagValueWhereClauseConverter.buildTagValueWhereClause(criteria.getFilterTermsTree(), sql);
final int maxResults = searchConfig.getMaxResults();
sql.append(" LIMIT " + maxResults);
LOGGER.debug("Search query: {}", sql.toString());
return sql;
}
private Optional<Integer> getOptFieldIndexPosition(final FieldIndexMap fieldIndexMap, final String fieldName) {
int idx = fieldIndexMap.get(fieldName);
if (idx == -1) {
return Optional.empty();
} else {
return Optional.of(idx);
}
}
/**
* Build a mapper function that will only extract the columns of interest from the resultSet row.
* Assumes something external to the returned function will advance the resultSet
*/
private Function<ResultSet, Val[]> buildResultSetMapper(
final FieldIndexMap fieldIndexMap,
final StatisticStoreDoc statisticStoreEntity) {
LAMBDA_LOGGER.debug(() -> String.format("Building mapper for fieldIndexMap %s, entity %s",
fieldIndexMap, statisticStoreEntity.getUuid()));
// construct a list of field extractors that can populate the appropriate bit of the data arr
// when given a resultSet row
List<ValueExtractor> valueExtractors = fieldIndexMap.getMap().entrySet().stream()
.map(entry -> {
final int idx = entry.getValue();
final String fieldName = entry.getKey();
final ValueExtractor extractor;
if (fieldName.equals(StatisticStoreDoc.FIELD_NAME_DATE_TIME)) {
extractor = buildLongValueExtractor(SQLStatisticNames.TIME_MS, idx);
} else if (fieldName.equals(StatisticStoreDoc.FIELD_NAME_COUNT)) {
extractor = buildLongValueExtractor(SQLStatisticNames.COUNT, idx);
} else if (fieldName.equals(StatisticStoreDoc.FIELD_NAME_PRECISION_MS)) {
extractor = buildPrecisionMsExtractor(idx);
} else if (fieldName.equals(StatisticStoreDoc.FIELD_NAME_VALUE)) {
final StatisticType statisticType = statisticStoreEntity.getStatisticType();
if (statisticType.equals(StatisticType.COUNT)) {
extractor = buildLongValueExtractor(SQLStatisticNames.COUNT, idx);
} else if (statisticType.equals(StatisticType.VALUE)) {
// value stat
extractor = buildStatValueExtractor(idx);
} else {
throw new RuntimeException(String.format("Unexpected type %s", statisticType));
}
} else if (statisticStoreEntity.getFieldNames().contains(fieldName)) {
// this is a tag field so need to extract the tags/values from the NAME col.
// We only want to do this extraction once so we cache the values
extractor = buildTagFieldValueExtractor(fieldName, idx);
} else {
throw new RuntimeException(String.format("Unexpected fieldName %s", fieldName));
}
LAMBDA_LOGGER.debug(() ->
String.format("Adding extraction function for field %s, idx %s", fieldName, idx));
return extractor;
})
.collect(Collectors.toList());
final int arrSize = valueExtractors.size();
//the mapping function that will be used on each row in the resultSet, that makes use of the ValueExtractors
//created above
return rs -> {
Preconditions.checkNotNull(rs);
try {
if (rs.isClosed()) {
throw new RuntimeException("ResultSet is closed");
}
} catch (SQLException e) {
throw new RuntimeException("Error testing closed state of resultSet", e);
}
//the data array we are populating
final Val[] data = new Val[arrSize];
//state to hold while mapping this row, used to save parsing the NAME col multiple times
final Map<String, Val> fieldValueCache = new HashMap<>();
//run each of our field value extractors against the resultSet to fill up the data arr
valueExtractors.forEach(valueExtractor ->
valueExtractor.extract(rs, data, fieldValueCache));
LAMBDA_LOGGER.trace(() -> {
try {
return String.format("Mapped resultSet row %s to %s", rs.getRow(), Arrays.toString(data));
} catch (SQLException e) {
throw new RuntimeException(String.format("Error getting current row number: %s", e.getMessage()), e);
}
});
return data;
};
}
private ValueExtractor buildPrecisionMsExtractor(final int idx) {
final ValueExtractor extractor;
extractor = (rs, arr, cache) -> {
// the precision in the table represents the number of zeros
// of millisecond precision, e.g.
// 6=1,000,000ms
final long precisionMs;
try {
precisionMs = (long) Math.pow(10, rs.getInt(SQLStatisticNames.PRECISION));
} catch (SQLException e) {
throw new RuntimeException("Error extracting precision field", e);
}
arr[idx] = ValLong.create(precisionMs);
};
return extractor;
}
private ValueExtractor buildStatValueExtractor(final int idx) {
final ValueExtractor extractor;
extractor = (rs, arr, cache) -> {
final double aggregatedValue;
final long count;
try {
aggregatedValue = rs.getDouble(SQLStatisticNames.VALUE);
count = rs.getLong(SQLStatisticNames.COUNT);
} catch (SQLException e) {
throw new RuntimeException("Error extracting count and value fields", e);
}
// the aggregateValue is sum of all values against that
// key/time. We therefore need to get the
// average using the count column
final double averagedValue = count != 0 ? (aggregatedValue / count) : 0;
arr[idx] = ValDouble.create(averagedValue);
};
return extractor;
}
private ValueExtractor buildLongValueExtractor(final String columnName, final int fieldIndex) {
return (rs, arr, cache) ->
arr[fieldIndex] = getResultSetLong(rs, columnName);
}
private ValueExtractor buildTagFieldValueExtractor(final String fieldName, final int fieldIndex) {
return (rs, arr, cache) -> {
Val value = cache.get(fieldName);
if (value == null) {
//populate our cache of
extractTagsMapFromColumn(getResultSetString(rs, SQLStatisticNames.NAME))
.forEach(cache::put);
}
value = cache.get(fieldName);
arr[fieldIndex] = value;
};
}
private Val getResultSetLong(final ResultSet resultSet, final String column) {
try {
return ValLong.create(resultSet.getLong(column));
} catch (SQLException e) {
throw new RuntimeException(String.format("Error extracting field %s", column), e);
}
}
private Val getResultSetString(final ResultSet resultSet, final String column) {
try {
return ValString.create(resultSet.getString(column));
} catch (SQLException e) {
throw new RuntimeException(String.format("Error extracting field %s", column), e);
}
}
private Flowable<Val[]> getFlowableQueryResults(final TaskContext parentContext,
final SqlBuilder sql,
final Function<ResultSet, Val[]> resultSetMapper) {
//Not thread safe as each onNext will get the same ResultSet instance, however its position
// will have moved on each time.
return Flowable
.using(
() -> new PreparedStatementResourceHolder(SQLStatisticsDbConnProvider, sql, searchConfig),
factory -> {
LOGGER.debug("Converting factory to a flowable");
Preconditions.checkNotNull(factory);
PreparedStatement ps = factory.getPreparedStatement();
return Flowable.generate(
() -> executeQuery(parentContext, sql, ps),
(rs, emitter) -> {
// The line below can be un-commented in development debugging to slow down the
// return of all results to test iterative results and dashboard polling.
// LockSupport.parkNanos(200_000);
//advance the resultSet, if it is a row emit it, else finish the flow
if (Thread.currentThread().isInterrupted()) {
LOGGER.debug("Task is terminated/interrupted, calling onComplete");
emitter.onComplete();
} else {
if (rs.next()) {
LOGGER.trace("calling onNext");
Val[] values = resultSetMapper.apply(rs);
emitter.onNext(values);
} else {
LOGGER.debug("End of resultSet, calling onComplete");
emitter.onComplete();
}
}
});
},
PreparedStatementResourceHolder::dispose);
}
private ResultSet executeQuery(final TaskContext parentContext,
final SqlBuilder sql,
final PreparedStatement ps) {
return taskContextFactory.contextResult(
parentContext,
SqlStatisticsStore.TASK_NAME,
taskContext -> {
final Supplier<String> message = () -> "Executing query " + sql.toString();
taskContext.info(message);
LAMBDA_LOGGER.debug(message);
try {
return ps.executeQuery();
} catch (SQLException e) {
throw new RuntimeException(String.format("Error executing query %s, %s",
ps.toString(), e.getMessage()), e);
}
})
.get();
}
/**
* @param columnValue The value from the STAT_KEY.NAME column which could be of the
* form 'StatName' or 'StatName¬Tag1¬Tag1Val1¬Tag2¬Tag2Val1'
* @return A map of tag=>value, or an empty map if there are none
*/
private Map<String, Val> extractTagsMapFromColumn(final Val columnValue) {
final String[] tokens = columnValue.toString().split(SQLStatisticConstants.NAME_SEPARATOR);
if (tokens.length == 1) {
// no separators so there are no tags
return Collections.emptyMap();
} else if (tokens.length % 2 == 0) {
throw new RuntimeException(
String.format("Expecting an odd number of tokens, columnValue: %s", columnValue));
} else {
final Map<String, Val> statisticTags = new HashMap<>();
// stat name will be at pos 0 so start at 1
for (int i = 1; i < tokens.length; i++) {
final String tag = tokens[i++];
String value = tokens[i];
if (value.equals(SQLStatisticConstants.NULL_VALUE_STRING)) {
statisticTags.put(tag, ValNull.INSTANCE);
} else {
statisticTags.put(tag, ValString.create(value));
}
}
return statisticTags;
}
}
/**
* TODO: This is a bit simplistic as a user could create a filter that said
* user=user1 AND user='*' which makes no sense. At the moment we would
* assume that the user tag is being rolled up so user=user1 would never be
* found in the data and thus would return no data.
*/
private static RollUpBitMask buildRollUpBitMaskFromCriteria(final FindEventCriteria criteria,
final StatisticStoreDoc statisticsDataSource) {
final Set<String> rolledUpTagsFound = criteria.getRolledUpFieldNames();
final RollUpBitMask result;
if (rolledUpTagsFound.size() > 0) {
final List<Integer> rollUpTagPositionList = new ArrayList<>();
for (final String tag : rolledUpTagsFound) {
final Integer position = statisticsDataSource.getPositionInFieldList(tag);
if (position == null) {
throw new RuntimeException(String.format("No field position found for tag %s", tag));
}
rollUpTagPositionList.add(position);
}
result = RollUpBitMask.fromTagPositions(rollUpTagPositionList);
} else {
result = RollUpBitMask.ZERO_MASK;
}
return result;
}
@FunctionalInterface
private interface ValueExtractor {
/**
* Function for extracting values from a {@link ResultSet} and placing them into the passed String[]
*
* @param resultSet The {@link ResultSet} instance to extract data from. It is assumed the {@link ResultSet}
* has already been positioned at the desired row. next() should not be called on the
* resultSet.
* @param data The data array to populate
* @param fieldValueCache A map of fieldName=>fieldValue that can be used to hold state while
* processing a row
*/
void extract(final ResultSet resultSet,
final Val[] data,
final Map<String, Val> fieldValueCache);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private static class PreparedStatementResourceHolder {
private Connection connection;
private PreparedStatement preparedStatement;
PreparedStatementResourceHolder(final DataSource dataSource,
final SqlBuilder sql,
final SearchConfig searchConfig) {
try {
connection = dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException("Error getting connection", e);
}
try {
//settings ot prevent mysql from reading the whole resultset into memory
//see https://github.com/ontop/ontop/wiki/WorkingWithMySQL
//Also needs 'useCursorFetch=true' on the jdbc connect string
preparedStatement = connection.prepareStatement(
sql.toString(),
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY,
ResultSet.CLOSE_CURSORS_AT_COMMIT);
final int fetchSize = searchConfig.getFetchSize();
LOGGER.debug("Setting fetch size to {}", fetchSize);
preparedStatement.setFetchSize(fetchSize);
PreparedStatementUtil.setArguments(preparedStatement, sql.getArgs());
LAMBDA_LOGGER.debug(() -> String.format("Created preparedStatement %s", preparedStatement.toString()));
} catch (SQLException e) {
throw new RuntimeException(String.format("Error preparing statement for sql [%s]", sql.toString()), e);
}
}
PreparedStatement getPreparedStatement() {
return preparedStatement;
}
void dispose() {
LOGGER.debug("dispose called");
if (preparedStatement != null) {
try {
LOGGER.debug("Closing preparedStatement");
preparedStatement.close();
} catch (SQLException e) {
throw new RuntimeException("Error closing preparedStatement", e);
}
preparedStatement = null;
}
if (connection != null) {
try {
LOGGER.debug("Closing connection");
connection.close();
} catch (SQLException e) {
throw new RuntimeException("Error closing connection", e);
}
connection = null;
}
}
}
}
| stroom-statistics/stroom-statistics-impl-sql/src/main/java/stroom/statistics/impl/sql/search/StatisticsSearchServiceImpl.java | package stroom.statistics.impl.sql.search;
import stroom.dashboard.expression.v1.FieldIndexMap;
import stroom.dashboard.expression.v1.Val;
import stroom.dashboard.expression.v1.ValDouble;
import stroom.dashboard.expression.v1.ValLong;
import stroom.dashboard.expression.v1.ValNull;
import stroom.dashboard.expression.v1.ValString;
import stroom.statistics.impl.sql.PreparedStatementUtil;
import stroom.statistics.impl.sql.SQLStatisticConstants;
import stroom.statistics.impl.sql.SQLStatisticNames;
import stroom.statistics.impl.sql.SQLStatisticsDbConnProvider;
import stroom.statistics.impl.sql.SqlBuilder;
import stroom.statistics.impl.sql.rollup.RollUpBitMask;
import stroom.statistics.impl.sql.shared.StatisticStoreDoc;
import stroom.statistics.impl.sql.shared.StatisticType;
import stroom.task.api.TaskContext;
import stroom.task.api.TaskContextFactory;
import stroom.util.logging.LambdaLogger;
import stroom.util.logging.LambdaLoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import io.reactivex.Flowable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
@SuppressWarnings("unused")
//called by DI
//TODO rename to StatisticsDatabaseSearchServiceImpl
class StatisticsSearchServiceImpl implements StatisticsSearchService {
private static final Logger LOGGER = LoggerFactory.getLogger(StatisticsSearchServiceImpl.class);
private static final LambdaLogger LAMBDA_LOGGER = LambdaLoggerFactory.getLogger(StatisticsSearchServiceImpl.class);
private static final String KEY_TABLE_ALIAS = "K";
private static final String VALUE_TABLE_ALIAS = "V";
private static final String ALIASED_TIME_MS_COL = VALUE_TABLE_ALIAS + "." + SQLStatisticNames.TIME_MS;
private static final String ALIASED_PRECISION_COL = VALUE_TABLE_ALIAS + "." + SQLStatisticNames.PRECISION;
private static final String ALIASED_COUNT_COL = VALUE_TABLE_ALIAS + "." + SQLStatisticNames.COUNT;
private static final String ALIASED_VALUE_COL = VALUE_TABLE_ALIAS + "." + SQLStatisticNames.VALUE;
private final SQLStatisticsDbConnProvider SQLStatisticsDbConnProvider;
private final SearchConfig searchConfig;
private final TaskContextFactory taskContextFactory;
//defines how the entity fields relate to the table columns
private static final Map<String, List<String>> STATIC_FIELDS_TO_COLUMNS_MAP = ImmutableMap.<String, List<String>>builder()
.put(StatisticStoreDoc.FIELD_NAME_DATE_TIME, Collections.singletonList(ALIASED_TIME_MS_COL))
.put(StatisticStoreDoc.FIELD_NAME_PRECISION_MS, Collections.singletonList(ALIASED_PRECISION_COL))
.put(StatisticStoreDoc.FIELD_NAME_COUNT, Collections.singletonList(ALIASED_COUNT_COL))
.put(StatisticStoreDoc.FIELD_NAME_VALUE, Arrays.asList(ALIASED_COUNT_COL, ALIASED_VALUE_COL))
.build();
@SuppressWarnings("unused") // Called by DI
@Inject
StatisticsSearchServiceImpl(final SQLStatisticsDbConnProvider SQLStatisticsDbConnProvider,
final SearchConfig searchConfig,
final TaskContextFactory taskContextFactory) {
this.SQLStatisticsDbConnProvider = SQLStatisticsDbConnProvider;
this.searchConfig = searchConfig;
this.taskContextFactory = taskContextFactory;
}
@Override
public Flowable<Val[]> search(final TaskContext parentTaskContext,
final StatisticStoreDoc statisticStoreEntity,
final FindEventCriteria criteria,
final FieldIndexMap fieldIndexMap) {
List<String> selectCols = getSelectColumns(statisticStoreEntity, fieldIndexMap);
SqlBuilder sql = buildSql(statisticStoreEntity, criteria, fieldIndexMap);
// build a mapper function to convert a resultSet row into a String[] based on the fields
// required by all coprocessors
Function<ResultSet, Val[]> resultSetMapper = buildResultSetMapper(fieldIndexMap, statisticStoreEntity);
// the query will not be executed until somebody subscribes to the flowable
return getFlowableQueryResults(parentTaskContext, sql, resultSetMapper);
}
private List<String> getSelectColumns(final StatisticStoreDoc statisticStoreEntity,
final FieldIndexMap fieldIndexMap) {
//assemble a map of how fields map to 1-* select cols
//get all the static field mappings
final Map<String, List<String>> fieldToColumnsMap = new HashMap<>(STATIC_FIELDS_TO_COLUMNS_MAP);
//now add in all the dynamic tag field mappings
statisticStoreEntity.getFieldNames().forEach(tagField ->
fieldToColumnsMap.computeIfAbsent(tagField, k -> new ArrayList<>())
.add(KEY_TABLE_ALIAS + "." + SQLStatisticNames.NAME));
//now map the fields in use to a distinct list of columns
return fieldToColumnsMap.entrySet().stream()
.flatMap(entry ->
entry.getValue().stream()
.map(colName ->
getOptFieldIndexPosition(fieldIndexMap, entry.getKey())
.map(val -> colName))
.filter(Optional::isPresent)
.map(Optional::get))
.distinct()
.collect(Collectors.toList());
}
/**
* Construct the sql select for the query's criteria
*/
private SqlBuilder buildSql(final StatisticStoreDoc statisticStoreEntity,
final FindEventCriteria criteria,
final FieldIndexMap fieldIndexMap) {
/**
* SQL for testing querying the stat/tag names
* <p>
* create table test (name varchar(255)) ENGINE=InnoDB DEFAULT
* CHARSET=latin1;
* <p>
* insert into test values ('StatName1');
* <p>
* insert into test values ('StatName2¬Tag1¬Val1¬Tag2¬Val2');
* <p>
* insert into test values ('StatName2¬Tag2¬Val2¬Tag1¬Val1');
* <p>
* select * from test where name REGEXP '^StatName1(¬|$)';
* <p>
* select * from test where name REGEXP '¬Tag1¬Val1(¬|$)';
*/
final RollUpBitMask rollUpBitMask = buildRollUpBitMaskFromCriteria(criteria, statisticStoreEntity);
final String statNameWithMask = statisticStoreEntity.getName() + rollUpBitMask.asHexString();
SqlBuilder sql = new SqlBuilder();
sql.append("SELECT ");
String selectColsStr = getSelectColumns(statisticStoreEntity, fieldIndexMap).stream()
.collect(Collectors.joining(", "));
sql.append(selectColsStr);
// join to key table
sql.append(" FROM " + SQLStatisticNames.SQL_STATISTIC_KEY_TABLE_NAME + " K");
sql.join(SQLStatisticNames.SQL_STATISTIC_VALUE_TABLE_NAME,
"V",
"K",
SQLStatisticNames.ID,
"V",
SQLStatisticNames.SQL_STATISTIC_KEY_FOREIGN_KEY);
// do a like on the name first so we can hit the index before doing the slow regex matches
sql.append(" WHERE K." + SQLStatisticNames.NAME + " LIKE ");
sql.arg(statNameWithMask + "%");
// exact match on the stat name bit of the key
sql.append(" AND K." + SQLStatisticNames.NAME + " REGEXP ");
sql.arg("^" + statNameWithMask + "(" + SQLStatisticConstants.NAME_SEPARATOR + "|$)");
// add the time bounds
sql.append(" AND V." + SQLStatisticNames.TIME_MS + " >= ");
sql.arg(criteria.getPeriod().getFromMs());
sql.append(" AND V." + SQLStatisticNames.TIME_MS + " < ");
sql.arg(criteria.getPeriod().getToMs());
// now add the query terms
SQLTagValueWhereClauseConverter.buildTagValueWhereClause(criteria.getFilterTermsTree(), sql);
final int maxResults = searchConfig.getMaxResults();
sql.append(" LIMIT " + maxResults);
LOGGER.debug("Search query: {}", sql.toString());
return sql;
}
private Optional<Integer> getOptFieldIndexPosition(final FieldIndexMap fieldIndexMap, final String fieldName) {
int idx = fieldIndexMap.get(fieldName);
if (idx == -1) {
return Optional.empty();
} else {
return Optional.of(idx);
}
}
/**
* Build a mapper function that will only extract the columns of interest from the resultSet row.
* Assumes something external to the returned function will advance the resultSet
*/
private Function<ResultSet, Val[]> buildResultSetMapper(
final FieldIndexMap fieldIndexMap,
final StatisticStoreDoc statisticStoreEntity) {
LAMBDA_LOGGER.debug(() -> String.format("Building mapper for fieldIndexMap %s, entity %s",
fieldIndexMap, statisticStoreEntity.getUuid()));
// construct a list of field extractors that can populate the appropriate bit of the data arr
// when given a resultSet row
List<ValueExtractor> valueExtractors = fieldIndexMap.getMap().entrySet().stream()
.map(entry -> {
final int idx = entry.getValue();
final String fieldName = entry.getKey();
final ValueExtractor extractor;
if (fieldName.equals(StatisticStoreDoc.FIELD_NAME_DATE_TIME)) {
extractor = buildLongValueExtractor(SQLStatisticNames.TIME_MS, idx);
} else if (fieldName.equals(StatisticStoreDoc.FIELD_NAME_COUNT)) {
extractor = buildLongValueExtractor(SQLStatisticNames.COUNT, idx);
} else if (fieldName.equals(StatisticStoreDoc.FIELD_NAME_PRECISION_MS)) {
extractor = buildPrecisionMsExtractor(idx);
} else if (fieldName.equals(StatisticStoreDoc.FIELD_NAME_VALUE)) {
final StatisticType statisticType = statisticStoreEntity.getStatisticType();
if (statisticType.equals(StatisticType.COUNT)) {
extractor = buildLongValueExtractor(SQLStatisticNames.COUNT, idx);
} else if (statisticType.equals(StatisticType.VALUE)) {
// value stat
extractor = buildStatValueExtractor(idx);
} else {
throw new RuntimeException(String.format("Unexpected type %s", statisticType));
}
} else if (statisticStoreEntity.getFieldNames().contains(fieldName)) {
// this is a tag field so need to extract the tags/values from the NAME col.
// We only want to do this extraction once so we cache the values
extractor = buildTagFieldValueExtractor(fieldName, idx);
} else {
throw new RuntimeException(String.format("Unexpected fieldName %s", fieldName));
}
LAMBDA_LOGGER.debug(() ->
String.format("Adding extraction function for field %s, idx %s", fieldName, idx));
return extractor;
})
.collect(Collectors.toList());
final int arrSize = valueExtractors.size();
//the mapping function that will be used on each row in the resultSet, that makes use of the ValueExtractors
//created above
return rs -> {
Preconditions.checkNotNull(rs);
try {
if (rs.isClosed()) {
throw new RuntimeException("ResultSet is closed");
}
} catch (SQLException e) {
throw new RuntimeException("Error testing closed state of resultSet", e);
}
//the data array we are populating
final Val[] data = new Val[arrSize];
//state to hold while mapping this row, used to save parsing the NAME col multiple times
final Map<String, Val> fieldValueCache = new HashMap<>();
//run each of our field value extractors against the resultSet to fill up the data arr
valueExtractors.forEach(valueExtractor ->
valueExtractor.extract(rs, data, fieldValueCache));
LAMBDA_LOGGER.trace(() -> {
try {
return String.format("Mapped resultSet row %s to %s", rs.getRow(), Arrays.toString(data));
} catch (SQLException e) {
throw new RuntimeException(String.format("Error getting current row number: %s", e.getMessage()), e);
}
});
return data;
};
}
private ValueExtractor buildPrecisionMsExtractor(final int idx) {
final ValueExtractor extractor;
extractor = (rs, arr, cache) -> {
// the precision in the table represents the number of zeros
// of millisecond precision, e.g.
// 6=1,000,000ms
final long precisionMs;
try {
precisionMs = (long) Math.pow(10, rs.getInt(SQLStatisticNames.PRECISION));
} catch (SQLException e) {
throw new RuntimeException("Error extracting precision field", e);
}
arr[idx] = ValLong.create(precisionMs);
};
return extractor;
}
private ValueExtractor buildStatValueExtractor(final int idx) {
final ValueExtractor extractor;
extractor = (rs, arr, cache) -> {
final double aggregatedValue;
final long count;
try {
aggregatedValue = rs.getDouble(SQLStatisticNames.VALUE);
count = rs.getLong(SQLStatisticNames.COUNT);
} catch (SQLException e) {
throw new RuntimeException("Error extracting count and value fields", e);
}
// the aggregateValue is sum of all values against that
// key/time. We therefore need to get the
// average using the count column
final double averagedValue = count != 0 ? (aggregatedValue / count) : 0;
arr[idx] = ValDouble.create(averagedValue);
};
return extractor;
}
private ValueExtractor buildLongValueExtractor(final String columnName, final int fieldIndex) {
return (rs, arr, cache) ->
arr[fieldIndex] = getResultSetLong(rs, columnName);
}
private ValueExtractor buildTagFieldValueExtractor(final String fieldName, final int fieldIndex) {
return (rs, arr, cache) -> {
Val value = cache.get(fieldName);
if (value == null) {
//populate our cache of
extractTagsMapFromColumn(getResultSetString(rs, SQLStatisticNames.NAME))
.forEach(cache::put);
}
value = cache.get(fieldName);
arr[fieldIndex] = value;
};
}
private Val getResultSetLong(final ResultSet resultSet, final String column) {
try {
return ValLong.create(resultSet.getLong(column));
} catch (SQLException e) {
throw new RuntimeException(String.format("Error extracting field %s", column), e);
}
}
private Val getResultSetString(final ResultSet resultSet, final String column) {
try {
return ValString.create(resultSet.getString(column));
} catch (SQLException e) {
throw new RuntimeException(String.format("Error extracting field %s", column), e);
}
}
private Flowable<Val[]> getFlowableQueryResults(final TaskContext parentContext,
final SqlBuilder sql,
final Function<ResultSet, Val[]> resultSetMapper) {
//Not thread safe as each onNext will get the same ResultSet instance, however its position
// will have moved on each time.
return Flowable
.using(
() -> new PreparedStatementResourceHolder(SQLStatisticsDbConnProvider, sql, searchConfig),
factory -> {
LOGGER.debug("Converting factory to a flowable");
Preconditions.checkNotNull(factory);
PreparedStatement ps = factory.getPreparedStatement();
return Flowable.generate(
() -> executeQuery(parentContext, sql, ps),
(rs, emitter) -> {
// The line below can be un-commented in development debugging to slow down the
// return of all results to test iterative results and dashboard polling.
// LockSupport.parkNanos(200_000);
//advance the resultSet, if it is a row emit it, else finish the flow
if (Thread.currentThread().isInterrupted()) {
LOGGER.debug("Task is terminated/interrupted, calling onComplete");
emitter.onComplete();
} else {
if (rs.next()) {
LOGGER.trace("calling onNext");
Val[] values = resultSetMapper.apply(rs);
emitter.onNext(values);
} else {
LOGGER.debug("End of resultSet, calling onComplete");
emitter.onComplete();
}
}
});
},
PreparedStatementResourceHolder::dispose);
}
private ResultSet executeQuery(TaskContext parentContext, SqlBuilder sql, PreparedStatement ps) {
return taskContextFactory.contextResult(
parentContext,
SqlStatisticsStore.TASK_NAME,
taskContext -> {
final Supplier<String> message = () -> "Executing query " + sql.toString();
taskContext.info(message);
LAMBDA_LOGGER.debug(message);
try {
return ps.executeQuery();
} catch (SQLException e) {
throw new RuntimeException(String.format("Error executing query %s, %s",
ps.toString(), e.getMessage()), e);
}
})
.get();
}
/**
* @param columnValue The value from the STAT_KEY.NAME column which could be of the
* form 'StatName' or 'StatName¬Tag1¬Tag1Val1¬Tag2¬Tag2Val1'
* @return A map of tag=>value, or an empty map if there are none
*/
private Map<String, Val> extractTagsMapFromColumn(final Val columnValue) {
final String[] tokens = columnValue.toString().split(SQLStatisticConstants.NAME_SEPARATOR);
if (tokens.length == 1) {
// no separators so there are no tags
return Collections.emptyMap();
} else if (tokens.length % 2 == 0) {
throw new RuntimeException(
String.format("Expecting an odd number of tokens, columnValue: %s", columnValue));
} else {
final Map<String, Val> statisticTags = new HashMap<>();
// stat name will be at pos 0 so start at 1
for (int i = 1; i < tokens.length; i++) {
final String tag = tokens[i++];
String value = tokens[i];
if (value.equals(SQLStatisticConstants.NULL_VALUE_STRING)) {
statisticTags.put(tag, ValNull.INSTANCE);
} else {
statisticTags.put(tag, ValString.create(value));
}
}
return statisticTags;
}
}
/**
* TODO: This is a bit simplistic as a user could create a filter that said
* user=user1 AND user='*' which makes no sense. At the moment we would
* assume that the user tag is being rolled up so user=user1 would never be
* found in the data and thus would return no data.
*/
private static RollUpBitMask buildRollUpBitMaskFromCriteria(final FindEventCriteria criteria,
final StatisticStoreDoc statisticsDataSource) {
final Set<String> rolledUpTagsFound = criteria.getRolledUpFieldNames();
final RollUpBitMask result;
if (rolledUpTagsFound.size() > 0) {
final List<Integer> rollUpTagPositionList = new ArrayList<>();
for (final String tag : rolledUpTagsFound) {
final Integer position = statisticsDataSource.getPositionInFieldList(tag);
if (position == null) {
throw new RuntimeException(String.format("No field position found for tag %s", tag));
}
rollUpTagPositionList.add(position);
}
result = RollUpBitMask.fromTagPositions(rollUpTagPositionList);
} else {
result = RollUpBitMask.ZERO_MASK;
}
return result;
}
@FunctionalInterface
private interface ValueExtractor {
/**
* Function for extracting values from a {@link ResultSet} and placing them into the passed String[]
*
* @param resultSet The {@link ResultSet} instance to extract data from. It is assumed the {@link ResultSet}
* has already been positioned at the desired row. next() should not be called on the
* resultSet.
* @param data The data array to populate
* @param fieldValueCache A map of fieldName=>fieldValue that can be used to hold state while
* processing a row
*/
void extract(final ResultSet resultSet,
final Val[] data,
final Map<String, Val> fieldValueCache);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private static class PreparedStatementResourceHolder {
private Connection connection;
private PreparedStatement preparedStatement;
PreparedStatementResourceHolder(final DataSource dataSource,
final SqlBuilder sql,
final SearchConfig searchConfig) {
try {
connection = dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException("Error getting connection", e);
}
try {
//settings ot prevent mysql from reading the whole resultset into memory
//see https://github.com/ontop/ontop/wiki/WorkingWithMySQL
//Also needs 'useCursorFetch=true' on the jdbc connect string
preparedStatement = connection.prepareStatement(
sql.toString(),
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY,
ResultSet.CLOSE_CURSORS_AT_COMMIT);
final int fetchSize = searchConfig.getFetchSize();
LOGGER.debug("Setting fetch size to {}", fetchSize);
preparedStatement.setFetchSize(fetchSize);
PreparedStatementUtil.setArguments(preparedStatement, sql.getArgs());
LAMBDA_LOGGER.debug(() -> String.format("Created preparedStatement %s", preparedStatement.toString()));
} catch (SQLException e) {
throw new RuntimeException(String.format("Error preparing statement for sql [%s]", sql.toString()), e);
}
}
PreparedStatement getPreparedStatement() {
return preparedStatement;
}
void dispose() {
LOGGER.debug("dispose called");
if (preparedStatement != null) {
try {
LOGGER.debug("Closing preparedStatement");
preparedStatement.close();
} catch (SQLException e) {
throw new RuntimeException("Error closing preparedStatement", e);
}
preparedStatement = null;
}
if (connection != null) {
try {
LOGGER.debug("Closing connection");
connection.close();
} catch (SQLException e) {
throw new RuntimeException("Error closing connection", e);
}
connection = null;
}
}
}
}
| Add final to args, reformat
| stroom-statistics/stroom-statistics-impl-sql/src/main/java/stroom/statistics/impl/sql/search/StatisticsSearchServiceImpl.java | Add final to args, reformat |
|
Java | apache-2.0 | 233e6142915ddc5973e8a15dd56d9d4a628c4cd7 | 0 | anujbhan/airavata,gouravshenoy/airavata,machristie/airavata,machristie/airavata,machristie/airavata,gouravshenoy/airavata,anujbhan/airavata,anujbhan/airavata,anujbhan/airavata,gouravshenoy/airavata,gouravshenoy/airavata,apache/airavata,machristie/airavata,anujbhan/airavata,apache/airavata,machristie/airavata,apache/airavata,machristie/airavata,apache/airavata,apache/airavata,anujbhan/airavata,apache/airavata,apache/airavata,apache/airavata,anujbhan/airavata,gouravshenoy/airavata,gouravshenoy/airavata,gouravshenoy/airavata,machristie/airavata | /*
*
* 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.airavata.registry.core.experiment.catalog.resources;
import org.apache.airavata.model.status.ExperimentState;
import org.apache.airavata.registry.core.experiment.catalog.ExpCatResourceUtils;
import org.apache.airavata.registry.core.experiment.catalog.ExperimentCatResource;
import org.apache.airavata.registry.core.experiment.catalog.ResourceType;
import org.apache.airavata.registry.core.experiment.catalog.model.*;
import org.apache.airavata.registry.core.experiment.catalog.utils.QueryGenerator;
import org.apache.airavata.registry.cpi.RegistryException;
import org.apache.airavata.registry.cpi.ResultOrderType;
import org.apache.airavata.registry.cpi.utils.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class WorkerResource extends AbstractExpCatResource {
private final static Logger logger = LoggerFactory.getLogger(WorkerResource.class);
private String user;
private String gatewayId;
public WorkerResource() {
}
public WorkerResource(String user, String gatewayId) {
this.user = user;
this.gatewayId = gatewayId;
}
public String getGatewayId() {
return gatewayId;
}
public void setGatewayId(String gatewayId) {
this.gatewayId = gatewayId;
}
/**
* Gateway worker can create child data structures such as projects and user workflows
*
* @param type child resource type
* @return child resource
*/
public ExperimentCatResource create(ResourceType type) throws RegistryException {
ExperimentCatResource result = null;
switch (type) {
case PROJECT:
org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource projectResource = new org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource();
projectResource.setWorker(this);
projectResource.setGatewayId(gatewayId);
result = projectResource;
break;
case EXPERIMENT:
ExperimentResource experimentResource = new ExperimentResource();
experimentResource.setUserName(user);
experimentResource.setGatewayExecutionId(gatewayId);
result = experimentResource;
break;
default:
logger.error("Unsupported resource type for worker resource.", new IllegalArgumentException());
throw new IllegalArgumentException("Unsupported resource type for worker resource.");
}
return result;
}
/**
* @param type child resource type
* @param name child resource name
*/
public void remove(ResourceType type, Object name) throws RegistryException {
EntityManager em = null;
try {
em = ExpCatResourceUtils.getEntityManager();
em.getTransaction().begin();
Query q;
QueryGenerator generator;
switch (type) {
case PROJECT:
generator = new QueryGenerator(PROJECT);
generator.setParameter(ProjectConstants.PROJECT_ID, name);
q = generator.deleteQuery(em);
q.executeUpdate();
break;
case EXPERIMENT:
generator = new QueryGenerator(EXPERIMENT);
generator.setParameter(ExperimentConstants.EXPERIMENT_ID, name);
q = generator.deleteQuery(em);
q.executeUpdate();
break;
default:
logger.error("Unsupported resource type for worker resource.", new IllegalArgumentException());
break;
}
em.getTransaction().commit();
em.close();
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RegistryException(e.getMessage());
} finally {
if (em != null && em.isOpen()) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
em.close();
}
}
}
/**
* @param type child resource type
* @param name child resource name
* @return child resource
*/
public ExperimentCatResource get(ResourceType type, Object name) throws RegistryException {
ExperimentCatResource result = null;
EntityManager em = null;
try {
em = ExpCatResourceUtils.getEntityManager();
em.getTransaction().begin();
QueryGenerator generator;
Query q;
switch (type) {
case PROJECT:
generator = new QueryGenerator(PROJECT);
generator.setParameter(ProjectConstants.PROJECT_ID, name);
q = generator.selectQuery(em);
Project project = (Project) q.getSingleResult();
result = Utils.getResource(ResourceType.PROJECT, project);
break;
case EXPERIMENT:
generator = new QueryGenerator(EXPERIMENT);
generator.setParameter(ExperimentConstants.EXPERIMENT_ID, name);
q = generator.selectQuery(em);
Experiment experiment = (Experiment) q.getSingleResult();
result = Utils.getResource(ResourceType.EXPERIMENT, experiment);
break;
default:
logger.error("Unsupported resource type for worker resource.", new IllegalArgumentException());
break;
}
em.getTransaction().commit();
em.close();
} catch (Exception e) {
throw new RegistryException(e);
} finally {
if (em != null && em.isOpen()) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
em.close();
}
}
return result;
}
// public List<GFacJobDataResource> getGFacJobs(String serviceDescriptionId, String hostDescriptionId, String applicationDescriptionId){
// List<GFacJobDataResource> result = new ArrayList<GFacJobDataResource>();
// EntityManager em = ResourceUtils.getEntityManager();
// em.getTransaction().begin();
// QueryGenerator generator;
// Query q;
// generator = new QueryGenerator(GFAC_JOB_DATA);
// generator.setParameter(GFacJobDataConstants.SERVICE_DESC_ID, serviceDescriptionId);
// generator.setParameter(GFacJobDataConstants.HOST_DESC_ID, hostDescriptionId);
// generator.setParameter(GFacJobDataConstants.APP_DESC_ID, applicationDescriptionId);
// q = generator.selectQuery(em);
// for (Object o : q.getResultList()) {
// GFac_Job_Data gFacJobData = (GFac_Job_Data)o;
// result.add((GFacJobDataResource)Utils.getResource(ResourceType.GFAC_JOB_DATA, gFacJobData));
// }
// em.getTransaction().commit();
// em.close();
// return result;
// }
//
// public List<GFacJobStatusResource> getGFacJobStatuses(String jobId){
// List<GFacJobStatusResource> resourceList = new ArrayList<GFacJobStatusResource>();
// EntityManager em = ResourceUtils.getEntityManager();
// em.getTransaction().begin();
// QueryGenerator generator;
// Query q;
// generator = new QueryGenerator(GFAC_JOB_STATUS);
// generator.setParameter(GFacJobStatusConstants.LOCAL_JOB_ID, jobId);
// q = generator.selectQuery(em);
// for (Object result : q.getResultList()) {
// GFac_Job_Status gFacJobStatus = (GFac_Job_Status) result;
// GFacJobStatusResource gFacJobStatusResource =
// (GFacJobStatusResource)Utils.getResource(ResourceType.GFAC_JOB_STATUS, gFacJobStatus);
// resourceList.add(gFacJobStatusResource);
// }
// return resourceList;
// }
/**
* Method get all results of the given child resource type
*
* @param type child resource type
* @return list of child resources
*/
public List<ExperimentCatResource> get(ResourceType type) throws RegistryException {
return get(type, -1, -1, null, null);
}
/**
* Method get all results of the given child resource type with paginaltion and ordering
*
* @param type child resource type
* @param limit
* @param offset
* @param orderByIdentifier
* @param resultOrderType
* @return list of child resources
* @throws org.apache.airavata.registry.cpi.RegistryException
*/
public List<ExperimentCatResource> get(ResourceType type, int limit, int offset, Object orderByIdentifier,
ResultOrderType resultOrderType) throws RegistryException {
List<ExperimentCatResource> result = new ArrayList<ExperimentCatResource>();
EntityManager em = null;
try {
em = ExpCatResourceUtils.getEntityManager();
em.getTransaction().begin();
QueryGenerator generator;
Query q;
switch (type) {
case PROJECT:
generator = new QueryGenerator(PROJECT);
UserPK userPK = new UserPK();
userPK.setGatewayId(getGatewayId());
userPK.setUserName(user);
Users users = em.find(Users.class, userPK);
Gateway gatewayModel = em.find(Gateway.class, gatewayId);
generator.setParameter("users", users);
if (gatewayModel != null) {
generator.setParameter("gateway", gatewayModel);
}
//ordering - only supported only by CREATION_TIME
if (orderByIdentifier != null && resultOrderType != null
&& orderByIdentifier.equals(Constants.FieldConstants.ProjectConstants.CREATION_TIME)) {
q = generator.selectQuery(em, ProjectConstants.CREATION_TIME, resultOrderType);
} else {
q = generator.selectQuery(em);
}
//pagination
if (limit > 0 && offset >= 0) {
q.setFirstResult(offset);
q.setMaxResults(limit);
}
for (Object o : q.getResultList()) {
Project project = (Project) o;
org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource projectResource = (org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource) Utils.getResource(ResourceType.PROJECT, project);
result.add(projectResource);
}
break;
case EXPERIMENT:
generator = new QueryGenerator(EXPERIMENT);
generator.setParameter(ExperimentConstants.USER_NAME, getUser());
//ordering - only supported only by CREATION_TIME
if (orderByIdentifier != null && resultOrderType != null
&& orderByIdentifier.equals(Constants.FieldConstants.ProjectConstants.CREATION_TIME)) {
q = generator.selectQuery(em, ExperimentConstants.CREATION_TIME, resultOrderType);
} else {
q = generator.selectQuery(em);
}
//pagination
if (limit > 0 && offset >= 0) {
q.setFirstResult(offset);
q.setMaxResults(limit);
}
for (Object o : q.getResultList()) {
Experiment experiment = (Experiment) o;
ExperimentResource experimentResource = (ExperimentResource) Utils.getResource(ResourceType.EXPERIMENT, experiment);
result.add(experimentResource);
}
break;
default:
logger.error("Unsupported resource type for worker resource.", new IllegalArgumentException());
break;
}
em.getTransaction().commit();
em.close();
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RegistryException(e);
} finally {
if (em != null && em.isOpen()) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
em.close();
}
}
return result;
}
/**
* save gateway worker to database
*/
public void save() throws RegistryException {
EntityManager em = null;
try {
em = ExpCatResourceUtils.getEntityManager();
GatewayWorkerPK gatewayWorkerPK = new GatewayWorkerPK();
gatewayWorkerPK.setGatewayId(gatewayId);
gatewayWorkerPK.setUserName(user);
GatewayWorker existingWorker = em.find(GatewayWorker.class, gatewayWorkerPK);
em.close();
em = ExpCatResourceUtils.getEntityManager();
em.getTransaction().begin();
GatewayWorker gatewayWorker = new GatewayWorker();
gatewayWorker.setUserName(user);
gatewayWorker.setGatewayId(gatewayId);
if (existingWorker != null) {
existingWorker.setUserName(user);
existingWorker.setGatewayId(gatewayId);
gatewayWorker = em.merge(existingWorker);
} else {
em.persist(gatewayWorker);
}
em.getTransaction().commit();
em.close();
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RegistryException(e);
} finally {
if (em != null && em.isOpen()) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
em.close();
}
}
}
/**
* @return user name
*/
public String getUser() {
return user;
}
/**
* @param user user name
*/
public void setUser(String user) {
this.user = user;
}
/**
* @param id project id
* @return whether the project is available under the user
*/
public boolean isProjectExists(String id) throws RegistryException {
return isExists(ResourceType.PROJECT, id);
}
/**
* @param projectId project id
* @return project resource for the user
*/
public org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource createProject(String projectId) throws RegistryException {
org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource project = (org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource) create(ResourceType.PROJECT);
project.setId(projectId);
return project;
}
/**
* @param id project id
* @return project resource
*/
public org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource getProject(String id) throws RegistryException {
return (org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource) get(ResourceType.PROJECT, id);
}
/**
* @param id project id
*/
public void removeProject(String id) throws RegistryException {
remove(ResourceType.PROJECT, id);
}
/**
* Get projects list of user
*
* @return list of projects for the user
*/
public List<org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource> getProjects() throws RegistryException {
return getProjects(-1, -1, null, null);
}
/**
* Get projects list of user with pagination and ordering
*
* @return list of projects for the user
*/
public List<org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource> getProjects(int limit, int offset, Object orderByIdentifier,
ResultOrderType resultOrderType) throws RegistryException {
List<org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource> result = new ArrayList<org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource>();
List<ExperimentCatResource> list = get(ResourceType.PROJECT, limit, offset, orderByIdentifier, resultOrderType);
for (ExperimentCatResource resource : list) {
result.add((org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource) resource);
}
return result;
}
/**
* @param name experiment name
* @return whether experiment is already exist for the given user
*/
public boolean isExperimentExists(String name) throws RegistryException {
return isExists(ResourceType.EXPERIMENT, name);
}
/**
* @param name experiment name
* @return experiment resource
*/
public ExperimentResource getExperiment(String name) throws RegistryException {
return (ExperimentResource) get(ResourceType.EXPERIMENT, name);
}
//
// public GFacJobDataResource getGFacJob(String jobId){
// return (GFacJobDataResource)get(ResourceType.GFAC_JOB_DATA,jobId);
// }
/**
* Method to get list of expeirments of user
*
* @return list of experiments for the user
*/
public List<ExperimentResource> getExperiments() throws RegistryException {
return getExperiments(-1, -1, null, null);
}
/**
* Method to get list of experiments of user with pagination and ordering
*
* @param limit
* @param offset
* @param orderByIdentifier
* @param resultOrderType
* @return
* @throws org.apache.airavata.registry.cpi.RegistryException
*/
public List<ExperimentResource> getExperiments(int limit, int offset, Object orderByIdentifier,
ResultOrderType resultOrderType) throws RegistryException {
List<ExperimentResource> result = new ArrayList<ExperimentResource>();
List<ExperimentCatResource> list = get(ResourceType.EXPERIMENT, limit, offset, orderByIdentifier, resultOrderType);
for (ExperimentCatResource resource : list) {
result.add((ExperimentResource) resource);
}
return result;
}
/**
* @param experimentId experiment name
*/
public void removeExperiment(String experimentId) throws RegistryException {
remove(ResourceType.EXPERIMENT, experimentId);
}
/**
* To search the projects of user with the given filter criteria and retrieve the results with
* pagination support. Results can be ordered based on an identifier (i.e column) either ASC or
* DESC. But in the current implementation ordering is only supported based on the project
* creation time
*
* @param filters
* @param limit
* @param offset
* @param orderByIdentifier
* @param resultOrderType
* @return
* @throws org.apache.airavata.registry.cpi.RegistryException
*/
public List<org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource> searchProjects(Map<String, String> filters, int limit,
int offset, Object orderByIdentifier, ResultOrderType resultOrderType) throws RegistryException {
List<org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource> result = new ArrayList<org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource>();
EntityManager em = null;
try {
String query = "SELECT DISTINCT p from Project p WHERE ";
if (filters != null && filters.size() != 0) {
for (String field : filters.keySet()) {
String filterVal = filters.get(field);
if (field.equals(ProjectConstants.USERNAME)) {
query += "p." + field + "= '" + filterVal + "' AND ";
} else if (field.equals(ProjectConstants.GATEWAY_ID)) {
query += "p." + field + "= '" + filterVal + "' AND ";
} else {
if (filterVal.contains("*")) {
filterVal = filterVal.replaceAll("\\*", "");
}
query += "p." + field + " LIKE '%" + filterVal + "%' AND ";
}
}
}
query = query.substring(0, query.length() - 5);
//ordering
if (orderByIdentifier != null && resultOrderType != null
&& orderByIdentifier.equals(Constants.FieldConstants.ProjectConstants.CREATION_TIME)) {
String order = (resultOrderType == ResultOrderType.ASC) ? "ASC" : "DESC";
query += " ORDER BY p." + ProjectConstants.CREATION_TIME + " " + order;
}
em = ExpCatResourceUtils.getEntityManager();
em.getTransaction().begin();
Query q;
//pagination
if (offset >= 0 && limit >= 0) {
q = em.createQuery(query).setFirstResult(offset).setMaxResults(limit);
} else {
q = em.createQuery(query);
}
List resultList = q.getResultList();
for (Object o : resultList) {
Project project = (Project) o;
org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource projectResource =
(ProjectResource) Utils.getResource(ResourceType.PROJECT, project);
result.add(projectResource);
}
em.getTransaction().commit();
em.close();
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RegistryException(e);
} finally {
if (em != null && em.isOpen()) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
em.close();
}
}
return result;
}
/**
* To search the experiments of user with the given time period and filter criteria and retrieve the results with
* pagination support. Results can be ordered based on an identifier (i.e column) either ASC or
* DESC. But in the current implementation ordering is only supported based on creationTime. Also if
* time period values i.e fromTime and toTime are null they will be ignored.
*
* @param fromTime
* @param toTime
* @param filters
* @param limit
* @param offset
* @param orderByIdentifier
* @param resultOrderType
* @return
* @throws org.apache.airavata.registry.cpi.RegistryException
*/
public List<ExperimentSummaryResource> searchExperiments(List<String> accessibleIds, Timestamp fromTime, Timestamp toTime, Map<String, String> filters, int limit,
int offset, Object orderByIdentifier, ResultOrderType resultOrderType) throws RegistryException {
List<ExperimentSummaryResource> result = new ArrayList();
EntityManager em = null;
try {
String query = "SELECT e FROM ExperimentSummary e " +
"WHERE ";
// FIXME There is a performance bottleneck for using IN clause. Try using temporary tables ?
if(accessibleIds != null){
query += " e.experimentId IN (";
for(String id : accessibleIds)
query += (id + ",");
query = query.substring(0, query.length()-1) + ") AND ";
}
if (filters.get(ExperimentStatusConstants.STATE) != null) {
String experimentState = ExperimentState.valueOf(filters.get(ExperimentStatusConstants.STATE)).toString();
query += "e.state='" + experimentState + "' AND ";
}
if (toTime != null && fromTime != null && toTime.after(fromTime)) {
query += "e.creationTime > '" + fromTime + "' " + "AND e.creationTime <'" + toTime + "' AND ";
}
filters.remove(ExperimentStatusConstants.STATE);
if (filters != null && filters.size() != 0) {
for (String field : filters.keySet()) {
String filterVal = filters.get(field);
if (field.equals(ExperimentConstants.USER_NAME)) {
query += "e." + field + "= '" + filterVal + "' AND ";
} else if (field.equals(ExperimentConstants.GATEWAY_ID)) {
query += "e." + field + "= '" + filterVal + "' AND ";
} else if (field.equals(ExperimentConstants.PROJECT_ID)) {
query += "e." + field + "= '" + filterVal + "' AND ";
} else {
if (filterVal.contains("*")) {
filterVal = filterVal.replaceAll("\\*", "");
}
query += "e." + field + " LIKE '%" + filterVal + "%' AND ";
}
}
}
query = query.substring(0, query.length() - 5);
//ordering
if (orderByIdentifier != null && resultOrderType != null
&& orderByIdentifier.equals(Constants.FieldConstants.ExperimentConstants.CREATION_TIME)) {
String order = (resultOrderType == ResultOrderType.ASC) ? "ASC" : "DESC";
query += " ORDER BY e." + ExperimentConstants.CREATION_TIME + " " + order;
}
em = ExpCatResourceUtils.getEntityManager();
em.getTransaction().begin();
Query q;
//pagination
if (offset >= 0 && limit >= 0) {
q = em.createQuery(query).setFirstResult(offset).setMaxResults(limit);
} else {
q = em.createQuery(query);
}
List resultList = q.getResultList();
for (Object o : resultList) {
ExperimentSummary experimentSummary = (ExperimentSummary) o;
ExperimentSummaryResource experimentSummaryResource =
(ExperimentSummaryResource) Utils.getResource(ResourceType.EXPERIMENT_SUMMARY,
experimentSummary);
result.add(experimentSummaryResource);
}
em.getTransaction().commit();
em.close();
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RegistryException(e);
} finally {
if (em != null && em.isOpen()) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
em.close();
}
}
return result;
}
/**
* Method to get experiment statistics for a gateway
*
* @param gatewayId
* @param fromTime
* @param toTime
* @return
* @throws org.apache.airavata.registry.cpi.RegistryException
*/
public ExperimentStatisticsResource getExperimentStatistics(String gatewayId, Timestamp fromTime, Timestamp toTime) throws RegistryException {
ExperimentStatisticsResource experimentStatisticsResource = new ExperimentStatisticsResource();
List<ExperimentSummaryResource> allExperiments = getExperimentStatisticsForState(null, gatewayId, fromTime, toTime);
experimentStatisticsResource.setAllExperimentCount(allExperiments.size());
experimentStatisticsResource.setAllExperiments(allExperiments);
List<ExperimentSummaryResource> createdExperiments = getExperimentStatisticsForState(ExperimentState.CREATED, gatewayId, fromTime, toTime);
createdExperiments.addAll(getExperimentStatisticsForState(ExperimentState.VALIDATED, gatewayId, fromTime, toTime));
experimentStatisticsResource.setCreatedExperimentCount(createdExperiments.size());
experimentStatisticsResource.setCreatedExperiments(createdExperiments);
List<ExperimentSummaryResource> runningExperiments = getExperimentStatisticsForState(ExperimentState.EXECUTING, gatewayId, fromTime, toTime);
runningExperiments.addAll(getExperimentStatisticsForState(ExperimentState.SCHEDULED, gatewayId, fromTime, toTime));
runningExperiments.addAll(getExperimentStatisticsForState(ExperimentState.LAUNCHED, gatewayId, fromTime, toTime));
experimentStatisticsResource.setRunningExperimentCount(runningExperiments.size());
experimentStatisticsResource.setRunningExperiments(runningExperiments);
List<ExperimentSummaryResource> completedExperiments = getExperimentStatisticsForState(ExperimentState.COMPLETED, gatewayId, fromTime, toTime);
experimentStatisticsResource.setCompletedExperimentCount(completedExperiments.size());
experimentStatisticsResource.setCompletedExperiments(completedExperiments);
List<ExperimentSummaryResource> failedExperiments = getExperimentStatisticsForState(ExperimentState.FAILED, gatewayId, fromTime, toTime);
experimentStatisticsResource.setFailedExperimentCount(failedExperiments.size());
experimentStatisticsResource.setFailedExperiments(failedExperiments);
List<ExperimentSummaryResource> cancelledExperiments = getExperimentStatisticsForState(ExperimentState.CANCELED, gatewayId, fromTime, toTime);
cancelledExperiments.addAll(getExperimentStatisticsForState(ExperimentState.CANCELING, gatewayId, fromTime, toTime));
experimentStatisticsResource.setCancelledExperimentCount(cancelledExperiments.size());
experimentStatisticsResource.setCancelledExperiments(cancelledExperiments);
return experimentStatisticsResource;
}
private List<ExperimentSummaryResource> getExperimentStatisticsForState(
ExperimentState expState, String gatewayId, Timestamp fromTime, Timestamp toTime) throws RegistryException {
EntityManager em = null;
List<ExperimentSummaryResource> result = new ArrayList();
try {
String query = "SELECT e FROM ExperimentSummary e " +
"WHERE ";
if (expState != null) {
query += "e.state='" + expState.toString() + "' AND ";
}
query += "e.creationTime > '" + fromTime + "' " + "AND e.creationTime <'" + toTime + "' AND ";
query += "e." + ExperimentConstants.GATEWAY_ID + "= '" + gatewayId + "' ORDER BY e.creationTime DESC";
em = ExpCatResourceUtils.getEntityManager();
em.getTransaction().begin();
Query q = em.createQuery(query);
List resultList = q.getResultList();
for (Object o : resultList) {
ExperimentSummary experimentSummary = (ExperimentSummary) o;
ExperimentSummaryResource experimentSummaryResource =
(ExperimentSummaryResource) Utils.getResource(ResourceType.EXPERIMENT_SUMMARY,
experimentSummary);
result.add(experimentSummaryResource);
}
em.getTransaction().commit();
em.close();
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RegistryException(e);
} finally {
if (em != null && em.isOpen()) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
em.close();
}
}
return result;
}
}
| modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/experiment/catalog/resources/WorkerResource.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.airavata.registry.core.experiment.catalog.resources;
import org.apache.airavata.model.status.ExperimentState;
import org.apache.airavata.registry.core.experiment.catalog.ExpCatResourceUtils;
import org.apache.airavata.registry.core.experiment.catalog.ExperimentCatResource;
import org.apache.airavata.registry.core.experiment.catalog.ResourceType;
import org.apache.airavata.registry.core.experiment.catalog.model.*;
import org.apache.airavata.registry.core.experiment.catalog.utils.QueryGenerator;
import org.apache.airavata.registry.cpi.RegistryException;
import org.apache.airavata.registry.cpi.ResultOrderType;
import org.apache.airavata.registry.cpi.utils.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class WorkerResource extends AbstractExpCatResource {
private final static Logger logger = LoggerFactory.getLogger(WorkerResource.class);
private String user;
private String gatewayId;
public WorkerResource() {
}
public WorkerResource(String user, String gatewayId) {
this.user = user;
this.gatewayId = gatewayId;
}
public String getGatewayId() {
return gatewayId;
}
public void setGatewayId(String gatewayId) {
this.gatewayId = gatewayId;
}
/**
* Gateway worker can create child data structures such as projects and user workflows
*
* @param type child resource type
* @return child resource
*/
public ExperimentCatResource create(ResourceType type) throws RegistryException {
ExperimentCatResource result = null;
switch (type) {
case PROJECT:
org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource projectResource = new org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource();
projectResource.setWorker(this);
projectResource.setGatewayId(gatewayId);
result = projectResource;
break;
case EXPERIMENT:
ExperimentResource experimentResource = new ExperimentResource();
experimentResource.setUserName(user);
experimentResource.setGatewayExecutionId(gatewayId);
result = experimentResource;
break;
default:
logger.error("Unsupported resource type for worker resource.", new IllegalArgumentException());
throw new IllegalArgumentException("Unsupported resource type for worker resource.");
}
return result;
}
/**
* @param type child resource type
* @param name child resource name
*/
public void remove(ResourceType type, Object name) throws RegistryException {
EntityManager em = null;
try {
em = ExpCatResourceUtils.getEntityManager();
em.getTransaction().begin();
Query q;
QueryGenerator generator;
switch (type) {
case PROJECT:
generator = new QueryGenerator(PROJECT);
generator.setParameter(ProjectConstants.PROJECT_ID, name);
q = generator.deleteQuery(em);
q.executeUpdate();
break;
case EXPERIMENT:
generator = new QueryGenerator(EXPERIMENT);
generator.setParameter(ExperimentConstants.EXPERIMENT_ID, name);
q = generator.deleteQuery(em);
q.executeUpdate();
break;
default:
logger.error("Unsupported resource type for worker resource.", new IllegalArgumentException());
break;
}
em.getTransaction().commit();
em.close();
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RegistryException(e.getMessage());
} finally {
if (em != null && em.isOpen()) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
em.close();
}
}
}
/**
* @param type child resource type
* @param name child resource name
* @return child resource
*/
public ExperimentCatResource get(ResourceType type, Object name) throws RegistryException {
ExperimentCatResource result = null;
EntityManager em = null;
try {
em = ExpCatResourceUtils.getEntityManager();
em.getTransaction().begin();
QueryGenerator generator;
Query q;
switch (type) {
case PROJECT:
generator = new QueryGenerator(PROJECT);
generator.setParameter(ProjectConstants.PROJECT_ID, name);
q = generator.selectQuery(em);
Project project = (Project) q.getSingleResult();
result = Utils.getResource(ResourceType.PROJECT, project);
break;
case EXPERIMENT:
generator = new QueryGenerator(EXPERIMENT);
generator.setParameter(ExperimentConstants.EXPERIMENT_ID, name);
q = generator.selectQuery(em);
Experiment experiment = (Experiment) q.getSingleResult();
result = Utils.getResource(ResourceType.EXPERIMENT, experiment);
break;
default:
logger.error("Unsupported resource type for worker resource.", new IllegalArgumentException());
break;
}
em.getTransaction().commit();
em.close();
} catch (Exception e) {
throw new RegistryException(e);
} finally {
if (em != null && em.isOpen()) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
em.close();
}
}
return result;
}
// public List<GFacJobDataResource> getGFacJobs(String serviceDescriptionId, String hostDescriptionId, String applicationDescriptionId){
// List<GFacJobDataResource> result = new ArrayList<GFacJobDataResource>();
// EntityManager em = ResourceUtils.getEntityManager();
// em.getTransaction().begin();
// QueryGenerator generator;
// Query q;
// generator = new QueryGenerator(GFAC_JOB_DATA);
// generator.setParameter(GFacJobDataConstants.SERVICE_DESC_ID, serviceDescriptionId);
// generator.setParameter(GFacJobDataConstants.HOST_DESC_ID, hostDescriptionId);
// generator.setParameter(GFacJobDataConstants.APP_DESC_ID, applicationDescriptionId);
// q = generator.selectQuery(em);
// for (Object o : q.getResultList()) {
// GFac_Job_Data gFacJobData = (GFac_Job_Data)o;
// result.add((GFacJobDataResource)Utils.getResource(ResourceType.GFAC_JOB_DATA, gFacJobData));
// }
// em.getTransaction().commit();
// em.close();
// return result;
// }
//
// public List<GFacJobStatusResource> getGFacJobStatuses(String jobId){
// List<GFacJobStatusResource> resourceList = new ArrayList<GFacJobStatusResource>();
// EntityManager em = ResourceUtils.getEntityManager();
// em.getTransaction().begin();
// QueryGenerator generator;
// Query q;
// generator = new QueryGenerator(GFAC_JOB_STATUS);
// generator.setParameter(GFacJobStatusConstants.LOCAL_JOB_ID, jobId);
// q = generator.selectQuery(em);
// for (Object result : q.getResultList()) {
// GFac_Job_Status gFacJobStatus = (GFac_Job_Status) result;
// GFacJobStatusResource gFacJobStatusResource =
// (GFacJobStatusResource)Utils.getResource(ResourceType.GFAC_JOB_STATUS, gFacJobStatus);
// resourceList.add(gFacJobStatusResource);
// }
// return resourceList;
// }
/**
* Method get all results of the given child resource type
*
* @param type child resource type
* @return list of child resources
*/
public List<ExperimentCatResource> get(ResourceType type) throws RegistryException {
return get(type, -1, -1, null, null);
}
/**
* Method get all results of the given child resource type with paginaltion and ordering
*
* @param type child resource type
* @param limit
* @param offset
* @param orderByIdentifier
* @param resultOrderType
* @return list of child resources
* @throws org.apache.airavata.registry.cpi.RegistryException
*/
public List<ExperimentCatResource> get(ResourceType type, int limit, int offset, Object orderByIdentifier,
ResultOrderType resultOrderType) throws RegistryException {
List<ExperimentCatResource> result = new ArrayList<ExperimentCatResource>();
EntityManager em = null;
try {
em = ExpCatResourceUtils.getEntityManager();
em.getTransaction().begin();
QueryGenerator generator;
Query q;
switch (type) {
case PROJECT:
generator = new QueryGenerator(PROJECT);
UserPK userPK = new UserPK();
userPK.setGatewayId(getGatewayId());
userPK.setUserName(user);
Users users = em.find(Users.class, userPK);
Gateway gatewayModel = em.find(Gateway.class, gatewayId);
generator.setParameter("users", users);
if (gatewayModel != null) {
generator.setParameter("gateway", gatewayModel);
}
//ordering - only supported only by CREATION_TIME
if (orderByIdentifier != null && resultOrderType != null
&& orderByIdentifier.equals(Constants.FieldConstants.ProjectConstants.CREATION_TIME)) {
q = generator.selectQuery(em, ProjectConstants.CREATION_TIME, resultOrderType);
} else {
q = generator.selectQuery(em);
}
//pagination
if (limit > 0 && offset >= 0) {
q.setFirstResult(offset);
q.setMaxResults(limit);
}
for (Object o : q.getResultList()) {
Project project = (Project) o;
org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource projectResource = (org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource) Utils.getResource(ResourceType.PROJECT, project);
result.add(projectResource);
}
break;
case EXPERIMENT:
generator = new QueryGenerator(EXPERIMENT);
generator.setParameter(ExperimentConstants.USER_NAME, getUser());
//ordering - only supported only by CREATION_TIME
if (orderByIdentifier != null && resultOrderType != null
&& orderByIdentifier.equals(Constants.FieldConstants.ProjectConstants.CREATION_TIME)) {
q = generator.selectQuery(em, ExperimentConstants.CREATION_TIME, resultOrderType);
} else {
q = generator.selectQuery(em);
}
//pagination
if (limit > 0 && offset >= 0) {
q.setFirstResult(offset);
q.setMaxResults(limit);
}
for (Object o : q.getResultList()) {
Experiment experiment = (Experiment) o;
ExperimentResource experimentResource = (ExperimentResource) Utils.getResource(ResourceType.EXPERIMENT, experiment);
result.add(experimentResource);
}
break;
default:
logger.error("Unsupported resource type for worker resource.", new IllegalArgumentException());
break;
}
em.getTransaction().commit();
em.close();
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RegistryException(e);
} finally {
if (em != null && em.isOpen()) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
em.close();
}
}
return result;
}
/**
* save gateway worker to database
*/
public void save() throws RegistryException {
EntityManager em = null;
try {
em = ExpCatResourceUtils.getEntityManager();
GatewayWorkerPK gatewayWorkerPK = new GatewayWorkerPK();
gatewayWorkerPK.setGatewayId(gatewayId);
gatewayWorkerPK.setUserName(user);
GatewayWorker existingWorker = em.find(GatewayWorker.class, gatewayWorkerPK);
em.close();
em = ExpCatResourceUtils.getEntityManager();
em.getTransaction().begin();
GatewayWorker gatewayWorker = new GatewayWorker();
gatewayWorker.setUserName(user);
gatewayWorker.setGatewayId(gatewayId);
if (existingWorker != null) {
existingWorker.setUserName(user);
existingWorker.setGatewayId(gatewayId);
gatewayWorker = em.merge(existingWorker);
} else {
em.persist(gatewayWorker);
}
em.getTransaction().commit();
em.close();
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RegistryException(e);
} finally {
if (em != null && em.isOpen()) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
em.close();
}
}
}
/**
* @return user name
*/
public String getUser() {
return user;
}
/**
* @param user user name
*/
public void setUser(String user) {
this.user = user;
}
/**
* @param id project id
* @return whether the project is available under the user
*/
public boolean isProjectExists(String id) throws RegistryException {
return isExists(ResourceType.PROJECT, id);
}
/**
* @param projectId project id
* @return project resource for the user
*/
public org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource createProject(String projectId) throws RegistryException {
org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource project = (org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource) create(ResourceType.PROJECT);
project.setId(projectId);
return project;
}
/**
* @param id project id
* @return project resource
*/
public org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource getProject(String id) throws RegistryException {
return (org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource) get(ResourceType.PROJECT, id);
}
/**
* @param id project id
*/
public void removeProject(String id) throws RegistryException {
remove(ResourceType.PROJECT, id);
}
/**
* Get projects list of user
*
* @return list of projects for the user
*/
public List<org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource> getProjects() throws RegistryException {
return getProjects(-1, -1, null, null);
}
/**
* Get projects list of user with pagination and ordering
*
* @return list of projects for the user
*/
public List<org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource> getProjects(int limit, int offset, Object orderByIdentifier,
ResultOrderType resultOrderType) throws RegistryException {
List<org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource> result = new ArrayList<org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource>();
List<ExperimentCatResource> list = get(ResourceType.PROJECT, limit, offset, orderByIdentifier, resultOrderType);
for (ExperimentCatResource resource : list) {
result.add((org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource) resource);
}
return result;
}
/**
* @param name experiment name
* @return whether experiment is already exist for the given user
*/
public boolean isExperimentExists(String name) throws RegistryException {
return isExists(ResourceType.EXPERIMENT, name);
}
/**
* @param name experiment name
* @return experiment resource
*/
public ExperimentResource getExperiment(String name) throws RegistryException {
return (ExperimentResource) get(ResourceType.EXPERIMENT, name);
}
//
// public GFacJobDataResource getGFacJob(String jobId){
// return (GFacJobDataResource)get(ResourceType.GFAC_JOB_DATA,jobId);
// }
/**
* Method to get list of expeirments of user
*
* @return list of experiments for the user
*/
public List<ExperimentResource> getExperiments() throws RegistryException {
return getExperiments(-1, -1, null, null);
}
/**
* Method to get list of experiments of user with pagination and ordering
*
* @param limit
* @param offset
* @param orderByIdentifier
* @param resultOrderType
* @return
* @throws org.apache.airavata.registry.cpi.RegistryException
*/
public List<ExperimentResource> getExperiments(int limit, int offset, Object orderByIdentifier,
ResultOrderType resultOrderType) throws RegistryException {
List<ExperimentResource> result = new ArrayList<ExperimentResource>();
List<ExperimentCatResource> list = get(ResourceType.EXPERIMENT, limit, offset, orderByIdentifier, resultOrderType);
for (ExperimentCatResource resource : list) {
result.add((ExperimentResource) resource);
}
return result;
}
/**
* @param experimentId experiment name
*/
public void removeExperiment(String experimentId) throws RegistryException {
remove(ResourceType.EXPERIMENT, experimentId);
}
/**
* To search the projects of user with the given filter criteria and retrieve the results with
* pagination support. Results can be ordered based on an identifier (i.e column) either ASC or
* DESC. But in the current implementation ordering is only supported based on the project
* creation time
*
* @param filters
* @param limit
* @param offset
* @param orderByIdentifier
* @param resultOrderType
* @return
* @throws org.apache.airavata.registry.cpi.RegistryException
*/
public List<org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource> searchProjects(Map<String, String> filters, int limit,
int offset, Object orderByIdentifier, ResultOrderType resultOrderType) throws RegistryException {
List<org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource> result = new ArrayList<org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource>();
EntityManager em = null;
try {
String query = "SELECT DISTINCT p from Project p WHERE ";
if (filters != null && filters.size() != 0) {
for (String field : filters.keySet()) {
String filterVal = filters.get(field);
if (field.equals(ProjectConstants.USERNAME)) {
query += "p." + field + "= '" + filterVal + "' AND ";
} else if (field.equals(ProjectConstants.GATEWAY_ID)) {
query += "p." + field + "= '" + filterVal + "' AND ";
} else {
if (filterVal.contains("*")) {
filterVal = filterVal.replaceAll("\\*", "");
}
query += "p." + field + " LIKE '%" + filterVal + "%' AND ";
}
}
}
query = query.substring(0, query.length() - 5);
//ordering
if (orderByIdentifier != null && resultOrderType != null
&& orderByIdentifier.equals(Constants.FieldConstants.ProjectConstants.CREATION_TIME)) {
String order = (resultOrderType == ResultOrderType.ASC) ? "ASC" : "DESC";
query += " ORDER BY p." + ProjectConstants.CREATION_TIME + " " + order;
}
em = ExpCatResourceUtils.getEntityManager();
em.getTransaction().begin();
Query q;
//pagination
if (offset >= 0 && limit >= 0) {
q = em.createQuery(query).setFirstResult(offset).setMaxResults(limit);
} else {
q = em.createQuery(query);
}
List resultList = q.getResultList();
for (Object o : resultList) {
Project project = (Project) o;
org.apache.airavata.registry.core.experiment.catalog.resources.ProjectResource projectResource =
(ProjectResource) Utils.getResource(ResourceType.PROJECT, project);
result.add(projectResource);
}
em.getTransaction().commit();
em.close();
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RegistryException(e);
} finally {
if (em != null && em.isOpen()) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
em.close();
}
}
return result;
}
/**
* To search the experiments of user with the given time period and filter criteria and retrieve the results with
* pagination support. Results can be ordered based on an identifier (i.e column) either ASC or
* DESC. But in the current implementation ordering is only supported based on creationTime. Also if
* time period values i.e fromTime and toTime are null they will be ignored.
*
* @param fromTime
* @param toTime
* @param filters
* @param limit
* @param offset
* @param orderByIdentifier
* @param resultOrderType
* @return
* @throws org.apache.airavata.registry.cpi.RegistryException
*/
public List<ExperimentSummaryResource> searchExperiments(List<String> accessibleIds, Timestamp fromTime, Timestamp toTime, Map<String, String> filters, int limit,
int offset, Object orderByIdentifier, ResultOrderType resultOrderType) throws RegistryException {
List<ExperimentSummaryResource> result = new ArrayList();
EntityManager em = null;
try {
String query = "SELECT e FROM ExperimentSummary e " +
"WHERE ";
// FIXME There is a performance bottleneck for using IN clause. Try using temporary tables ?
if(accessibleIds != null){
query += " e.experimentId IN (";
for(String id : accessibleIds)
query += (id + ",");
query = query.substring(0, query.length()-1) + ") ";
}
if (filters.get(ExperimentStatusConstants.STATE) != null) {
String experimentState = ExperimentState.valueOf(filters.get(ExperimentStatusConstants.STATE)).toString();
query += "e.state='" + experimentState + "' AND ";
}
if (toTime != null && fromTime != null && toTime.after(fromTime)) {
query += "e.creationTime > '" + fromTime + "' " + "AND e.creationTime <'" + toTime + "' AND ";
}
filters.remove(ExperimentStatusConstants.STATE);
if (filters != null && filters.size() != 0) {
for (String field : filters.keySet()) {
String filterVal = filters.get(field);
if (field.equals(ExperimentConstants.USER_NAME)) {
query += "e." + field + "= '" + filterVal + "' AND ";
} else if (field.equals(ExperimentConstants.GATEWAY_ID)) {
query += "e." + field + "= '" + filterVal + "' AND ";
} else if (field.equals(ExperimentConstants.PROJECT_ID)) {
query += "e." + field + "= '" + filterVal + "' AND ";
} else {
if (filterVal.contains("*")) {
filterVal = filterVal.replaceAll("\\*", "");
}
query += "e." + field + " LIKE '%" + filterVal + "%' AND ";
}
}
}
query = query.substring(0, query.length() - 5);
//ordering
if (orderByIdentifier != null && resultOrderType != null
&& orderByIdentifier.equals(Constants.FieldConstants.ExperimentConstants.CREATION_TIME)) {
String order = (resultOrderType == ResultOrderType.ASC) ? "ASC" : "DESC";
query += " ORDER BY e." + ExperimentConstants.CREATION_TIME + " " + order;
}
em = ExpCatResourceUtils.getEntityManager();
em.getTransaction().begin();
Query q;
//pagination
if (offset >= 0 && limit >= 0) {
q = em.createQuery(query).setFirstResult(offset).setMaxResults(limit);
} else {
q = em.createQuery(query);
}
List resultList = q.getResultList();
for (Object o : resultList) {
ExperimentSummary experimentSummary = (ExperimentSummary) o;
ExperimentSummaryResource experimentSummaryResource =
(ExperimentSummaryResource) Utils.getResource(ResourceType.EXPERIMENT_SUMMARY,
experimentSummary);
result.add(experimentSummaryResource);
}
em.getTransaction().commit();
em.close();
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RegistryException(e);
} finally {
if (em != null && em.isOpen()) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
em.close();
}
}
return result;
}
/**
* Method to get experiment statistics for a gateway
*
* @param gatewayId
* @param fromTime
* @param toTime
* @return
* @throws org.apache.airavata.registry.cpi.RegistryException
*/
public ExperimentStatisticsResource getExperimentStatistics(String gatewayId, Timestamp fromTime, Timestamp toTime) throws RegistryException {
ExperimentStatisticsResource experimentStatisticsResource = new ExperimentStatisticsResource();
List<ExperimentSummaryResource> allExperiments = getExperimentStatisticsForState(null, gatewayId, fromTime, toTime);
experimentStatisticsResource.setAllExperimentCount(allExperiments.size());
experimentStatisticsResource.setAllExperiments(allExperiments);
List<ExperimentSummaryResource> createdExperiments = getExperimentStatisticsForState(ExperimentState.CREATED, gatewayId, fromTime, toTime);
createdExperiments.addAll(getExperimentStatisticsForState(ExperimentState.VALIDATED, gatewayId, fromTime, toTime));
experimentStatisticsResource.setCreatedExperimentCount(createdExperiments.size());
experimentStatisticsResource.setCreatedExperiments(createdExperiments);
List<ExperimentSummaryResource> runningExperiments = getExperimentStatisticsForState(ExperimentState.EXECUTING, gatewayId, fromTime, toTime);
runningExperiments.addAll(getExperimentStatisticsForState(ExperimentState.SCHEDULED, gatewayId, fromTime, toTime));
runningExperiments.addAll(getExperimentStatisticsForState(ExperimentState.LAUNCHED, gatewayId, fromTime, toTime));
experimentStatisticsResource.setRunningExperimentCount(runningExperiments.size());
experimentStatisticsResource.setRunningExperiments(runningExperiments);
List<ExperimentSummaryResource> completedExperiments = getExperimentStatisticsForState(ExperimentState.COMPLETED, gatewayId, fromTime, toTime);
experimentStatisticsResource.setCompletedExperimentCount(completedExperiments.size());
experimentStatisticsResource.setCompletedExperiments(completedExperiments);
List<ExperimentSummaryResource> failedExperiments = getExperimentStatisticsForState(ExperimentState.FAILED, gatewayId, fromTime, toTime);
experimentStatisticsResource.setFailedExperimentCount(failedExperiments.size());
experimentStatisticsResource.setFailedExperiments(failedExperiments);
List<ExperimentSummaryResource> cancelledExperiments = getExperimentStatisticsForState(ExperimentState.CANCELED, gatewayId, fromTime, toTime);
cancelledExperiments.addAll(getExperimentStatisticsForState(ExperimentState.CANCELING, gatewayId, fromTime, toTime));
experimentStatisticsResource.setCancelledExperimentCount(cancelledExperiments.size());
experimentStatisticsResource.setCancelledExperiments(cancelledExperiments);
return experimentStatisticsResource;
}
private List<ExperimentSummaryResource> getExperimentStatisticsForState(
ExperimentState expState, String gatewayId, Timestamp fromTime, Timestamp toTime) throws RegistryException {
EntityManager em = null;
List<ExperimentSummaryResource> result = new ArrayList();
try {
String query = "SELECT e FROM ExperimentSummary e " +
"WHERE ";
if (expState != null) {
query += "e.state='" + expState.toString() + "' AND ";
}
query += "e.creationTime > '" + fromTime + "' " + "AND e.creationTime <'" + toTime + "' AND ";
query += "e." + ExperimentConstants.GATEWAY_ID + "= '" + gatewayId + "' ORDER BY e.creationTime DESC";
em = ExpCatResourceUtils.getEntityManager();
em.getTransaction().begin();
Query q = em.createQuery(query);
List resultList = q.getResultList();
for (Object o : resultList) {
ExperimentSummary experimentSummary = (ExperimentSummary) o;
ExperimentSummaryResource experimentSummaryResource =
(ExperimentSummaryResource) Utils.getResource(ResourceType.EXPERIMENT_SUMMARY,
experimentSummary);
result.add(experimentSummaryResource);
}
em.getTransaction().commit();
em.close();
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RegistryException(e);
} finally {
if (em != null && em.isOpen()) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
em.close();
}
}
return result;
}
}
| fixing query typo
| modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/experiment/catalog/resources/WorkerResource.java | fixing query typo |
|
Java | apache-2.0 | d3d4d2fd83efaf17684e928755f6fb832d686e67 | 0 | milindaperera/product-ei,wso2/product-ei,wso2/product-ei,wso2/product-ei,milindaperera/product-ei,wso2/product-ei,milindaperera/product-ei,milindaperera/product-ei,milindaperera/product-ei,wso2/product-ei | package org.wso2.carbon.esb.mediator.test.aggregate;
import org.apache.commons.lang.ArrayUtils;
import org.awaitility.Awaitility;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.application.mgt.stub.ApplicationAdminExceptionException;
import org.wso2.carbon.automation.test.utils.http.client.HttpsResponse;
import org.wso2.carbon.integration.common.admin.client.ApplicationAdminClient;
import org.wso2.carbon.integration.common.admin.client.CarbonAppUploaderClient;
import org.wso2.esb.integration.common.utils.ESBIntegrationTest;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.rmi.RemoteException;
import java.util.Calendar;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
public class SoapHeaderBlocksTestCase extends ESBIntegrationTest {
private CarbonAppUploaderClient carbonAppUploaderClient;
private ApplicationAdminClient applicationAdminClient;
private final int MAX_TIME = 120;
private final String carFileName = "SoapHeaderTestRegFiles_1.0.0";
private final String carFileNameWithExtension = "SoapHeaderTestRegFiles_1.0.0.car";
private final String serviceName="SoapHeaderBlockTestProxy";
@BeforeClass(alwaysRun = true)
public void setEnvironment() throws Exception {
super.init();
carbonAppUploaderClient = new CarbonAppUploaderClient(context.getContextUrls().getBackEndUrl(), getSessionCookie());
carbonAppUploaderClient.uploadCarbonAppArtifact(carFileNameWithExtension
, new DataHandler( new FileDataSource( new File(getESBResourceLocation()
+ File.separator + "car" + File.separator + carFileNameWithExtension))));
applicationAdminClient = new ApplicationAdminClient(context.getContextUrls().getBackEndUrl(), getSessionCookie());
Awaitility.await().pollInterval(100, TimeUnit.MILLISECONDS).atMost(
MAX_TIME, TimeUnit.SECONDS).until(isCarFileDeployed(carFileName));
loadESBConfigurationFromClasspath("/artifacts/ESB/synapseconfig/requestWithSoapHeaderBlockConfig/synapse.xml");
TimeUnit.SECONDS.sleep(5);
}
@Test(groups = {"wso2.esb"})
public void aggregateMediatorSoapHeaderBlockTestCase() throws Exception {
HttpsResponse response = postWithBasicAuth(getProxyServiceURLHttps(serviceName),
"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" "
+ "xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<s:Header>"
+ "<VsDebugger "
+ "xmlns=\"http://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink\">"
+ "uIDPo0Mttttvvvvvvv</VsDebugger>"
+ "</s:Header>"
+ "<s:Body xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
+ "<sendLetter xmlns=\"http://ws.cts.deg.gov.ae/\">" + "<letter xmlns=\"\">"
+ "<body/>" + "<confidentiality>Public</confidentiality>"
+ "<date>201d6-02-29T15:22:14.88dd7</date>" + "<from>"
+ "<code>ADdddSG</code>" + "<id>AAdd7</id>" + "</from>"
+ "<importance>Normal</importance>"
+ "<outgoingRef>DSssssG/ddddOUT/2016TEST/0uy0099</outgoingRef>"
+ "<priority>Normal</priority>" + "<replyTo>218602</replyTo>"
+ "<signedCopy>" + "<filename>Test.pdf</filename>"
+ "<format>pdf</format>" + "</signedCopy>"
+ "<subject>Test 1</subject>" + "<to>"
+ "<code>DM</code>" + "<id>[email protected]</id>"
+ "</to>" + "</letter>" + "</sendLetter>" + "</s:Body>"
+ "</s:Envelope>", "text/xml;charset=UTF-8", "admin", "admin");
Assert.assertEquals(response.getResponseCode(), 200);
}
@AfterClass(alwaysRun = true)
public void destroy() throws Exception {
super.cleanup();
}
public HttpsResponse postWithBasicAuth(String uri, String requestQuery, String contentType, String userName,
String password) throws IOException {
if (uri.startsWith("https://")) {
URL url = new URL(uri);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
String encode = new String(new org.apache.commons.codec.binary.Base64()
.encode((userName + ":" + password).getBytes(Charset.defaultCharset())), Charset.defaultCharset())
.replaceAll("\n", "");
conn.setRequestProperty("Authorization", "Basic " + encode);
conn.setDoOutput(true); // Triggers POST.
conn.setRequestProperty("Content-Type", contentType);
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("SOAPAction", "http://test/sendLetterRequest");
conn.setRequestProperty("Content-Length",
"" + Integer.toString(requestQuery.getBytes(Charset.defaultCharset()).length));
conn.setUseCaches(false);
conn.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(requestQuery);
conn.setReadTimeout(3000);
conn.connect();
System.out.println(conn.getRequestMethod());
// Get the response
boolean responseRecieved = false;
StringBuilder sb = new StringBuilder();
BufferedReader rd = null;
try {
rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset()));
String line;
while ((line = rd.readLine()) != null) {
responseRecieved = true;
sb.append(line);
}
} catch (FileNotFoundException ignored) {
} finally {
if (rd != null) {
rd.close();
}
if(!responseRecieved){
return new HttpsResponse(sb.toString(), 500);
}
wr.flush();
wr.close();
conn.disconnect();
}
return new HttpsResponse(sb.toString(), conn.getResponseCode());
}
return null;
}
private Callable<Boolean> isCarFileDeployed(final String carFileName) {
return new Callable<Boolean>() {
@Override
public Boolean call() throws ApplicationAdminExceptionException, RemoteException {
log.info("waiting " + MAX_TIME + " millis for car deployment " + carFileName);
Calendar startTime = Calendar.getInstance();
long time = Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis();
String[] applicationList = applicationAdminClient.listAllApplications();
if (applicationList != null) {
if (ArrayUtils.contains(applicationList, carFileName)) {
log.info("car file deployed in " + time + " milliseconds");
return true;
}
}
return false;
}
};
}
}
| integration/mediation-tests/tests-mediator-1/src/test/java/org/wso2/carbon/esb/mediator/test/aggregate/SoapHeaderBlocksTestCase.java | package org.wso2.carbon.esb.mediator.test.aggregate;
import org.apache.commons.lang.ArrayUtils;
import org.awaitility.Awaitility;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.application.mgt.stub.ApplicationAdminExceptionException;
import org.wso2.carbon.automation.test.utils.http.client.HttpsResponse;
import org.wso2.carbon.integration.common.admin.client.ApplicationAdminClient;
import org.wso2.carbon.integration.common.admin.client.CarbonAppUploaderClient;
import org.wso2.esb.integration.common.utils.ESBIntegrationTest;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.rmi.RemoteException;
import java.util.Calendar;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
public class SoapHeaderBlocksTestCase extends ESBIntegrationTest {
private CarbonAppUploaderClient carbonAppUploaderClient;
private ApplicationAdminClient applicationAdminClient;
private final int MAX_TIME = 120;
private final String carFileName = "SoapHeaderTestRegFiles_1.0.0";
private final String carFileNameWithExtension = "SoapHeaderTestRegFiles_1.0.0.car";
private final String serviceName="SoapHeaderBlockTestProxy";
@BeforeClass(alwaysRun = true)
public void setEnvironment() throws Exception {
super.init();
carbonAppUploaderClient = new CarbonAppUploaderClient(context.getContextUrls().getBackEndUrl(), getSessionCookie());
carbonAppUploaderClient.uploadCarbonAppArtifact(carFileNameWithExtension
, new DataHandler( new FileDataSource( new File(getESBResourceLocation()
+ File.separator + "car" + File.separator + carFileNameWithExtension))));
applicationAdminClient = new ApplicationAdminClient(context.getContextUrls().getBackEndUrl(), getSessionCookie());
Awaitility.await().pollInterval(100, TimeUnit.MILLISECONDS).atMost(
MAX_TIME, TimeUnit.SECONDS).until(isCarFileExists(carFileName));
loadESBConfigurationFromClasspath("/artifacts/ESB/synapseconfig/requestWithSoapHeaderBlockConfig/synapse.xml");
TimeUnit.SECONDS.sleep(5);
}
@Test(groups = {"wso2.esb"})
public void aggregateMediatorSoapHeaderBlockTestCase() throws Exception {
HttpsResponse response = postWithBasicAuth(getProxyServiceURLHttps(serviceName),
"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" "
+ "xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<s:Header>"
+ "<VsDebugger "
+ "xmlns=\"http://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink\">"
+ "uIDPo0Mttttvvvvvvv</VsDebugger>"
+ "</s:Header>"
+ "<s:Body xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
+ "<sendLetter xmlns=\"http://ws.cts.deg.gov.ae/\">" + "<letter xmlns=\"\">"
+ "<body/>" + "<confidentiality>Public</confidentiality>"
+ "<date>201d6-02-29T15:22:14.88dd7</date>" + "<from>"
+ "<code>ADdddSG</code>" + "<id>AAdd7</id>" + "</from>"
+ "<importance>Normal</importance>"
+ "<outgoingRef>DSssssG/ddddOUT/2016TEST/0uy0099</outgoingRef>"
+ "<priority>Normal</priority>" + "<replyTo>218602</replyTo>"
+ "<signedCopy>" + "<filename>Test.pdf</filename>"
+ "<format>pdf</format>" + "</signedCopy>"
+ "<subject>Test 1</subject>" + "<to>"
+ "<code>DM</code>" + "<id>[email protected]</id>"
+ "</to>" + "</letter>" + "</sendLetter>" + "</s:Body>"
+ "</s:Envelope>", "text/xml;charset=UTF-8", "admin", "admin");
Assert.assertEquals(response.getResponseCode(), 200);
}
@AfterClass(alwaysRun = true)
public void destroy() throws Exception {
super.cleanup();
}
public HttpsResponse postWithBasicAuth(String uri, String requestQuery, String contentType, String userName,
String password) throws IOException {
if (uri.startsWith("https://")) {
URL url = new URL(uri);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
String encode = new String(new org.apache.commons.codec.binary.Base64()
.encode((userName + ":" + password).getBytes(Charset.defaultCharset())), Charset.defaultCharset())
.replaceAll("\n", "");
conn.setRequestProperty("Authorization", "Basic " + encode);
conn.setDoOutput(true); // Triggers POST.
conn.setRequestProperty("Content-Type", contentType);
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("SOAPAction", "http://test/sendLetterRequest");
conn.setRequestProperty("Content-Length",
"" + Integer.toString(requestQuery.getBytes(Charset.defaultCharset()).length));
conn.setUseCaches(false);
conn.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(requestQuery);
conn.setReadTimeout(3000);
conn.connect();
System.out.println(conn.getRequestMethod());
// Get the response
boolean responseRecieved = false;
StringBuilder sb = new StringBuilder();
BufferedReader rd = null;
try {
rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset()));
String line;
while ((line = rd.readLine()) != null) {
responseRecieved = true;
sb.append(line);
}
} catch (FileNotFoundException ignored) {
} finally {
if (rd != null) {
rd.close();
}
if(!responseRecieved){
return new HttpsResponse(sb.toString(), 500);
}
wr.flush();
wr.close();
conn.disconnect();
}
return new HttpsResponse(sb.toString(), conn.getResponseCode());
}
return null;
}
private Callable<Boolean> isCarFileExists(final String carFileName) {
return new Callable<Boolean>() {
@Override
public Boolean call() throws ApplicationAdminExceptionException, RemoteException {
log.info("waiting " + MAX_TIME + " millis for car deployment " + carFileName);
Calendar startTime = Calendar.getInstance();
long time = Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis();
String[] applicationList = applicationAdminClient.listAllApplications();
if (applicationList != null) {
if (ArrayUtils.contains(applicationList, carFileName)) {
log.info("car file deployed in " + time + " milliseconds");
return true;
}
}
return false;
}
};
}
}
| Refactor integration test cases
| integration/mediation-tests/tests-mediator-1/src/test/java/org/wso2/carbon/esb/mediator/test/aggregate/SoapHeaderBlocksTestCase.java | Refactor integration test cases |
|
Java | apache-2.0 | b9f7ea275a2e14cbb19c000c3bde49f02bf526fe | 0 | dinithis/stratos,Thanu/stratos,hsbhathiya/stratos,Thanu/stratos,gayangunarathne/stratos,hsbhathiya/stratos,hsbhathiya/stratos,dinithis/stratos,hsbhathiya/stratos,apache/stratos,pkdevbox/stratos,lasinducharith/stratos,lasinducharith/stratos,ravihansa3000/stratos,agentmilindu/stratos,anuruddhal/stratos,dinithis/stratos,Thanu/stratos,hsbhathiya/stratos,anuruddhal/stratos,agentmilindu/stratos,apache/stratos,anuruddhal/stratos,gayangunarathne/stratos,ravihansa3000/stratos,agentmilindu/stratos,apache/stratos,anuruddhal/stratos,pubudu538/stratos,ravihansa3000/stratos,dinithis/stratos,gayangunarathne/stratos,lasinducharith/stratos,Thanu/stratos,Thanu/stratos,asankasanjaya/stratos,anuruddhal/stratos,pubudu538/stratos,agentmilindu/stratos,anuruddhal/stratos,pkdevbox/stratos,asankasanjaya/stratos,pubudu538/stratos,apache/stratos,asankasanjaya/stratos,lasinducharith/stratos,gayangunarathne/stratos,pkdevbox/stratos,asankasanjaya/stratos,gayangunarathne/stratos,Thanu/stratos,apache/stratos,ravihansa3000/stratos,agentmilindu/stratos,pubudu538/stratos,ravihansa3000/stratos,lasinducharith/stratos,pkdevbox/stratos,lasinducharith/stratos,hsbhathiya/stratos,anuruddhal/stratos,gayangunarathne/stratos,dinithis/stratos,pkdevbox/stratos,pkdevbox/stratos,asankasanjaya/stratos,pubudu538/stratos,apache/stratos,pubudu538/stratos,hsbhathiya/stratos,pubudu538/stratos,asankasanjaya/stratos,dinithis/stratos,apache/stratos,ravihansa3000/stratos,agentmilindu/stratos,asankasanjaya/stratos,ravihansa3000/stratos,Thanu/stratos,lasinducharith/stratos,agentmilindu/stratos,dinithis/stratos,pkdevbox/stratos,gayangunarathne/stratos | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.stratos.messaging.message.processor.topology;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.stratos.messaging.domain.topology.*;
import org.apache.stratos.messaging.event.topology.ApplicationUndeployedEvent;
import org.apache.stratos.messaging.message.processor.MessageProcessor;
import org.apache.stratos.messaging.message.processor.topology.updater.TopologyUpdater;
import org.apache.stratos.messaging.util.Util;
import java.util.Set;
public class ApplicationUndeployedMessageProcessor extends MessageProcessor {
private static final Log log = LogFactory.getLog(ApplicationUndeployedMessageProcessor.class);
private MessageProcessor nextProcessor;
@Override
public void setNext(MessageProcessor nextProcessor) {
this.nextProcessor = nextProcessor;
}
@Override
public boolean process(String type, String message, Object object) {
Topology topology = (Topology) object;
if (ApplicationUndeployedEvent.class.getName().equals(type)) {
if (!topology.isInitialized()) {
return false;
}
ApplicationUndeployedEvent event = (ApplicationUndeployedEvent)
Util.jsonToObject(message, ApplicationUndeployedEvent.class);
if (event == null) {
log.error("Unable to convert the JSON message to ApplicationUndeployedEvent");
return false;
}
// get write lock for the application and relevant Clusters
TopologyUpdater.acquireWriteLockForApplication(event.getApplicationId());
Set<ClusterDataHolder> clusterDataHolders = event.getClusterData();
if (clusterDataHolders != null) {
for (ClusterDataHolder clusterData : clusterDataHolders) {
TopologyUpdater.acquireWriteLockForCluster(clusterData.getServiceType(),
clusterData.getClusterId());
}
}
try {
return doProcess(event, topology);
} finally {
// remove locks
if (clusterDataHolders != null) {
for (ClusterDataHolder clusterData : clusterDataHolders) {
TopologyUpdater.releaseWriteLockForCluster(clusterData.getServiceType(),
clusterData.getClusterId());
}
}
TopologyUpdater.releaseWriteLockForApplication(event.getApplicationId());
}
} else {
if (nextProcessor != null) {
// ask the next processor to take care of the message.
return nextProcessor.process(type, message, topology);
} else {
throw new RuntimeException(String.format
("Failed to process message using available message processors: [type] %s [body] %s", type, message));
}
}
}
private boolean doProcess (ApplicationUndeployedEvent event, Topology topology) {
// update the application status to Terminating
Application application = topology.getApplication(event.getApplicationId());
// check and update application status to 'Terminating'
if (!application.isStateTransitionValid(ApplicationStatus.Terminating)) {
log.error("Invalid state transfer from " + application.getStatus() + " to " + ApplicationStatus.Terminating);
}
// for now anyway update the status forcefully
application.setStatus(ApplicationStatus.Terminating);
log.info("Application " + event.getApplicationId() + "'s status updated to " + ApplicationStatus.Terminating);
// update all the Clusters' statuses to 'Terminating'
Set<ClusterDataHolder> clusterData = application.getClusterDataRecursively();
// update the Cluster statuses to Terminating
for (ClusterDataHolder clusterDataHolder : clusterData) {
Service service = topology.getService(clusterDataHolder.getServiceType());
if (service != null) {
Cluster aCluster = service.getCluster(clusterDataHolder.getClusterId());
if (aCluster != null) {
// validate state transition
if (!aCluster.isStateTransitionValid(ClusterStatus.Terminating)) {
log.error("Invalid state transfer from " + aCluster.getStatus() + " to "
+ ClusterStatus.Terminating);
}
// for now anyway update the status forcefully
aCluster.setStatus(ClusterStatus.Terminating);
log.info("Cluster " + clusterDataHolder.getClusterId() + "'s status updated to "
+ ClusterStatus.Terminating + " successfully");
} else {
log.warn("Unable to find Cluster with cluster id " + clusterDataHolder.getClusterId() +
" in Topology");
}
} else {
log.warn("Unable to remove cluster with cluster id: " + clusterDataHolder.getClusterId() + " from Topology, " +
" associated Service [ " + clusterDataHolder.getServiceType() + " ] npt found");
}
}
notifyEventListeners(event);
return true;
}
}
| components/org.apache.stratos.messaging/src/main/java/org/apache/stratos/messaging/message/processor/topology/ApplicationUndeployedMessageProcessor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.stratos.messaging.message.processor.topology;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.stratos.messaging.domain.topology.*;
import org.apache.stratos.messaging.event.topology.ApplicationUndeployedEvent;
import org.apache.stratos.messaging.message.processor.MessageProcessor;
import org.apache.stratos.messaging.message.processor.topology.updater.TopologyUpdater;
import org.apache.stratos.messaging.util.Util;
import java.util.Set;
public class ApplicationUndeployedMessageProcessor extends MessageProcessor {
private static final Log log = LogFactory.getLog(ApplicationCreatedMessageProcessor.class);
private MessageProcessor nextProcessor;
@Override
public void setNext(MessageProcessor nextProcessor) {
this.nextProcessor = nextProcessor;
}
@Override
public boolean process(String type, String message, Object object) {
Topology topology = (Topology) object;
if (ApplicationUndeployedEvent.class.getName().equals(type)) {
if (!topology.isInitialized()) {
return false;
}
ApplicationUndeployedEvent event = (ApplicationUndeployedEvent)
Util.jsonToObject(message, ApplicationUndeployedEvent.class);
if (event == null) {
log.error("Unable to convert the JSON message to ApplicationUndeployedEvent");
return false;
}
// get write lock for the application and relevant Clusters
TopologyUpdater.acquireWriteLockForApplication(event.getApplicationId());
Set<ClusterDataHolder> clusterDataHolders = event.getClusterData();
if (clusterDataHolders != null) {
for (ClusterDataHolder clusterData : clusterDataHolders) {
TopologyUpdater.acquireWriteLockForCluster(clusterData.getServiceType(),
clusterData.getClusterId());
}
}
try {
return doProcess(event, topology);
} finally {
// remove locks
if (clusterDataHolders != null) {
for (ClusterDataHolder clusterData : clusterDataHolders) {
TopologyUpdater.releaseWriteLockForCluster(clusterData.getServiceType(),
clusterData.getClusterId());
}
}
TopologyUpdater.releaseWriteLockForApplication(event.getApplicationId());
}
} else {
if (nextProcessor != null) {
// ask the next processor to take care of the message.
return nextProcessor.process(type, message, topology);
} else {
throw new RuntimeException(String.format
("Failed to process message using available message processors: [type] %s [body] %s", type, message));
}
}
}
private boolean doProcess (ApplicationUndeployedEvent event, Topology topology) {
// update the application status to Terminating
Application application = topology.getApplication(event.getApplicationId());
// check and update application status to 'Terminating'
if (!application.isStateTransitionValid(ApplicationStatus.Terminating)) {
log.error("Invalid state transfer from " + application.getStatus() + " to " + ApplicationStatus.Terminating);
}
// for now anyway update the status forcefully
application.setStatus(ApplicationStatus.Terminating);
log.info("Application " + event.getApplicationId() + "'s status updated to " + ApplicationStatus.Terminating);
// update all the Clusters' statuses to 'Terminating'
Set<ClusterDataHolder> clusterData = application.getClusterDataRecursively();
// update the Cluster statuses to Terminating
for (ClusterDataHolder clusterDataHolder : clusterData) {
Service service = topology.getService(clusterDataHolder.getServiceType());
if (service != null) {
Cluster aCluster = service.getCluster(clusterDataHolder.getClusterId());
if (aCluster != null) {
// validate state transition
if (aCluster.isStateTransitionValid(ClusterStatus.Terminating)) {
log.error("Invalid state transfer from " + aCluster.getStatus() + " to "
+ ClusterStatus.Terminating + " successfully");
}
// for now anyway update the status forcefully
aCluster.setStatus(ClusterStatus.Terminating);
log.info("Cluster " + clusterDataHolder.getClusterId() + "'s status updated to "
+ ClusterStatus.Terminating + " successfully");
} else {
log.warn("Unable to find Cluster with cluster id " + clusterDataHolder.getClusterId() +
" in Topology");
}
} else {
log.warn("Unable to remove cluster with cluster id: " + clusterDataHolder.getClusterId() + " from Topology, " +
" associated Service [ " + clusterDataHolder.getServiceType() + " ] npt found");
}
}
return true;
}
}
| correcting the log and notifying listeners
| components/org.apache.stratos.messaging/src/main/java/org/apache/stratos/messaging/message/processor/topology/ApplicationUndeployedMessageProcessor.java | correcting the log and notifying listeners |
|
Java | apache-2.0 | 564a1c632e1ef4634dccba515b95195f1277a84c | 0 | subutai-io/base,subutai-io/base,subutai-io/Subutai,subutai-io/Subutai,subutai-io/Subutai,subutai-io/base,subutai-io/Subutai,subutai-io/base,subutai-io/Subutai,subutai-io/Subutai | package org.safehaus.subutai.core.environment.ui.manage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.safehaus.subutai.common.protocol.CloneContainersMessage;
import org.safehaus.subutai.common.protocol.EnvironmentBuildTask;
import org.safehaus.subutai.common.protocol.NodeGroup;
import org.safehaus.subutai.core.environment.api.helper.EnvironmentBuildProcess;
import org.safehaus.subutai.core.environment.ui.EnvironmentManagerPortalModule;
import org.safehaus.subutai.core.environment.ui.window.DetailsWindow;
import org.safehaus.subutai.core.peer.api.Peer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.ui.Button;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.Notification;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.Table;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.themes.Runo;
/**
* Created by bahadyr on 9/10/14.
*/
public class EnvironmentBuildWizard extends DetailsWindow
{
private static final Logger LOG = LoggerFactory.getLogger( EnvironmentBuildWizard.class.getName() );
private int step = 1;
private EnvironmentBuildTask environmentBuildTask;
private Table peersTable;
private Table containerToPeerTable;
private EnvironmentManagerPortalModule managerUI;
public EnvironmentBuildWizard( final String caption, EnvironmentManagerPortalModule managerUI,
EnvironmentBuildTask environmentBuildTask )
{
super( caption );
this.managerUI = managerUI;
this.environmentBuildTask = environmentBuildTask;
next();
}
public void next()
{
step++;
putForm();
}
private void putForm()
{
switch ( step )
{
case 1:
{
setContent( genPeersTable() );
break;
}
case 2:
{
setContent( genContainerToPeersTable() );
break;
}
case 3:
{
managerUI.getEnvironmentManager().buildEnvironment( environmentBuildTask );
close();
break;
}
default:
{
setContent( genPeersTable() );
break;
}
}
}
public EnvironmentManagerPortalModule getManagerUI()
{
return managerUI;
}
public void setManagerUI( final EnvironmentManagerPortalModule managerUI )
{
this.managerUI = managerUI;
}
public EnvironmentBuildTask getEnvironmentBuildTask()
{
return environmentBuildTask;
}
public void setEnvironmentBuildTask( final EnvironmentBuildTask environmentBuildTask )
{
this.environmentBuildTask = environmentBuildTask;
}
public void back()
{
step--;
}
private VerticalLayout genPeersTable()
{
VerticalLayout vl = new VerticalLayout();
peersTable = new Table();
peersTable.addContainerProperty( "Name", String.class, null );
peersTable.addContainerProperty( "Select", CheckBox.class, null );
peersTable.setPageLength( 10 );
peersTable.setSelectable( false );
peersTable.setEnabled( true );
peersTable.setImmediate( true );
peersTable.setSizeFull();
List<Peer> peers = managerUI.getPeerManager().peers();
if ( !peers.isEmpty() )
{
for ( Peer peer : peers )
{
CheckBox ch = new CheckBox();
Object id = peersTable.addItem( new Object[] {
peer.getName(), ch
}, peer );
}
}
Button nextButton = new Button( "Next" );
nextButton.addClickListener( new Button.ClickListener()
{
@Override
public void buttonClick( final Button.ClickEvent clickEvent )
{
if ( !selectedPeers().isEmpty() )
{
next();
}
else
{
Notification.show( "Please select peers", Notification.Type.HUMANIZED_MESSAGE );
}
}
} );
vl.addComponent( peersTable );
vl.addComponent( nextButton );
return vl;
}
private TabSheet genContainerToPeersTable()
{
TabSheet sheet = new TabSheet();
sheet.setStyleName( Runo.TABSHEET_SMALL );
sheet.setSizeFull();
VerticalLayout vl = new VerticalLayout();
containerToPeerTable = new Table();
containerToPeerTable.addContainerProperty( "Container", String.class, null );
containerToPeerTable.addContainerProperty( "Put", ComboBox.class, null );
containerToPeerTable.setPageLength( 10 );
containerToPeerTable.setSelectable( false );
containerToPeerTable.setEnabled( true );
containerToPeerTable.setImmediate( true );
containerToPeerTable.setSizeFull();
for ( NodeGroup ng : environmentBuildTask.getEnvironmentBlueprint().getNodeGroups() )
{
for ( int i = 0; i < ng.getNumberOfNodes(); i++ )
{
ComboBox comboBox = new ComboBox();
BeanItemContainer<Peer> bic = new BeanItemContainer<>( Peer.class );
bic.addAll( selectedPeers() );
comboBox.setContainerDataSource( bic );
comboBox.setNullSelectionAllowed( false );
comboBox.setTextInputAllowed( false );
comboBox.setItemCaptionPropertyId( "name" );
containerToPeerTable.addItem( new Object[] {
ng.getTemplateName(), comboBox
}, ng.getTemplateName() );
}
}
Button nextButton = new Button( "Build" );
nextButton.addClickListener( new Button.ClickListener()
{
@Override
public void buttonClick( final Button.ClickEvent clickEvent )
{
Map<String, Peer> topology = topologySelection();
if ( !topology.isEmpty() || containerToPeerTable.getItemIds().size() != topology.size() )
{
managerUI.getEnvironmentManager().saveBuildProcess(
createBackgroundEnvironmentBuildProcess( environmentBuildTask, topology ) );
}
else
{
Notification.show( "Topology is not properly set" );
}
close();
}
} );
vl.addComponent( containerToPeerTable );
vl.addComponent( nextButton );
sheet.addTab( vl, "Node to Peer" );
sheet.addTab( new Button( "test" ), "Blueprint to Peer group" );
sheet.addTab( new Button( "test" ), "Node group to Peer group" );
sheet.addTab( new Button( "test" ), "Node group to Peer" );
return sheet;
}
private List<Peer> selectedPeers()
{
List<Peer> peers = new ArrayList<>();
if ( !peers.isEmpty() )
{
for ( Object itemId : peersTable.getItemIds() )
{
CheckBox selection = ( CheckBox ) peersTable.getItem( itemId ).getItemProperty( "Select" ).getValue();
if ( selection.getValue() )
{
peers.add( ( Peer ) itemId );
}
}
}
return peers;
}
public EnvironmentBuildProcess createBackgroundEnvironmentBuildProcess( EnvironmentBuildTask ebt,
Map<String, Peer> topology )
{
EnvironmentBuildProcess process = new EnvironmentBuildProcess( ebt.getEnvironmentBlueprint().getName() );
for ( NodeGroup ng : ebt.getEnvironmentBlueprint().getNodeGroups() )
{
Peer peer = topology.get( ng.getTemplateName() );
String key = peer.getId().toString() + "-" + ng.getTemplateName();
if ( !process.getMessageMap().containsKey( key ) )
{
CloneContainersMessage ccm = new CloneContainersMessage( process.getUuid(), peer.getId() );
ccm.setTemplate( ng.getTemplateName() );
ccm.setPeerId( peer.getId() );
ccm.setEnvId( ebt.getUuid() );
ccm.setNumberOfNodes( 1 );
ccm.setStrategy( ng.getPlacementStrategy().toString() );
process.putCloneContainerMessage( key, ccm );
}
else
{
process.getMessageMap().get( key ).incrementNumberOfNodes();
}
}
return process;
}
private Map<String, Peer> topologySelection()
{
Map<String, Peer> topology = new HashMap<>();
for ( Object itemId : containerToPeerTable.getItemIds() )
{
String templateName =
( String ) containerToPeerTable.getItem( itemId ).getItemProperty( "Container" ).getValue();
ComboBox selection =
( ComboBox ) containerToPeerTable.getItem( itemId ).getItemProperty( "Put" ).getValue();
Peer peer = ( Peer ) selection.getValue();
topology.put( templateName, peer );
}
return topology;
}
}
| management/server/core/environment-manager/environment-manager-ui/src/main/java/org/safehaus/subutai/core/environment/ui/manage/EnvironmentBuildWizard.java | package org.safehaus.subutai.core.environment.ui.manage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.safehaus.subutai.common.protocol.CloneContainersMessage;
import org.safehaus.subutai.common.protocol.EnvironmentBuildTask;
import org.safehaus.subutai.common.protocol.NodeGroup;
import org.safehaus.subutai.core.environment.api.helper.EnvironmentBuildProcess;
import org.safehaus.subutai.core.environment.ui.EnvironmentManagerPortalModule;
import org.safehaus.subutai.core.environment.ui.window.DetailsWindow;
import org.safehaus.subutai.core.peer.api.Peer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.ui.Button;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.Notification;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.Table;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.themes.Runo;
/**
* Created by bahadyr on 9/10/14.
*/
public class EnvironmentBuildWizard extends DetailsWindow
{
private static final Logger LOG = LoggerFactory.getLogger( EnvironmentBuildWizard.class.getName() );
private int step = 1;
private EnvironmentBuildTask environmentBuildTask;
private Table peersTable;
private Table containerToPeerTable;
private EnvironmentManagerPortalModule managerUI;
public EnvironmentBuildWizard( final String caption, EnvironmentManagerPortalModule managerUI,
EnvironmentBuildTask environmentBuildTask )
{
super( caption );
this.managerUI = managerUI;
this.environmentBuildTask = environmentBuildTask;
}
public void next()
{
step++;
putForm();
}
private void putForm()
{
switch ( step )
{
case 1:
{
setContent( genPeersTable() );
break;
}
case 2:
{
setContent( genContainerToPeersTable() );
break;
}
case 3:
{
managerUI.getEnvironmentManager().buildEnvironment( environmentBuildTask );
close();
break;
}
default:
{
setContent( genPeersTable() );
break;
}
}
}
public EnvironmentManagerPortalModule getManagerUI()
{
return managerUI;
}
public void setManagerUI( final EnvironmentManagerPortalModule managerUI )
{
this.managerUI = managerUI;
}
public EnvironmentBuildTask getEnvironmentBuildTask()
{
return environmentBuildTask;
}
public void setEnvironmentBuildTask( final EnvironmentBuildTask environmentBuildTask )
{
this.environmentBuildTask = environmentBuildTask;
}
public void back()
{
step--;
}
private VerticalLayout genPeersTable()
{
VerticalLayout vl = new VerticalLayout();
peersTable = new Table();
peersTable.addContainerProperty( "Name", String.class, null );
peersTable.addContainerProperty( "Select", CheckBox.class, null );
peersTable.setPageLength( 10 );
peersTable.setSelectable( false );
peersTable.setEnabled( true );
peersTable.setImmediate( true );
peersTable.setSizeFull();
List<Peer> peers = managerUI.getPeerManager().peers();
if ( !peers.isEmpty() )
{
for ( Peer peer : peers )
{
CheckBox ch = new CheckBox();
Object id = peersTable.addItem( new Object[] {
peer.getName(), ch
}, peer );
}
}
Button nextButton = new Button( "Next" );
nextButton.addClickListener( new Button.ClickListener()
{
@Override
public void buttonClick( final Button.ClickEvent clickEvent )
{
if ( !selectedPeers().isEmpty() )
{
next();
}
else
{
Notification.show( "Please select peers", Notification.Type.HUMANIZED_MESSAGE );
}
}
} );
vl.addComponent( peersTable );
vl.addComponent( nextButton );
return vl;
}
private TabSheet genContainerToPeersTable()
{
TabSheet sheet = new TabSheet();
sheet.setStyleName( Runo.TABSHEET_SMALL );
sheet.setSizeFull();
VerticalLayout vl = new VerticalLayout();
containerToPeerTable = new Table();
containerToPeerTable.addContainerProperty( "Container", String.class, null );
containerToPeerTable.addContainerProperty( "Put", ComboBox.class, null );
containerToPeerTable.setPageLength( 10 );
containerToPeerTable.setSelectable( false );
containerToPeerTable.setEnabled( true );
containerToPeerTable.setImmediate( true );
containerToPeerTable.setSizeFull();
for ( NodeGroup ng : environmentBuildTask.getEnvironmentBlueprint().getNodeGroups() )
{
for ( int i = 0; i < ng.getNumberOfNodes(); i++ )
{
ComboBox comboBox = new ComboBox();
BeanItemContainer<Peer> bic = new BeanItemContainer<>( Peer.class );
bic.addAll( selectedPeers() );
comboBox.setContainerDataSource( bic );
comboBox.setNullSelectionAllowed( false );
comboBox.setTextInputAllowed( false );
comboBox.setItemCaptionPropertyId( "name" );
containerToPeerTable.addItem( new Object[] {
ng.getTemplateName(), comboBox
}, ng.getTemplateName() );
}
}
Button nextButton = new Button( "Build" );
nextButton.addClickListener( new Button.ClickListener()
{
@Override
public void buttonClick( final Button.ClickEvent clickEvent )
{
Map<String, Peer> topology = topologySelection();
if ( !topology.isEmpty() || containerToPeerTable.getItemIds().size() != topology.size() )
{
managerUI.getEnvironmentManager().saveBuildProcess(
createBackgroundEnvironmentBuildProcess( environmentBuildTask, topology ) );
}
else
{
Notification.show( "Topology is not properly set" );
}
close();
}
} );
vl.addComponent( containerToPeerTable );
vl.addComponent( nextButton );
sheet.addTab( vl, "Node to Peer" );
sheet.addTab( new Button( "test" ), "Blueprint to Peer group" );
sheet.addTab( new Button( "test" ), "Node group to Peer group" );
sheet.addTab( new Button( "test" ), "Node group to Peer" );
return sheet;
}
private List<Peer> selectedPeers()
{
List<Peer> peers = new ArrayList<>();
for ( Object itemId : peersTable.getItemIds() )
{
CheckBox selection = ( CheckBox ) peersTable.getItem( itemId ).getItemProperty( "Select" ).getValue();
if ( selection.getValue() )
{
peers.add( ( Peer ) itemId );
}
}
return peers;
}
public EnvironmentBuildProcess createBackgroundEnvironmentBuildProcess( EnvironmentBuildTask ebt,
Map<String, Peer> topology )
{
EnvironmentBuildProcess process = new EnvironmentBuildProcess( ebt.getEnvironmentBlueprint().getName() );
for ( NodeGroup ng : ebt.getEnvironmentBlueprint().getNodeGroups() )
{
Peer peer = topology.get( ng.getTemplateName() );
String key = peer.getId().toString() + "-" + ng.getTemplateName();
if ( !process.getMessageMap().containsKey( key ) )
{
CloneContainersMessage ccm = new CloneContainersMessage( process.getUuid(), peer.getId() );
ccm.setTemplate( ng.getTemplateName() );
ccm.setPeerId( peer.getId() );
ccm.setEnvId( ebt.getUuid() );
ccm.setNumberOfNodes( 1 );
ccm.setStrategy( ng.getPlacementStrategy().toString() );
process.putCloneContainerMessage( key, ccm );
}
else
{
process.getMessageMap().get( key ).incrementNumberOfNodes();
}
}
return process;
}
private Map<String, Peer> topologySelection()
{
Map<String, Peer> topology = new HashMap<>();
for ( Object itemId : containerToPeerTable.getItemIds() )
{
String templateName =
( String ) containerToPeerTable.getItem( itemId ).getItemProperty( "Container" ).getValue();
ComboBox selection =
( ComboBox ) containerToPeerTable.getItem( itemId ).getItemProperty( "Put" ).getValue();
Peer peer = ( Peer ) selection.getValue();
topology.put( templateName, peer );
}
return topology;
}
}
| Environment manager code refactor.
| management/server/core/environment-manager/environment-manager-ui/src/main/java/org/safehaus/subutai/core/environment/ui/manage/EnvironmentBuildWizard.java | Environment manager code refactor. |
|
Java | apache-2.0 | bcccd125b9afc5128fe684212b08c62e2ee49edb | 0 | profjrr/zaproxy,kingthorin/zaproxy,meitar/zaproxy,urgupluoglu/zaproxy,zapbot/zaproxy,NVolcz/zaproxy,JordanGS/zaproxy,psiinon/zaproxy,pdehaan/zaproxy,mustafa421/zaproxy,0xkasun/zaproxy,cassiodeveloper/zaproxy,Ali-Razmjoo/zaproxy,gsavastano/zaproxy,surikato/zaproxy,thc202/zaproxy,Harinus/zaproxy,0xkasun/zaproxy,mabdi/zaproxy,tjackiw/zaproxy,zapbot/zaproxy,jorik041/zaproxy,zapbot/zaproxy,mario-areias/zaproxy,tjackiw/zaproxy,Harinus/zaproxy,MD14/zaproxy,efdutra/zaproxy,UjuE/zaproxy,0xkasun/zaproxy,ozzyjohnson/zaproxy,MD14/zaproxy,robocoder/zaproxy,lightsey/zaproxy,veggiespam/zaproxy,kingthorin/zaproxy,NVolcz/zaproxy,MD14/zaproxy,Ali-Razmjoo/zaproxy,DJMIN/zaproxy,jorik041/zaproxy,jorik041/zaproxy,zapbot/zaproxy,lightsey/zaproxy,zapbot/zaproxy,kingthorin/zaproxy,psiinon/zaproxy,thamizarasu/zaproxy,meitar/zaproxy,Harinus/zaproxy,rajiv65/zaproxy,mustafa421/zaproxy,mustafa421/zaproxy,gmaran23/zaproxy,UjuE/zaproxy,veggiespam/zaproxy,psiinon/zaproxy,Ali-Razmjoo/zaproxy,robocoder/zaproxy,cassiodeveloper/zaproxy,UjuE/zaproxy,mabdi/zaproxy,rajiv65/zaproxy,pdehaan/zaproxy,gmaran23/zaproxy,efdutra/zaproxy,zaproxy/zaproxy,profjrr/zaproxy,DJMIN/zaproxy,JordanGS/zaproxy,gmaran23/zaproxy,rajiv65/zaproxy,kingthorin/zaproxy,ozzyjohnson/zaproxy,gsavastano/zaproxy,DJMIN/zaproxy,DJMIN/zaproxy,DJMIN/zaproxy,thamizarasu/zaproxy,rajiv65/zaproxy,thc202/zaproxy,pdehaan/zaproxy,NVolcz/zaproxy,Ali-Razmjoo/zaproxy,psiinon/zaproxy,meitar/zaproxy,lightsey/zaproxy,zaproxy/zaproxy,thc202/zaproxy,gmaran23/zaproxy,meitar/zaproxy,urgupluoglu/zaproxy,pdehaan/zaproxy,surikato/zaproxy,zaproxy/zaproxy,thc202/zaproxy,Ali-Razmjoo/zaproxy,mabdi/zaproxy,cassiodeveloper/zaproxy,lightsey/zaproxy,surikato/zaproxy,profjrr/zaproxy,urgupluoglu/zaproxy,thc202/zaproxy,robocoder/zaproxy,meitar/zaproxy,Ye-Yong-Chi/zaproxy,Ali-Razmjoo/zaproxy,tjackiw/zaproxy,Harinus/zaproxy,gsavastano/zaproxy,MD14/zaproxy,profjrr/zaproxy,Ye-Yong-Chi/zaproxy,veggiespam/zaproxy,Harinus/zaproxy,mabdi/zaproxy,efdutra/zaproxy,mabdi/zaproxy,mario-areias/zaproxy,efdutra/zaproxy,urgupluoglu/zaproxy,mustafa421/zaproxy,thamizarasu/zaproxy,gmaran23/zaproxy,efdutra/zaproxy,urgupluoglu/zaproxy,NVolcz/zaproxy,NVolcz/zaproxy,meitar/zaproxy,JordanGS/zaproxy,NVolcz/zaproxy,Ye-Yong-Chi/zaproxy,0xkasun/zaproxy,Harinus/zaproxy,mario-areias/zaproxy,Ye-Yong-Chi/zaproxy,Ye-Yong-Chi/zaproxy,ozzyjohnson/zaproxy,DJMIN/zaproxy,zaproxy/zaproxy,zaproxy/zaproxy,ozzyjohnson/zaproxy,veggiespam/zaproxy,kingthorin/zaproxy,mabdi/zaproxy,lightsey/zaproxy,psiinon/zaproxy,jorik041/zaproxy,zapbot/zaproxy,thamizarasu/zaproxy,NVolcz/zaproxy,DJMIN/zaproxy,rajiv65/zaproxy,rajiv65/zaproxy,rajiv65/zaproxy,0xkasun/zaproxy,MD14/zaproxy,JordanGS/zaproxy,gsavastano/zaproxy,Harinus/zaproxy,mabdi/zaproxy,surikato/zaproxy,Ye-Yong-Chi/zaproxy,zaproxy/zaproxy,robocoder/zaproxy,urgupluoglu/zaproxy,lightsey/zaproxy,efdutra/zaproxy,gmaran23/zaproxy,thamizarasu/zaproxy,gmaran23/zaproxy,meitar/zaproxy,pdehaan/zaproxy,profjrr/zaproxy,gsavastano/zaproxy,mario-areias/zaproxy,tjackiw/zaproxy,profjrr/zaproxy,UjuE/zaproxy,thamizarasu/zaproxy,MD14/zaproxy,JordanGS/zaproxy,tjackiw/zaproxy,thamizarasu/zaproxy,mario-areias/zaproxy,veggiespam/zaproxy,mario-areias/zaproxy,pdehaan/zaproxy,psiinon/zaproxy,thc202/zaproxy,thc202/zaproxy,Ye-Yong-Chi/zaproxy,jorik041/zaproxy,jorik041/zaproxy,UjuE/zaproxy,tjackiw/zaproxy,mustafa421/zaproxy,cassiodeveloper/zaproxy,veggiespam/zaproxy,0xkasun/zaproxy,surikato/zaproxy,cassiodeveloper/zaproxy,gsavastano/zaproxy,robocoder/zaproxy,urgupluoglu/zaproxy,JordanGS/zaproxy,psiinon/zaproxy,MD14/zaproxy,cassiodeveloper/zaproxy,pdehaan/zaproxy,zapbot/zaproxy,mustafa421/zaproxy,kingthorin/zaproxy,ozzyjohnson/zaproxy,ozzyjohnson/zaproxy,Ali-Razmjoo/zaproxy,tjackiw/zaproxy,surikato/zaproxy,JordanGS/zaproxy,jorik041/zaproxy,profjrr/zaproxy,mario-areias/zaproxy,cassiodeveloper/zaproxy,meitar/zaproxy,surikato/zaproxy,mustafa421/zaproxy,kingthorin/zaproxy,lightsey/zaproxy,ozzyjohnson/zaproxy,robocoder/zaproxy,efdutra/zaproxy,gsavastano/zaproxy,0xkasun/zaproxy,UjuE/zaproxy,UjuE/zaproxy,veggiespam/zaproxy,robocoder/zaproxy,zaproxy/zaproxy | /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2012 ZAP development team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zaproxy.zap.control;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.configuration.SubnodeConfiguration;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.SystemUtils;
import org.apache.log4j.Logger;
import org.jgrapht.DirectedGraph;
import org.jgrapht.alg.CycleDetector;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.traverse.TopologicalOrderIterator;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.extension.Extension;
import org.zaproxy.zap.Version;
import org.zaproxy.zap.control.BaseZapAddOnXmlData.AddOnDep;
import org.zaproxy.zap.control.BaseZapAddOnXmlData.Dependencies;
public class AddOn {
public enum Status {unknown, example, alpha, beta, weekly, release}
private static ZapRelease v2_4 = new ZapRelease("2.4.0");
/**
* The installation status of the add-on.
*
* @since 2.4.0
*/
public enum InstallationStatus {
/**
* The add-on is available for installation, for example, an add-on in the marketplace (even if it requires previous
* actions, in this case, download the file).
*/
AVAILABLE,
/**
* The add-on was not (yet) installed. For example, the add-on is available in the 'plugin' directory but it's missing a
* dependency or requires a greater Java version. It's also in this status while a dependency is being updated.
*/
NOT_INSTALLED,
/**
* The add-on is installed.
*/
INSTALLED,
/**
* The add-on is being downloaded.
*/
DOWNLOADING,
/**
* The uninstallation of the add-on failed. For example, when the add-on is not dynamically installable or when an
* {@code Exception} is thrown during the uninstallation.
*/
UNINSTALLATION_FAILED,
/**
* The soft uninstallation of the add-on failed. It's in this status when the uninstallation failed for an update of a
* dependency.
*/
SOFT_UNINSTALLATION_FAILED
}
private String id;
private String name;
private String description = "";
private String author = "";
private int fileVersion;
private Version version;
private Status status;
private String changes = "";
private File file = null;
private URL url = null;
private URL info = null;
private long size = 0;
private boolean hasZapAddOnEntry = false;
/**
* Flag that indicates if the manifest was read (or attempted to). Allows to prevent reading the manifest a second time when
* the add-on file is corrupt.
*/
private boolean manifestRead;
private String notBeforeVersion = null;
private String notFromVersion = null;
private String hash = null;
/**
* The installation status of the add-on.
* <p>
* Default is {@code NOT_INSTALLED}.
*
* @see InstallationStatus#NOT_INSTALLED
*/
private InstallationStatus installationStatus = InstallationStatus.NOT_INSTALLED;
private List<String> extensions = Collections.emptyList();
/**
* The extensions of the add-on that were loaded.
* <p>
* This instance variable is lazy initialised.
*
* @see #setLoadedExtensions(List)
* @see #addLoadedExtension(Extension)
*/
private List<Extension> loadedExtensions;
private List<String> ascanrules = Collections.emptyList();
private List<String> pscanrules = Collections.emptyList();
private List<String> files = Collections.emptyList();
private Dependencies dependencies;
private static final Logger logger = Logger.getLogger(AddOn.class);
public static boolean isAddOn(String fileName) {
if (! fileName.toLowerCase().endsWith(".zap")) {
return false;
}
if (fileName.substring(0, fileName.indexOf(".")).split("-").length < 3) {
return false;
}
String[] strArray = fileName.substring(0, fileName.indexOf(".")).split("-");
try {
Status.valueOf(strArray[1]);
Integer.parseInt(strArray[2]);
} catch (Exception e) {
return false;
}
return true;
}
public static boolean isAddOn(File f) {
if (! f.exists()) {
return false;
}
return isAddOn(f.getName());
}
public AddOn(String fileName) throws Exception {
// Format is <name>-<status>-<version>.zap
if (! isAddOn(fileName)) {
throw new Exception("Invalid ZAP add-on file " + fileName);
}
String[] strArray = fileName.substring(0, fileName.indexOf(".")).split("-");
this.id = strArray[0];
this.name = this.id; // Will be overriden if theres a ZapAddOn.xml file
this.status = Status.valueOf(strArray[1]);
this.fileVersion = Integer.parseInt(strArray[2]);
}
/**
* Constructs an {@code AddOn} from the given {@code file}.
* <p>
* The {@code ZapAddOn.xml} ZIP file entry is read after validating that the add-on has a valid add-on file name.
* <p>
* The installation status of the add-on is 'not installed'.
*
* @param file the file of the add-on
* @throws Exception if the given {@code file} does not exist, does not have a valid add-on file name or an error occurred
* while reading the {@code ZapAddOn.xml} ZIP file entry
*/
public AddOn(File file) throws Exception {
this(file.getName());
if (! isAddOn(file)) {
throw new Exception("Invalid ZAP add-on file " + file.getAbsolutePath());
}
this.file = file;
loadManifestFile();
}
private void loadManifestFile() throws IOException {
manifestRead = true;
if (file.exists()) {
// Might not exist in the tests
try (ZipFile zip = new ZipFile(file)) {
ZipEntry zapAddOnEntry = zip.getEntry("ZapAddOn.xml");
if (zapAddOnEntry != null) {
try (InputStream zis = zip.getInputStream(zapAddOnEntry)) {
ZapAddOnXmlFile zapAddOnXml = new ZapAddOnXmlFile(zis);
this.name = zapAddOnXml.getName();
this.version = zapAddOnXml.getVersion();
this.description = zapAddOnXml.getDescription();
this.changes = zapAddOnXml.getChanges();
this.author = zapAddOnXml.getAuthor();
this.notBeforeVersion = zapAddOnXml.getNotBeforeVersion();
this.notFromVersion = zapAddOnXml.getNotFromVersion();
this.dependencies = zapAddOnXml.getDependencies();
this.ascanrules = zapAddOnXml.getAscanrules();
this.extensions = zapAddOnXml.getExtensions();
this.files = zapAddOnXml.getFiles();
this.pscanrules = zapAddOnXml.getPscanrules();
hasZapAddOnEntry = true;
}
}
}
}
}
/**
* Constructs an {@code AddOn} from an add-on entry of {@code ZapVersions.xml} file. The installation status of the add-on
* is 'not installed'.
* <p>
* The given {@code SubnodeConfiguration} must have a {@code XPathExpressionEngine} installed.
* <p>
* The {@code ZapAddOn.xml} ZIP file entry is read, if the add-on file exists locally.
*
* @param id the id of the add-on
* @param baseDir the base directory where the add-on is located
* @param xmlData the source of add-on entry of {@code ZapVersions.xml} file
* @throws MalformedURLException if the {@code URL} of the add-on is malformed
* @throws IOException if an error occurs while reading the XML data
* @see org.apache.commons.configuration.tree.xpath.XPathExpressionEngine
*/
public AddOn(String id, File baseDir, SubnodeConfiguration xmlData) throws MalformedURLException, IOException {
this.id = id;
ZapVersionsAddOnEntry addOnData = new ZapVersionsAddOnEntry(xmlData);
this.name = addOnData.getName();
this.description = addOnData.getDescription();
this.author = addOnData.getAuthor();
this.fileVersion = addOnData.getPackageVersion();
this.dependencies = addOnData.getDependencies();
this.version = addOnData.getVersion();
this.status = AddOn.Status.valueOf(addOnData.getStatus());
this.changes = addOnData.getChanges();
this.url = new URL(addOnData.getUrl());
this.file = new File(baseDir, addOnData.getFile());
this.size = addOnData.getSize();
this.notBeforeVersion = addOnData.getNotBeforeVersion();
this.notFromVersion = addOnData.getNotFromVersion();
if (addOnData.getInfo() != null && !addOnData.getInfo().isEmpty()) {
try {
this.info = new URL(addOnData.getInfo());
} catch (Exception ignore) {
if (logger.isDebugEnabled()) {
logger.debug("Wrong info URL for add-on \"" + name + "\":", ignore);
}
}
}
this.hash = addOnData.getHash();
loadManifestFile();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getFileVersion() {
return fileVersion;
}
/**
* Gets the semantic version of this add-on.
*
* @return the semantic version of the add-on, or {@code null} if none
* @since 2.4.0
*/
public Version getVersion() {
return version;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getChanges() {
return changes;
}
public void setChanges(String changes) {
this.changes = changes;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public URL getUrl() {
return url;
}
public void setUrl(URL url) {
this.url = url;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
/**
* Sets the installation status of the add-on.
*
* @param installationStatus the new installation status
* @throws IllegalArgumentException if the given {@code installationStatus} is {@code null}.
* @since 2.4.0
*/
public void setInstallationStatus(InstallationStatus installationStatus) {
if (installationStatus == null) {
throw new IllegalArgumentException("Parameter installationStatus must not be null.");
}
this.installationStatus = installationStatus;
}
/**
* Gets installations status of the add-on.
*
* @return the installation status, never {@code null}
* @since 2.4.0
*/
public InstallationStatus getInstallationStatus() {
return installationStatus;
}
public boolean hasZapAddOnEntry() {
if (! hasZapAddOnEntry) {
if (!manifestRead) {
// Worth trying, as it depends which constructor has been used
try {
this.loadManifestFile();
} catch (IOException e) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to read the ZapAddOn.xml file of " + id + ":", e);
}
}
}
}
return hasZapAddOnEntry;
}
public List<String> getExtensions() {
return extensions;
}
/**
* Gets the extensions of this add-on that were loaded.
*
* @return an unmodifiable {@code List} with the extensions of this add-on that were loaded
* @since 2.4.0
*/
public List<Extension> getLoadedExtensions() {
if (loadedExtensions == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(loadedExtensions);
}
/**
* Sets the loaded extensions of this add-on to the given list of extensions.
* <p>
* It's made a copy of the given list.
* <p>
* This add-on is set to the given {@code extensions}.
*
* @param extensions the extensions of this add-on that were loaded
* @throws IllegalArgumentException if extensions is {@code null}
* @since 2.4.0
* @see Extension#setAddOn(AddOn)
*/
public void setLoadedExtensions(List<Extension> extensions) {
if (extensions == null) {
throw new IllegalArgumentException("Parameter extensions must not be null.");
}
if (loadedExtensions != null) {
for (Extension extension : loadedExtensions) {
extension.setAddOn(null);
}
}
loadedExtensions = new ArrayList<>(extensions);
for (Extension extension : loadedExtensions) {
extension.setAddOn(this);
}
}
/**
* Adds the given {@code extension} to the list of loaded extensions of this add-on.
* <p>
* This add-on is set to the given {@code extension}.
*
* @param extension the extension of this add-on that was loaded
* @since 2.4.0
* @see Extension#setAddOn(AddOn)
*/
public void addLoadedExtension(Extension extension) {
if (loadedExtensions == null) {
loadedExtensions = new ArrayList<>(1);
}
if (!loadedExtensions.contains(extension)) {
loadedExtensions.add(extension);
extension.setAddOn(this);
}
}
public List<String> getAscanrules() {
return ascanrules;
}
public List<String> getPscanrules() {
return pscanrules;
}
public List<String> getFiles() {
return files;
}
public boolean isSameAddOn(AddOn addOn) {
return this.getId().equals(addOn.getId());
}
public boolean isUpdateTo(AddOn addOn) throws IllegalArgumentException {
if (! this.isSameAddOn(addOn)) {
throw new IllegalArgumentException("Different addons: " + this.getId() + " != " + addOn.getId());
}
if (this.getFileVersion() > addOn.getFileVersion()) {
return true;
}
return this.getStatus().ordinal() > addOn.getStatus().ordinal();
}
/**
* @deprecated (2.4.0) Use {@link #calculateRunRequirements(Collection)} instead. Returns {@code false}.
*/
@Deprecated
@SuppressWarnings("javadoc")
public boolean canLoad() {
return false;
}
/**
* Tells whether or not this add-on can be loaded in the currently running ZAP version, as given by
* {@code Constant.PROGRAM_VERSION}.
*
* @return {@code true} if the add-on can be loaded in the currently running ZAP version, {@code false} otherwise
* @see #canLoadInVersion(String)
* @see Constant#PROGRAM_VERSION
*/
public boolean canLoadInCurrentVersion() {
return canLoadInVersion(Constant.PROGRAM_VERSION);
}
/**
* Tells whether or not this add-on can be run in the currently running Java version.
* <p>
* This is a convenience method that calls {@code canRunInJavaVersion(String)} with the running Java version (as given by
* {@code SystemUtils.JAVA_VERSION}) as parameter.
*
* @return {@code true} if the add-on can be run in the currently running Java version, {@code false} otherwise
* @since 2.4.0
* @see #canRunInJavaVersion(String)
* @see SystemUtils#JAVA_VERSION
*/
public boolean canRunInCurrentJavaVersion() {
return canRunInJavaVersion(SystemUtils.JAVA_VERSION);
}
/**
* Tells whether or not this add-on can be run in the given {@code javaVersion}.
* <p>
* If the given {@code javaVersion} is {@code null} and this add-on depends on a specific java version the method returns
* {@code false}.
*
* @param javaVersion the java version that will be checked
* @return {@code true} if the add-on can be loaded in the given {@code javaVersion}, {@code false} otherwise
* @since 2.4.0
*/
public boolean canRunInJavaVersion(String javaVersion) {
if (dependencies == null) {
return true;
}
String requiredVersion = dependencies.getJavaVersion();
if (requiredVersion == null) {
return true;
}
if (javaVersion == null) {
return false;
}
return getJavaVersion(javaVersion) >= getJavaVersion(requiredVersion);
}
/**
* Calculates the requirements to run this add-on, in the current ZAP and Java versions and with the given
* {@code availableAddOns}.
* <p>
* If the add-on depends on other add-ons, those add-ons are also checked if are also runnable.
* <p>
* <strong>Note:</strong> All the given {@code availableAddOns} are expected to be loadable in the currently running ZAP
* version, that is, the method {@code AddOn.canLoadInCurrentVersion()}, returns {@code true}.
*
* @param availableAddOns the other add-ons available
* @return a requirements to run the add-on, and if not runnable the reason why it's not.
* @since 2.4.0
* @see #canLoadInCurrentVersion()
* @see #canRunInCurrentJavaVersion()
* @see RunRequirements
*/
public RunRequirements calculateRunRequirements(Collection<AddOn> availableAddOns) {
return calculateRunRequirementsImpl(availableAddOns, new RunRequirements(), null, this);
}
private static RunRequirements calculateRunRequirementsImpl(
Collection<AddOn> availableAddOns,
RunRequirements requirements,
AddOn parent,
AddOn addOn) {
AddOn installedVersion = getAddOn(availableAddOns, addOn.getId());
if (installedVersion != null && !addOn.equals(installedVersion)) {
requirements.setRunnable(false);
requirements.setIssue(RunRequirements.DependencyIssue.OLDER_VERSION, installedVersion);
if (logger.isDebugEnabled()) {
logger.debug("Add-on " + addOn + " not runnable, old version still installed: " + installedVersion);
}
return requirements;
}
if (!requirements.addDependency(parent, addOn)) {
requirements.setRunnable(false);
logger.warn("Cyclic dependency detected with: " + requirements.getDependencies());
requirements.setIssue(RunRequirements.DependencyIssue.CYCLIC, requirements.getDependencies());
return requirements;
}
if (addOn.dependencies == null) {
return requirements;
}
if (!addOn.canRunInCurrentJavaVersion()) {
requirements.setRunnable(false);
requirements.setMinimumJavaVersionIssue(addOn, addOn.dependencies.getJavaVersion());
}
for (AddOnDep dependency : addOn.dependencies.getAddOns()) {
String addOnId = dependency.getId();
if (addOnId != null) {
AddOn addOnDep = getAddOn(availableAddOns, addOnId);
if (addOnDep == null) {
requirements.setRunnable(false);
requirements.setIssue(RunRequirements.DependencyIssue.MISSING, addOnId);
return requirements;
}
if (dependency.getNotBeforeVersion() > -1 && addOnDep.fileVersion < dependency.getNotBeforeVersion()) {
requirements.setRunnable(false);
requirements.setIssue(
RunRequirements.DependencyIssue.PACKAGE_VERSION_NOT_BEFORE,
addOnDep,
Integer.valueOf(dependency.getNotBeforeVersion()));
return requirements;
}
if (dependency.getNotFromVersion() > -1 && addOnDep.fileVersion > dependency.getNotFromVersion()) {
requirements.setRunnable(false);
requirements.setIssue(
RunRequirements.DependencyIssue.PACKAGE_VERSION_NOT_FROM,
addOnDep,
Integer.valueOf(dependency.getNotFromVersion()));
return requirements;
}
if (!dependency.getSemVer().isEmpty()) {
if (addOnDep.version == null || !addOnDep.version.matches(dependency.getSemVer())) {
requirements.setRunnable(false);
requirements.setIssue(RunRequirements.DependencyIssue.VERSION, addOnDep, dependency.getSemVer());
return requirements;
}
}
RunRequirements reqs = calculateRunRequirementsImpl(availableAddOns, requirements, addOn, addOnDep);
if (reqs.hasDependencyIssue()) {
return reqs;
}
}
}
return requirements;
}
/**
* Returns the minimum Java version required to run this add-on or an empty {@code String} if there's no minimum version.
*
* @return the minimum Java version required to run this add-on or an empty {@code String} if no minimum version
* @since 2.4.0
*/
public String getMinimumJavaVersion() {
if (dependencies == null) {
return "";
}
return dependencies.getJavaVersion();
}
/**
* Gets the add-on with the given {@code id} from the given collection of {@code addOns}.
*
* @param addOns the collection of add-ons where the search will be made
* @param id the id of the add-on to search for
* @return the {@code AddOn} with the given id, or {@code null} if not found
*/
private static AddOn getAddOn(Collection<AddOn> addOns, String id) {
for (AddOn addOn : addOns) {
if (addOn.getId().equals(id)) {
return addOn;
}
}
return null;
}
/**
* Tells whether or not this add-on can be loaded in the given {@code zapVersion}.
*
* @param zapVersion the ZAP version that will be checked
* @return {@code true} if the add-on can be loaded in the given {@code zapVersion}, {@code false} otherwise
*/
public boolean canLoadInVersion(String zapVersion) {
ZapReleaseComparitor zrc = new ZapReleaseComparitor();
ZapRelease zr = new ZapRelease(zapVersion);
if (this.notBeforeVersion != null && this.notBeforeVersion.length() > 0) {
ZapRelease notBeforeRelease = new ZapRelease(this.notBeforeVersion);
if (zrc.compare(zr, notBeforeRelease) < 0) {
return false;
}
if (zrc.compare(notBeforeRelease, v2_4) < 0) {
// Dont load any add-ons that imply they are prior to 2.4.0 - they probably wont work
return false;
}
}
if (this.notFromVersion != null && this.notFromVersion.length() > 0) {
ZapRelease notFromRelease = new ZapRelease(this.notFromVersion);
return (zrc.compare(zr, notFromRelease) < 0);
}
return true;
}
public void setNotBeforeVersion(String notBeforeVersion) {
this.notBeforeVersion = notBeforeVersion;
}
public void setNotFromVersion(String notFromVersion) {
this.notFromVersion = notFromVersion;
}
public String getNotBeforeVersion() {
return notBeforeVersion;
}
public String getNotFromVersion() {
return notFromVersion;
}
public URL getInfo() {
return info;
}
public void setInfo(URL info) {
this.info = info;
}
public String getHash() {
return hash;
}
/**
* Returns the IDs of the add-ons dependencies, an empty collection if none.
*
* @return the IDs of the dependencies.
* @since 2.4.0
*/
public List<String> getIdsAddOnDependencies() {
if (dependencies == null) {
return Collections.emptyList();
}
List<String> ids = new ArrayList<>(dependencies.getAddOns().size());
for (AddOnDep dep : dependencies.getAddOns()) {
ids.add(dep.getId());
}
return ids;
}
/**
* Tells whether or not this add-on has a (direct) dependency on the given {@code addOn} (including version).
*
* @param addOn the add-on that will be checked
* @return {@code true} if it depends on the given add-on, {@code false} otherwise.
* @since 2.4.0
*/
public boolean dependsOn(AddOn addOn) {
if (dependencies == null || dependencies.getAddOns().isEmpty()) {
return false;
}
for (AddOnDep dependency : dependencies.getAddOns()) {
if (dependency.getId().equals(addOn.id)) {
if (dependency.getNotBeforeVersion() > -1 && addOn.fileVersion < dependency.getNotBeforeVersion()) {
return false;
}
if (dependency.getNotFromVersion() > -1 && addOn.fileVersion > dependency.getNotFromVersion()) {
return false;
}
if (!dependency.getSemVer().isEmpty()) {
if (addOn.version == null) {
return false;
} else if (!addOn.version.matches(dependency.getSemVer())) {
return false;
}
}
return true;
}
}
return false;
}
/**
* Tells whether or not this add-on has a (direct) dependency on any of the given {@code addOns} (including version).
*
* @param addOns the add-ons that will be checked
* @return {@code true} if it depends on any of the given add-ons, {@code false} otherwise.
* @since 2.4.0
*/
public boolean dependsOn(Collection<AddOn> addOns) {
if (dependencies == null || dependencies.getAddOns().isEmpty()) {
return false;
}
for (AddOn addOn : addOns) {
if (dependsOn(addOn)) {
return true;
}
}
return false;
}
@Override
public String toString() {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append("[id=").append(id);
strBuilder.append(", fileVersion=").append(fileVersion);
if (version != null) {
strBuilder.append(", version=").append(version);
}
strBuilder.append(']');
return strBuilder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + fileVersion;
result = prime * result + ((version == null) ? 0 : version.hashCode());
return result;
}
/**
* Two add-ons are considered equal if both add-ons have the same ID, file version and semantic version.
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
AddOn other = (AddOn) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
if (fileVersion != other.fileVersion) {
return false;
}
if (version == null) {
if (other.version != null) {
return false;
}
} else if (!version.equals(other.version)) {
return false;
}
return true;
}
/**
* The requirements to run an {@code AddOn}.
* <p>
* It can be used to check if an add-on can or not be run, which requirements it has (for example, minimum Java version or
* dependency add-ons) and which issues prevent it from being run, if any.
*
* @since 2.4.0
*/
public static class RunRequirements {
/**
* The reason why an add-on can not be run because of a dependency.
* <p>
* More details of the issue can be obtained with the method {@code RunRequirements.getDependencyIssueDetails()}. The
* exact contents are mentioned in each {@code DependencyIssue} constant.
*
* @see RunRequirements#getDependencyIssueDetails()
*/
public enum DependencyIssue {
/**
* A cyclic dependency was detected.
* <p>
* Issue details contain all the add-ons in the cyclic chain.
*/
CYCLIC,
/**
* Older version of the add-on is still installed.
* <p>
* Issue details contain the old version.
*/
OLDER_VERSION,
/**
* A dependency was not found.
* <p>
* Issue details contain the id of the add-on.
*/
MISSING,
/**
* The dependency found has a older version than the version required.
* <p>
* Issue details contain the instance of the {@code AddOn} and the required version.
*/
PACKAGE_VERSION_NOT_BEFORE,
/**
* The dependency found has a newer version than the version required.
* <p>
* Issue details contain the instance of the {@code AddOn} and the required version.
*/
PACKAGE_VERSION_NOT_FROM,
/**
* The dependency found has a different semantic version.
* <p>
* Issue details contain the instance of the {@code AddOn} and the required version.
*/
VERSION
}
private final DirectedGraph<AddOn, DefaultEdge> dependencyTree;
private AddOn addOn;
private Set<AddOn> dependencies;
private DependencyIssue depIssue;
private List<Object> issueDetails;
private String minimumJavaVersion;
private AddOn addOnMinimumJavaVersion;
private boolean runnable;
protected RunRequirements() {
dependencyTree = new DefaultDirectedGraph<>(DefaultEdge.class);
runnable = true;
issueDetails = Collections.emptyList();
}
/**
* Gets the add-on that was tested to check if it can be run.
*
* @return the tested add-on
*/
public AddOn getAddOn() {
return addOn;
}
/**
* Tells whether or not this add-on has a dependency issue.
*
* @return {@code true} if the add-on has a dependency issue, {@code false} otherwise
* @see #getDependencyIssue()
* @see #getDependencyIssueDetails()
* @see DependencyIssue
*/
public boolean hasDependencyIssue() {
return (depIssue != null);
}
/**
* Gets the dependency issue, if any.
*
* @return the {@code DependencyIssue} or {@code null}, if none
* @see #hasDependencyIssue()
* @see #getDependencyIssueDetails()
* @see DependencyIssue
*/
public DependencyIssue getDependencyIssue() {
return depIssue;
}
/**
* Gets the details of the dependency issue, if any.
*
* @return a list containing the details of the issue or an empty list if none
* @see #hasDependencyIssue()
* @see #getDependencyIssue()
* @see DependencyIssue
*/
public List<Object> getDependencyIssueDetails() {
return issueDetails;
}
/**
* Tells whether or not this add-on requires a newer Java version to run.
* <p>
* The requirement might be imposed by a dependency or the add-on itself. To check which one use the methods
* {@code getAddOn()} and {@code getAddOnMinimumJavaVersion()}.
*
* @return {@code true} if the add-on requires a newer Java version, {@code false} otherwise.
* @see #getAddOn()
* @see #getAddOnMinimumJavaVersion()
* @see #getMinimumJavaVersion()
*/
public boolean isNewerJavaVersionRequired() {
return (minimumJavaVersion != null);
}
/**
* Gets the minimum Java version required to run the add-on.
*
* @return the Java version, or {@code null} if no minimum.
* @see #isNewerJavaVersionRequired()
* @see #getAddOn()
* @see #getAddOnMinimumJavaVersion()
*/
public String getMinimumJavaVersion() {
return minimumJavaVersion;
}
/**
* Gets the add-on that requires the minimum Java version.
*
* @return the add-on, or {@code null} if no minimum.
* @see #isNewerJavaVersionRequired()
* @see #getMinimumJavaVersion()
* @see #getAddOn()
*/
public AddOn getAddOnMinimumJavaVersion() {
return addOnMinimumJavaVersion;
}
/**DirectedAcyclicGraph
* Tells whether or not this add-on can be run.
*
* @return {@code true} if the add-on can be run, {@code false} otherwise
*/
public boolean isRunnable() {
return runnable;
}
/**
* Gets the (found) dependencies of the add-on, including transitive dependencies.
*
* @return a set containing the dependencies of the add-on
* @see AddOn#getIdsAddOnDependencies()
*/
public Set<AddOn> getDependencies() {
if (dependencies == null) {
dependencies = new HashSet<>();
for (TopologicalOrderIterator<AddOn, DefaultEdge> it = new TopologicalOrderIterator<>(dependencyTree); it.hasNext();) {
dependencies.add(it.next());
}
dependencies.remove(addOn);
}
return Collections.unmodifiableSet(dependencies);
}
protected void setIssue(DependencyIssue issue, Object... details) {
this.depIssue = issue;
if (details != null) {
issueDetails = Arrays.asList(details);
} else {
issueDetails = Collections.emptyList();
}
}
protected void setMinimumJavaVersionIssue(AddOn srcAddOn, String requiredVersion) {
if (minimumJavaVersion == null) {
setMinimumJavaVersion(srcAddOn, requiredVersion);
} else if (requiredVersion.compareTo(minimumJavaVersion) > 0) {
setMinimumJavaVersion(srcAddOn, requiredVersion);
}
}
private void setMinimumJavaVersion(AddOn srcAddOn, String requiredVersion) {
addOnMinimumJavaVersion = srcAddOn;
minimumJavaVersion = requiredVersion;
}
protected boolean addDependency(AddOn parent, AddOn addOn) {
if (parent == null) {
this.addOn = addOn;
dependencyTree.addVertex(addOn);
return true;
}
dependencyTree.addVertex(parent);
dependencyTree.addVertex(addOn);
dependencyTree.addEdge(parent, addOn);
CycleDetector<AddOn, DefaultEdge> cycleDetector = new CycleDetector<>(dependencyTree);
boolean cycle = cycleDetector.detectCycles();
if (cycle) {
dependencies = cycleDetector.findCycles();
return false;
}
return true;
}
protected void setRunnable(boolean runnable) {
this.runnable = runnable;
}
}
private static int getJavaVersion(String javaVersion) {
return toVersionInt(toJavaVersionIntArray(javaVersion, 2));
}
// NOTE: Following 2 methods copied from org.apache.commons.lang.SystemUtils version 2.6 because of constrained visibility
private static int[] toJavaVersionIntArray(String version, int limit) {
if (version == null) {
return ArrayUtils.EMPTY_INT_ARRAY;
}
String[] strings = StringUtils.split(version, "._- ");
int[] ints = new int[Math.min(limit, strings.length)];
int j = 0;
for (int i = 0; i < strings.length && j < limit; i++) {
String s = strings[i];
if (s.length() > 0) {
try {
ints[j] = Integer.parseInt(s);
j++;
} catch (Exception e) {
}
}
}
if (ints.length > j) {
int[] newInts = new int[j];
System.arraycopy(ints, 0, newInts, 0, j);
ints = newInts;
}
return ints;
}
private static int toVersionInt(int[] javaVersions) {
if (javaVersions == null) {
return 0;
}
int intVersion = 0;
int len = javaVersions.length;
if (len >= 1) {
intVersion = javaVersions[0] * 100;
}
if (len >= 2) {
intVersion += javaVersions[1] * 10;
}
if (len >= 3) {
intVersion += javaVersions[2];
}
return intVersion;
}
}
| src/org/zaproxy/zap/control/AddOn.java | /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2012 ZAP development team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zaproxy.zap.control;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.configuration.SubnodeConfiguration;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.SystemUtils;
import org.apache.log4j.Logger;
import org.jgrapht.DirectedGraph;
import org.jgrapht.alg.CycleDetector;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.traverse.TopologicalOrderIterator;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.extension.Extension;
import org.zaproxy.zap.Version;
import org.zaproxy.zap.control.BaseZapAddOnXmlData.AddOnDep;
import org.zaproxy.zap.control.BaseZapAddOnXmlData.Dependencies;
public class AddOn {
public enum Status {unknown, example, alpha, beta, weekly, release}
/**
* The installation status of the add-on.
*
* @since 2.4.0
*/
public enum InstallationStatus {
/**
* The add-on is available for installation, for example, an add-on in the marketplace (even if it requires previous
* actions, in this case, download the file).
*/
AVAILABLE,
/**
* The add-on was not (yet) installed. For example, the add-on is available in the 'plugin' directory but it's missing a
* dependency or requires a greater Java version. It's also in this status while a dependency is being updated.
*/
NOT_INSTALLED,
/**
* The add-on is installed.
*/
INSTALLED,
/**
* The add-on is being downloaded.
*/
DOWNLOADING,
/**
* The uninstallation of the add-on failed. For example, when the add-on is not dynamically installable or when an
* {@code Exception} is thrown during the uninstallation.
*/
UNINSTALLATION_FAILED,
/**
* The soft uninstallation of the add-on failed. It's in this status when the uninstallation failed for an update of a
* dependency.
*/
SOFT_UNINSTALLATION_FAILED
}
private String id;
private String name;
private String description = "";
private String author = "";
private int fileVersion;
private Version version;
private Status status;
private String changes = "";
private File file = null;
private URL url = null;
private URL info = null;
private long size = 0;
private boolean hasZapAddOnEntry = false;
/**
* Flag that indicates if the manifest was read (or attempted to). Allows to prevent reading the manifest a second time when
* the add-on file is corrupt.
*/
private boolean manifestRead;
private String notBeforeVersion = null;
private String notFromVersion = null;
private String hash = null;
/**
* The installation status of the add-on.
* <p>
* Default is {@code NOT_INSTALLED}.
*
* @see InstallationStatus#NOT_INSTALLED
*/
private InstallationStatus installationStatus = InstallationStatus.NOT_INSTALLED;
private List<String> extensions = Collections.emptyList();
/**
* The extensions of the add-on that were loaded.
* <p>
* This instance variable is lazy initialised.
*
* @see #setLoadedExtensions(List)
* @see #addLoadedExtension(Extension)
*/
private List<Extension> loadedExtensions;
private List<String> ascanrules = Collections.emptyList();
private List<String> pscanrules = Collections.emptyList();
private List<String> files = Collections.emptyList();
private Dependencies dependencies;
private static final Logger logger = Logger.getLogger(AddOn.class);
public static boolean isAddOn(String fileName) {
if (! fileName.toLowerCase().endsWith(".zap")) {
return false;
}
if (fileName.substring(0, fileName.indexOf(".")).split("-").length < 3) {
return false;
}
String[] strArray = fileName.substring(0, fileName.indexOf(".")).split("-");
try {
Status.valueOf(strArray[1]);
Integer.parseInt(strArray[2]);
} catch (Exception e) {
return false;
}
return true;
}
public static boolean isAddOn(File f) {
if (! f.exists()) {
return false;
}
return isAddOn(f.getName());
}
public AddOn(String fileName) throws Exception {
// Format is <name>-<status>-<version>.zap
if (! isAddOn(fileName)) {
throw new Exception("Invalid ZAP add-on file " + fileName);
}
String[] strArray = fileName.substring(0, fileName.indexOf(".")).split("-");
this.id = strArray[0];
this.name = this.id; // Will be overriden if theres a ZapAddOn.xml file
this.status = Status.valueOf(strArray[1]);
this.fileVersion = Integer.parseInt(strArray[2]);
}
/**
* Constructs an {@code AddOn} from the given {@code file}.
* <p>
* The {@code ZapAddOn.xml} ZIP file entry is read after validating that the add-on has a valid add-on file name.
* <p>
* The installation status of the add-on is 'not installed'.
*
* @param file the file of the add-on
* @throws Exception if the given {@code file} does not exist, does not have a valid add-on file name or an error occurred
* while reading the {@code ZapAddOn.xml} ZIP file entry
*/
public AddOn(File file) throws Exception {
this(file.getName());
if (! isAddOn(file)) {
throw new Exception("Invalid ZAP add-on file " + file.getAbsolutePath());
}
this.file = file;
loadManifestFile();
}
private void loadManifestFile() throws IOException {
manifestRead = true;
if (file.exists()) {
// Might not exist in the tests
try (ZipFile zip = new ZipFile(file)) {
ZipEntry zapAddOnEntry = zip.getEntry("ZapAddOn.xml");
if (zapAddOnEntry != null) {
try (InputStream zis = zip.getInputStream(zapAddOnEntry)) {
ZapAddOnXmlFile zapAddOnXml = new ZapAddOnXmlFile(zis);
this.name = zapAddOnXml.getName();
this.version = zapAddOnXml.getVersion();
this.description = zapAddOnXml.getDescription();
this.changes = zapAddOnXml.getChanges();
this.author = zapAddOnXml.getAuthor();
this.notBeforeVersion = zapAddOnXml.getNotBeforeVersion();
this.notFromVersion = zapAddOnXml.getNotFromVersion();
this.dependencies = zapAddOnXml.getDependencies();
this.ascanrules = zapAddOnXml.getAscanrules();
this.extensions = zapAddOnXml.getExtensions();
this.files = zapAddOnXml.getFiles();
this.pscanrules = zapAddOnXml.getPscanrules();
hasZapAddOnEntry = true;
}
}
}
}
}
/**
* Constructs an {@code AddOn} from an add-on entry of {@code ZapVersions.xml} file. The installation status of the add-on
* is 'not installed'.
* <p>
* The given {@code SubnodeConfiguration} must have a {@code XPathExpressionEngine} installed.
* <p>
* The {@code ZapAddOn.xml} ZIP file entry is read, if the add-on file exists locally.
*
* @param id the id of the add-on
* @param baseDir the base directory where the add-on is located
* @param xmlData the source of add-on entry of {@code ZapVersions.xml} file
* @throws MalformedURLException if the {@code URL} of the add-on is malformed
* @throws IOException if an error occurs while reading the XML data
* @see org.apache.commons.configuration.tree.xpath.XPathExpressionEngine
*/
public AddOn(String id, File baseDir, SubnodeConfiguration xmlData) throws MalformedURLException, IOException {
this.id = id;
ZapVersionsAddOnEntry addOnData = new ZapVersionsAddOnEntry(xmlData);
this.name = addOnData.getName();
this.description = addOnData.getDescription();
this.author = addOnData.getAuthor();
this.fileVersion = addOnData.getPackageVersion();
this.dependencies = addOnData.getDependencies();
this.version = addOnData.getVersion();
this.status = AddOn.Status.valueOf(addOnData.getStatus());
this.changes = addOnData.getChanges();
this.url = new URL(addOnData.getUrl());
this.file = new File(baseDir, addOnData.getFile());
this.size = addOnData.getSize();
this.notBeforeVersion = addOnData.getNotBeforeVersion();
this.notFromVersion = addOnData.getNotFromVersion();
if (addOnData.getInfo() != null && !addOnData.getInfo().isEmpty()) {
try {
this.info = new URL(addOnData.getInfo());
} catch (Exception ignore) {
if (logger.isDebugEnabled()) {
logger.debug("Wrong info URL for add-on \"" + name + "\":", ignore);
}
}
}
this.hash = addOnData.getHash();
loadManifestFile();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getFileVersion() {
return fileVersion;
}
/**
* Gets the semantic version of this add-on.
*
* @return the semantic version of the add-on, or {@code null} if none
* @since 2.4.0
*/
public Version getVersion() {
return version;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getChanges() {
return changes;
}
public void setChanges(String changes) {
this.changes = changes;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public URL getUrl() {
return url;
}
public void setUrl(URL url) {
this.url = url;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
/**
* Sets the installation status of the add-on.
*
* @param installationStatus the new installation status
* @throws IllegalArgumentException if the given {@code installationStatus} is {@code null}.
* @since 2.4.0
*/
public void setInstallationStatus(InstallationStatus installationStatus) {
if (installationStatus == null) {
throw new IllegalArgumentException("Parameter installationStatus must not be null.");
}
this.installationStatus = installationStatus;
}
/**
* Gets installations status of the add-on.
*
* @return the installation status, never {@code null}
* @since 2.4.0
*/
public InstallationStatus getInstallationStatus() {
return installationStatus;
}
public boolean hasZapAddOnEntry() {
if (! hasZapAddOnEntry) {
if (!manifestRead) {
// Worth trying, as it depends which constructor has been used
try {
this.loadManifestFile();
} catch (IOException e) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to read the ZapAddOn.xml file of " + id + ":", e);
}
}
}
}
return hasZapAddOnEntry;
}
public List<String> getExtensions() {
return extensions;
}
/**
* Gets the extensions of this add-on that were loaded.
*
* @return an unmodifiable {@code List} with the extensions of this add-on that were loaded
* @since 2.4.0
*/
public List<Extension> getLoadedExtensions() {
if (loadedExtensions == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(loadedExtensions);
}
/**
* Sets the loaded extensions of this add-on to the given list of extensions.
* <p>
* It's made a copy of the given list.
* <p>
* This add-on is set to the given {@code extensions}.
*
* @param extensions the extensions of this add-on that were loaded
* @throws IllegalArgumentException if extensions is {@code null}
* @since 2.4.0
* @see Extension#setAddOn(AddOn)
*/
public void setLoadedExtensions(List<Extension> extensions) {
if (extensions == null) {
throw new IllegalArgumentException("Parameter extensions must not be null.");
}
if (loadedExtensions != null) {
for (Extension extension : loadedExtensions) {
extension.setAddOn(null);
}
}
loadedExtensions = new ArrayList<>(extensions);
for (Extension extension : loadedExtensions) {
extension.setAddOn(this);
}
}
/**
* Adds the given {@code extension} to the list of loaded extensions of this add-on.
* <p>
* This add-on is set to the given {@code extension}.
*
* @param extension the extension of this add-on that was loaded
* @since 2.4.0
* @see Extension#setAddOn(AddOn)
*/
public void addLoadedExtension(Extension extension) {
if (loadedExtensions == null) {
loadedExtensions = new ArrayList<>(1);
}
if (!loadedExtensions.contains(extension)) {
loadedExtensions.add(extension);
extension.setAddOn(this);
}
}
public List<String> getAscanrules() {
return ascanrules;
}
public List<String> getPscanrules() {
return pscanrules;
}
public List<String> getFiles() {
return files;
}
public boolean isSameAddOn(AddOn addOn) {
return this.getId().equals(addOn.getId());
}
public boolean isUpdateTo(AddOn addOn) throws IllegalArgumentException {
if (! this.isSameAddOn(addOn)) {
throw new IllegalArgumentException("Different addons: " + this.getId() + " != " + addOn.getId());
}
if (this.getFileVersion() > addOn.getFileVersion()) {
return true;
}
return this.getStatus().ordinal() > addOn.getStatus().ordinal();
}
/**
* @deprecated (2.4.0) Use {@link #calculateRunRequirements(Collection)} instead. Returns {@code false}.
*/
@Deprecated
@SuppressWarnings("javadoc")
public boolean canLoad() {
return false;
}
/**
* Tells whether or not this add-on can be loaded in the currently running ZAP version, as given by
* {@code Constant.PROGRAM_VERSION}.
*
* @return {@code true} if the add-on can be loaded in the currently running ZAP version, {@code false} otherwise
* @see #canLoadInVersion(String)
* @see Constant#PROGRAM_VERSION
*/
public boolean canLoadInCurrentVersion() {
return canLoadInVersion(Constant.PROGRAM_VERSION);
}
/**
* Tells whether or not this add-on can be run in the currently running Java version.
* <p>
* This is a convenience method that calls {@code canRunInJavaVersion(String)} with the running Java version (as given by
* {@code SystemUtils.JAVA_VERSION}) as parameter.
*
* @return {@code true} if the add-on can be run in the currently running Java version, {@code false} otherwise
* @since 2.4.0
* @see #canRunInJavaVersion(String)
* @see SystemUtils#JAVA_VERSION
*/
public boolean canRunInCurrentJavaVersion() {
return canRunInJavaVersion(SystemUtils.JAVA_VERSION);
}
/**
* Tells whether or not this add-on can be run in the given {@code javaVersion}.
* <p>
* If the given {@code javaVersion} is {@code null} and this add-on depends on a specific java version the method returns
* {@code false}.
*
* @param javaVersion the java version that will be checked
* @return {@code true} if the add-on can be loaded in the given {@code javaVersion}, {@code false} otherwise
* @since 2.4.0
*/
public boolean canRunInJavaVersion(String javaVersion) {
if (dependencies == null) {
return true;
}
String requiredVersion = dependencies.getJavaVersion();
if (requiredVersion == null) {
return true;
}
if (javaVersion == null) {
return false;
}
return getJavaVersion(javaVersion) >= getJavaVersion(requiredVersion);
}
/**
* Calculates the requirements to run this add-on, in the current ZAP and Java versions and with the given
* {@code availableAddOns}.
* <p>
* If the add-on depends on other add-ons, those add-ons are also checked if are also runnable.
* <p>
* <strong>Note:</strong> All the given {@code availableAddOns} are expected to be loadable in the currently running ZAP
* version, that is, the method {@code AddOn.canLoadInCurrentVersion()}, returns {@code true}.
*
* @param availableAddOns the other add-ons available
* @return a requirements to run the add-on, and if not runnable the reason why it's not.
* @since 2.4.0
* @see #canLoadInCurrentVersion()
* @see #canRunInCurrentJavaVersion()
* @see RunRequirements
*/
public RunRequirements calculateRunRequirements(Collection<AddOn> availableAddOns) {
return calculateRunRequirementsImpl(availableAddOns, new RunRequirements(), null, this);
}
private static RunRequirements calculateRunRequirementsImpl(
Collection<AddOn> availableAddOns,
RunRequirements requirements,
AddOn parent,
AddOn addOn) {
AddOn installedVersion = getAddOn(availableAddOns, addOn.getId());
if (installedVersion != null && !addOn.equals(installedVersion)) {
requirements.setRunnable(false);
requirements.setIssue(RunRequirements.DependencyIssue.OLDER_VERSION, installedVersion);
if (logger.isDebugEnabled()) {
logger.debug("Add-on " + addOn + " not runnable, old version still installed: " + installedVersion);
}
return requirements;
}
if (!requirements.addDependency(parent, addOn)) {
requirements.setRunnable(false);
logger.warn("Cyclic dependency detected with: " + requirements.getDependencies());
requirements.setIssue(RunRequirements.DependencyIssue.CYCLIC, requirements.getDependencies());
return requirements;
}
if (addOn.dependencies == null) {
return requirements;
}
if (!addOn.canRunInCurrentJavaVersion()) {
requirements.setRunnable(false);
requirements.setMinimumJavaVersionIssue(addOn, addOn.dependencies.getJavaVersion());
}
for (AddOnDep dependency : addOn.dependencies.getAddOns()) {
String addOnId = dependency.getId();
if (addOnId != null) {
AddOn addOnDep = getAddOn(availableAddOns, addOnId);
if (addOnDep == null) {
requirements.setRunnable(false);
requirements.setIssue(RunRequirements.DependencyIssue.MISSING, addOnId);
return requirements;
}
if (dependency.getNotBeforeVersion() > -1 && addOnDep.fileVersion < dependency.getNotBeforeVersion()) {
requirements.setRunnable(false);
requirements.setIssue(
RunRequirements.DependencyIssue.PACKAGE_VERSION_NOT_BEFORE,
addOnDep,
Integer.valueOf(dependency.getNotBeforeVersion()));
return requirements;
}
if (dependency.getNotFromVersion() > -1 && addOnDep.fileVersion > dependency.getNotFromVersion()) {
requirements.setRunnable(false);
requirements.setIssue(
RunRequirements.DependencyIssue.PACKAGE_VERSION_NOT_FROM,
addOnDep,
Integer.valueOf(dependency.getNotFromVersion()));
return requirements;
}
if (!dependency.getSemVer().isEmpty()) {
if (addOnDep.version == null || !addOnDep.version.matches(dependency.getSemVer())) {
requirements.setRunnable(false);
requirements.setIssue(RunRequirements.DependencyIssue.VERSION, addOnDep, dependency.getSemVer());
return requirements;
}
}
RunRequirements reqs = calculateRunRequirementsImpl(availableAddOns, requirements, addOn, addOnDep);
if (reqs.hasDependencyIssue()) {
return reqs;
}
}
}
return requirements;
}
/**
* Returns the minimum Java version required to run this add-on or an empty {@code String} if there's no minimum version.
*
* @return the minimum Java version required to run this add-on or an empty {@code String} if no minimum version
* @since 2.4.0
*/
public String getMinimumJavaVersion() {
if (dependencies == null) {
return "";
}
return dependencies.getJavaVersion();
}
/**
* Gets the add-on with the given {@code id} from the given collection of {@code addOns}.
*
* @param addOns the collection of add-ons where the search will be made
* @param id the id of the add-on to search for
* @return the {@code AddOn} with the given id, or {@code null} if not found
*/
private static AddOn getAddOn(Collection<AddOn> addOns, String id) {
for (AddOn addOn : addOns) {
if (addOn.getId().equals(id)) {
return addOn;
}
}
return null;
}
/**
* Tells whether or not this add-on can be loaded in the given {@code zapVersion}.
*
* @param zapVersion the ZAP version that will be checked
* @return {@code true} if the add-on can be loaded in the given {@code zapVersion}, {@code false} otherwise
*/
public boolean canLoadInVersion(String zapVersion) {
ZapReleaseComparitor zrc = new ZapReleaseComparitor();
ZapRelease zr = new ZapRelease(zapVersion);
if (this.notBeforeVersion != null && this.notBeforeVersion.length() > 0) {
ZapRelease notBeforeRelease = new ZapRelease(this.notBeforeVersion);
if (zrc.compare(zr, notBeforeRelease) < 0) {
return false;
}
}
if (this.notFromVersion != null && this.notFromVersion.length() > 0) {
ZapRelease notFromRelease = new ZapRelease(this.notFromVersion);
return (zrc.compare(zr, notFromRelease) < 0);
}
return true;
}
public void setNotBeforeVersion(String notBeforeVersion) {
this.notBeforeVersion = notBeforeVersion;
}
public void setNotFromVersion(String notFromVersion) {
this.notFromVersion = notFromVersion;
}
public String getNotBeforeVersion() {
return notBeforeVersion;
}
public String getNotFromVersion() {
return notFromVersion;
}
public URL getInfo() {
return info;
}
public void setInfo(URL info) {
this.info = info;
}
public String getHash() {
return hash;
}
/**
* Returns the IDs of the add-ons dependencies, an empty collection if none.
*
* @return the IDs of the dependencies.
* @since 2.4.0
*/
public List<String> getIdsAddOnDependencies() {
if (dependencies == null) {
return Collections.emptyList();
}
List<String> ids = new ArrayList<>(dependencies.getAddOns().size());
for (AddOnDep dep : dependencies.getAddOns()) {
ids.add(dep.getId());
}
return ids;
}
/**
* Tells whether or not this add-on has a (direct) dependency on the given {@code addOn} (including version).
*
* @param addOn the add-on that will be checked
* @return {@code true} if it depends on the given add-on, {@code false} otherwise.
* @since 2.4.0
*/
public boolean dependsOn(AddOn addOn) {
if (dependencies == null || dependencies.getAddOns().isEmpty()) {
return false;
}
for (AddOnDep dependency : dependencies.getAddOns()) {
if (dependency.getId().equals(addOn.id)) {
if (dependency.getNotBeforeVersion() > -1 && addOn.fileVersion < dependency.getNotBeforeVersion()) {
return false;
}
if (dependency.getNotFromVersion() > -1 && addOn.fileVersion > dependency.getNotFromVersion()) {
return false;
}
if (!dependency.getSemVer().isEmpty()) {
if (addOn.version == null) {
return false;
} else if (!addOn.version.matches(dependency.getSemVer())) {
return false;
}
}
return true;
}
}
return false;
}
/**
* Tells whether or not this add-on has a (direct) dependency on any of the given {@code addOns} (including version).
*
* @param addOns the add-ons that will be checked
* @return {@code true} if it depends on any of the given add-ons, {@code false} otherwise.
* @since 2.4.0
*/
public boolean dependsOn(Collection<AddOn> addOns) {
if (dependencies == null || dependencies.getAddOns().isEmpty()) {
return false;
}
for (AddOn addOn : addOns) {
if (dependsOn(addOn)) {
return true;
}
}
return false;
}
@Override
public String toString() {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append("[id=").append(id);
strBuilder.append(", fileVersion=").append(fileVersion);
if (version != null) {
strBuilder.append(", version=").append(version);
}
strBuilder.append(']');
return strBuilder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + fileVersion;
result = prime * result + ((version == null) ? 0 : version.hashCode());
return result;
}
/**
* Two add-ons are considered equal if both add-ons have the same ID, file version and semantic version.
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
AddOn other = (AddOn) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
if (fileVersion != other.fileVersion) {
return false;
}
if (version == null) {
if (other.version != null) {
return false;
}
} else if (!version.equals(other.version)) {
return false;
}
return true;
}
/**
* The requirements to run an {@code AddOn}.
* <p>
* It can be used to check if an add-on can or not be run, which requirements it has (for example, minimum Java version or
* dependency add-ons) and which issues prevent it from being run, if any.
*
* @since 2.4.0
*/
public static class RunRequirements {
/**
* The reason why an add-on can not be run because of a dependency.
* <p>
* More details of the issue can be obtained with the method {@code RunRequirements.getDependencyIssueDetails()}. The
* exact contents are mentioned in each {@code DependencyIssue} constant.
*
* @see RunRequirements#getDependencyIssueDetails()
*/
public enum DependencyIssue {
/**
* A cyclic dependency was detected.
* <p>
* Issue details contain all the add-ons in the cyclic chain.
*/
CYCLIC,
/**
* Older version of the add-on is still installed.
* <p>
* Issue details contain the old version.
*/
OLDER_VERSION,
/**
* A dependency was not found.
* <p>
* Issue details contain the id of the add-on.
*/
MISSING,
/**
* The dependency found has a older version than the version required.
* <p>
* Issue details contain the instance of the {@code AddOn} and the required version.
*/
PACKAGE_VERSION_NOT_BEFORE,
/**
* The dependency found has a newer version than the version required.
* <p>
* Issue details contain the instance of the {@code AddOn} and the required version.
*/
PACKAGE_VERSION_NOT_FROM,
/**
* The dependency found has a different semantic version.
* <p>
* Issue details contain the instance of the {@code AddOn} and the required version.
*/
VERSION
}
private final DirectedGraph<AddOn, DefaultEdge> dependencyTree;
private AddOn addOn;
private Set<AddOn> dependencies;
private DependencyIssue depIssue;
private List<Object> issueDetails;
private String minimumJavaVersion;
private AddOn addOnMinimumJavaVersion;
private boolean runnable;
protected RunRequirements() {
dependencyTree = new DefaultDirectedGraph<>(DefaultEdge.class);
runnable = true;
issueDetails = Collections.emptyList();
}
/**
* Gets the add-on that was tested to check if it can be run.
*
* @return the tested add-on
*/
public AddOn getAddOn() {
return addOn;
}
/**
* Tells whether or not this add-on has a dependency issue.
*
* @return {@code true} if the add-on has a dependency issue, {@code false} otherwise
* @see #getDependencyIssue()
* @see #getDependencyIssueDetails()
* @see DependencyIssue
*/
public boolean hasDependencyIssue() {
return (depIssue != null);
}
/**
* Gets the dependency issue, if any.
*
* @return the {@code DependencyIssue} or {@code null}, if none
* @see #hasDependencyIssue()
* @see #getDependencyIssueDetails()
* @see DependencyIssue
*/
public DependencyIssue getDependencyIssue() {
return depIssue;
}
/**
* Gets the details of the dependency issue, if any.
*
* @return a list containing the details of the issue or an empty list if none
* @see #hasDependencyIssue()
* @see #getDependencyIssue()
* @see DependencyIssue
*/
public List<Object> getDependencyIssueDetails() {
return issueDetails;
}
/**
* Tells whether or not this add-on requires a newer Java version to run.
* <p>
* The requirement might be imposed by a dependency or the add-on itself. To check which one use the methods
* {@code getAddOn()} and {@code getAddOnMinimumJavaVersion()}.
*
* @return {@code true} if the add-on requires a newer Java version, {@code false} otherwise.
* @see #getAddOn()
* @see #getAddOnMinimumJavaVersion()
* @see #getMinimumJavaVersion()
*/
public boolean isNewerJavaVersionRequired() {
return (minimumJavaVersion != null);
}
/**
* Gets the minimum Java version required to run the add-on.
*
* @return the Java version, or {@code null} if no minimum.
* @see #isNewerJavaVersionRequired()
* @see #getAddOn()
* @see #getAddOnMinimumJavaVersion()
*/
public String getMinimumJavaVersion() {
return minimumJavaVersion;
}
/**
* Gets the add-on that requires the minimum Java version.
*
* @return the add-on, or {@code null} if no minimum.
* @see #isNewerJavaVersionRequired()
* @see #getMinimumJavaVersion()
* @see #getAddOn()
*/
public AddOn getAddOnMinimumJavaVersion() {
return addOnMinimumJavaVersion;
}
/**DirectedAcyclicGraph
* Tells whether or not this add-on can be run.
*
* @return {@code true} if the add-on can be run, {@code false} otherwise
*/
public boolean isRunnable() {
return runnable;
}
/**
* Gets the (found) dependencies of the add-on, including transitive dependencies.
*
* @return a set containing the dependencies of the add-on
* @see AddOn#getIdsAddOnDependencies()
*/
public Set<AddOn> getDependencies() {
if (dependencies == null) {
dependencies = new HashSet<>();
for (TopologicalOrderIterator<AddOn, DefaultEdge> it = new TopologicalOrderIterator<>(dependencyTree); it.hasNext();) {
dependencies.add(it.next());
}
dependencies.remove(addOn);
}
return Collections.unmodifiableSet(dependencies);
}
protected void setIssue(DependencyIssue issue, Object... details) {
this.depIssue = issue;
if (details != null) {
issueDetails = Arrays.asList(details);
} else {
issueDetails = Collections.emptyList();
}
}
protected void setMinimumJavaVersionIssue(AddOn srcAddOn, String requiredVersion) {
if (minimumJavaVersion == null) {
setMinimumJavaVersion(srcAddOn, requiredVersion);
} else if (requiredVersion.compareTo(minimumJavaVersion) > 0) {
setMinimumJavaVersion(srcAddOn, requiredVersion);
}
}
private void setMinimumJavaVersion(AddOn srcAddOn, String requiredVersion) {
addOnMinimumJavaVersion = srcAddOn;
minimumJavaVersion = requiredVersion;
}
protected boolean addDependency(AddOn parent, AddOn addOn) {
if (parent == null) {
this.addOn = addOn;
dependencyTree.addVertex(addOn);
return true;
}
dependencyTree.addVertex(parent);
dependencyTree.addVertex(addOn);
dependencyTree.addEdge(parent, addOn);
CycleDetector<AddOn, DefaultEdge> cycleDetector = new CycleDetector<>(dependencyTree);
boolean cycle = cycleDetector.detectCycles();
if (cycle) {
dependencies = cycleDetector.findCycles();
return false;
}
return true;
}
protected void setRunnable(boolean runnable) {
this.runnable = runnable;
}
}
private static int getJavaVersion(String javaVersion) {
return toVersionInt(toJavaVersionIntArray(javaVersion, 2));
}
// NOTE: Following 2 methods copied from org.apache.commons.lang.SystemUtils version 2.6 because of constrained visibility
private static int[] toJavaVersionIntArray(String version, int limit) {
if (version == null) {
return ArrayUtils.EMPTY_INT_ARRAY;
}
String[] strings = StringUtils.split(version, "._- ");
int[] ints = new int[Math.min(limit, strings.length)];
int j = 0;
for (int i = 0; i < strings.length && j < limit; i++) {
String s = strings[i];
if (s.length() > 0) {
try {
ints[j] = Integer.parseInt(s);
j++;
} catch (Exception e) {
}
}
}
if (ints.length > j) {
int[] newInts = new int[j];
System.arraycopy(ints, 0, newInts, 0, j);
ints = newInts;
}
return ints;
}
private static int toVersionInt(int[] javaVersions) {
if (javaVersions == null) {
return 0;
}
int intVersion = 0;
int len = javaVersions.length;
if (len >= 1) {
intVersion = javaVersions[0] * 100;
}
if (len >= 2) {
intVersion += javaVersions[1] * 10;
}
if (len >= 3) {
intVersion += javaVersions[2];
}
return intVersion;
}
}
| Disable any add-ons that appear to be from 2.3.0 or before
| src/org/zaproxy/zap/control/AddOn.java | Disable any add-ons that appear to be from 2.3.0 or before |
|
Java | mit | d055a8266e7739994d3afc3371e6d3b198778bb6 | 0 | cucumber/cucumber-jvm,cucumber/cucumber-jvm,cucumber/cucumber-jvm,cucumber/cucumber-jvm,cucumber/cucumber-jvm | package io.cucumber.datatable;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.RandomAccess;
import static io.cucumber.datatable.CucumberDataTableException.duplicateKeyException;
import static java.util.Collections.emptyList;
import static java.util.Collections.unmodifiableList;
import static java.util.Collections.unmodifiableMap;
/**
* A m-by-n table of string values. For example:
* <p>
* <pre>
* | | firstName | lastName | birthDate |
* | 4a1 | Annie M. G. | Schmidt | 1911-03-20 |
* | c92 | Roald | Dahl | 1916-09-13 |
* </pre>
* <p>
* A table is either empty or contains one or more cells. As
* such if a table has zero height it must have zero width and
* vise versa.
* <p>
* The first row of the the table may be referred to as the
* table header. The remaining cells as the table body.
* <p>
* A table can be converted into an objects of an arbitrary
* type by a {@link TableConverter}. A table created without
* a table converter will throw a {@link NoConverterDefined}
* exception when doing so.
* <p>
* A DataTable is immutable and thread safe.
*/
public final class DataTable {
private final List<List<String>> raw;
private final TableConverter tableConverter;
/**
* Creates a new DataTable.
* <p>
* To improve performance this constructor assumes the provided raw table
* is rectangular, free of null values, immutable and a safe copy.
*
* @param raw the underlying table
* @param tableConverter to transform the table
* @throws NullPointerException if either raw or tableConverter is null
*/
private DataTable(List<List<String>> raw, TableConverter tableConverter) {
if (raw == null) throw new NullPointerException("cells can not be null");
if (tableConverter == null) throw new NullPointerException("tableConverter can not be null");
this.raw = raw;
this.tableConverter = tableConverter;
}
/**
* Creates a new DataTable.
* <p>
*
* @param raw the underlying table
* @return an new data table containing the raw values
* @throws NullPointerException if raw is null
* @throws IllegalArgumentException when the table is not rectangular or contains null values.
*/
public static DataTable create(List<List<String>> raw) {
return create(raw, new NoConverterDefined());
}
/**
* Creates a new DataTable with a table converter.
*
* @param raw the underlying table
* @param tableConverter to transform the table
* @return an new data table containing the raw values
* @throws NullPointerException if either raw or tableConverter is null
* @throws IllegalArgumentException when the table is not rectangular or contains null values
*/
public static DataTable create(List<List<String>> raw, TableConverter tableConverter) {
return new DataTable(copy(requireNonNullEntries(requireRectangularTable(raw))), tableConverter);
}
private static List<List<String>> copy(List<List<String>> balanced) {
List<List<String>> rawCopy = new ArrayList<>(balanced.size());
for (List<String> row : balanced) {
// A table without columns is an empty table and has no rows.
if (row.isEmpty()) {
return emptyList();
}
List<String> rowCopy = new ArrayList<>(row.size());
rowCopy.addAll(row);
rawCopy.add(unmodifiableList(rowCopy));
}
return unmodifiableList(rawCopy);
}
private static List<List<String>> requireNonNullEntries(List<List<String>> raw) {
// Iterate in case of linked list.
int rowIndex = 0;
for (List<String> row : raw) {
int columnIndex = row.indexOf(null);
if (columnIndex >= 0) {
throw new IllegalArgumentException(
"raw contained null at row: " + rowIndex + " column: " + columnIndex);
}
rowIndex++;
}
return raw;
}
private static List<List<String>> requireRectangularTable(List<List<String>> table) {
int columns = table.isEmpty() ? 0 : table.get(0).size();
for (List<String> row : table) {
if (columns != row.size()) {
throw new IllegalArgumentException(String.format("Table is not rectangular: expected %s column(s) but found %s.", columns, row.size()));
}
}
return table;
}
/**
* Creates an empty DataTable.
*
* @return an empty DataTable
*/
public static DataTable emptyDataTable() {
return new DataTable(Collections.<List<String>>emptyList(), new NoConverterDefined());
}
/**
* Returns a list view on the table. Contains the cells ordered from
* left to right, top to bottom starting at the top left.
*
* @return
*/
public List<String> asList() {
return new ListView();
}
/**
* Converts the table to a list of {@code itemType}.
*
* @param itemType the type of the list items
* @param <T> the type of the list items
* @return a List of objects
*/
public <T> List<T> asList(Type itemType) {
return tableConverter.toList(this, itemType);
}
/**
* Converts the table to a list of list of string.
*
* @return a list of list of string objects
*/
public List<List<String>> asLists() {
return cells();
}
/**
* Converts the table to a list of list of string.
*
* @return a list of list of string objects
*/
public List<List<String>> cells() {
return raw;
}
/**
* Converts the table to a list of lists of {@code itemType}.
*
* @param itemType the type of the list items
* @param <T> the type of the list items
* @return a list of list of objects
*/
public <T> List<List<T>> asLists(Type itemType) {
return tableConverter.toLists(this, itemType);
}
/**
* Converts the table to a single map of {@code keyType} to {@code valueType}.
* <p>
* For each row the first cell is used to create the key value. The
* remaining cells are used to create the value. If the table only has a single
* column that value is null.
*
* @param <K> key type
* @param <V> value type
* @param keyType key type
* @param valueType value type
* @return a map
* @throws CucumberDataTableException when the table contains duplicate keys
*/
public <K, V> Map<K, V> asMap(Type keyType, Type valueType) {
return tableConverter.toMap(this, keyType, valueType);
}
/**
* Converts the table to a list of maps of strings. For each row in the body
* of the table a map is created containing a mapping of column headers to
* the column cell of that row.
*
* @return a list of maps
* @throws CucumberDataTableException when the table contains duplicate keys
*/
public List<Map<String, String>> asMaps() {
if (raw.isEmpty()) return emptyList();
List<String> headers = raw.get(0);
List<Map<String, String>> headersAndRows = new ArrayList<>();
for (int i = 1; i < raw.size(); i++) {
List<String> row = raw.get(i);
LinkedHashMap<String, String> headersAndRow = new LinkedHashMap<>();
for (int j = 0; j < headers.size(); j++) {
String replaced = headersAndRow.put(headers.get(j), row.get(j));
if (replaced != null) {
throw duplicateKeyException(String.class, String.class, headers.get(j), row.get(j), replaced);
}
}
headersAndRows.add(unmodifiableMap(headersAndRow));
}
return unmodifiableList(headersAndRows);
}
/**
* Converts the table to a list of maps of {@code keyType} to {@code valueType}.
* For each row in the body of the table a map is created containing a mapping
* of column headers to the column cell of that row.
*
* @param <K> key type
* @param <V> value type
* @param keyType key type
* @param valueType value type
* @return a list of maps
* @throws CucumberDataTableException when the table contains duplicate keys
*/
public <K, V> List<Map<K, V>> asMaps(Type keyType, Type valueType) {
return tableConverter.toMaps(this, keyType, valueType);
}
/**
* Returns a single table cell.
*
* @param row row index of the cell
* @param column column index of the cell
* @return a single table cell
* @throws IndexOutOfBoundsException when either {@code row} or {@code column}
* is outside the table.
*/
public String cell(int row, int column) {
rangeCheckRow(row, height());
rangeCheckColumn(column, width());
return raw.get(row).get(column);
}
private static void rangeCheck(int index, int size) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("index: " + index + ", Size: " + size);
}
private static void rangeCheckRow(int row, int height) {
if (row < 0 || row >= height)
throw new IndexOutOfBoundsException("row: " + row + ", Height: " + height);
}
private static void rangeCheckColumn(int column, int width) {
if (column < 0 || column >= width)
throw new IndexOutOfBoundsException("column: " + column + ", Width: " + width);
}
/**
* Returns a single column.
*
* @param column column index the column
* @return a single column
* @throws IndexOutOfBoundsException when {@code column}
* is outside the table.
*/
public List<String> column(final int column) {
return new ColumnView(column);
}
/**
* Returns a table that is a view on a portion of this
* table. The sub table begins at {@code fromColumn} inclusive
* and extends to the end of that table.
*
* @param fromColumn the beginning column index, inclusive
* @return the specified sub table
* @throws IndexOutOfBoundsException when any endpoint is
* outside the table.
* @throws IllegalArgumentException when a from endpoint
* comes after an to endpoint
*/
public DataTable columns(final int fromColumn) {
return columns(fromColumn, width());
}
/**
* Returns a table that is a view on a portion of this
* table. The sub table begins at {@code fromColumn} inclusive
* and extends to {@code toColumn} exclusive.
*
* @param fromColumn the beginning column index, inclusive
* @param toColumn the end column index, exclusive
* @return the specified sub table
* @throws IndexOutOfBoundsException when any endpoint is outside
* the table.
* @throws IllegalArgumentException when a from endpoint comes
* after an to endpoint
*/
public DataTable columns(final int fromColumn, final int toColumn) {
return subTable(0, fromColumn, height(), toColumn);
}
/**
* Converts a table to {@code type}.
*
* @param type the desired type
* @param transposed transpose the table before transformation
* @param <T> the desired type
* @return an instance of {@code type}
* @throws CucumberDataTableException if the table could not be
* transformed to {@code type}.
*/
public <T> T convert(Type type, boolean transposed) {
return tableConverter.convert(this, type, transposed);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DataTable dataTable = (DataTable) o;
return raw.equals(dataTable.raw);
}
@Override
public int hashCode() {
return raw.hashCode();
}
/**
* Returns true iff this table has no cells.
*
* @return true iff this table has no cells
*/
public boolean isEmpty() {
return raw.isEmpty();
}
/**
* Returns a single row.
*
* @param row row index the column
* @return a single row
* @throws IndexOutOfBoundsException when {@code row}
* is outside the table.
*/
public List<String> row(int row) {
rangeCheckRow(row, height());
return raw.get(row);
}
/**
* Returns a table that is a view on a portion of this
* table. The sub table begins at {@code fromRow} inclusive
* and extends to the end of that table.
*
* @param fromRow the beginning row index, inclusive
* @return the specified sub table
* @throws IndexOutOfBoundsException when any endpoint is
* outside the table.
* @throws IllegalArgumentException when a from endpoint
* comes after an to endpoint
*/
public DataTable rows(int fromRow) {
return rows(fromRow, height());
}
/**
* Returns a table that is a view on a portion of this
* table. The sub table begins at {@code fromRow} inclusive
* and extends to {@code toRow} exclusive.
*
* @param fromRow the beginning row index, inclusive
* @param toRow the end row index, exclusive
* @return the specified sub table
* @throws IndexOutOfBoundsException when any endpoint is outside
* the table.
* @throws IllegalArgumentException when a from endpoint comes
* after an to endpoint
*/
public DataTable rows(int fromRow, int toRow) {
return subTable(fromRow, 0, toRow, width());
}
/**
* Returns a table that is a view on a portion of this
* table. The sub table begins at {@code fromRow} inclusive and
* {@code fromColumn} inclusive and extends to the last column
* and row.
*
* @param fromRow the beginning row index, inclusive
* @param fromColumn the beginning column index, inclusive
* @return the specified sub table
* @throws IndexOutOfBoundsException when any endpoint is outside
* the table.
*/
public DataTable subTable(int fromRow, int fromColumn) {
return subTable(fromRow, fromColumn, height(), width());
}
/**
* Returns a table that is a view on a portion of this
* table. The sub table begins at {@code fromRow} inclusive and
* {@code fromColumn} inclusive and extends to {@code toRow}
* exclusive and {@code toColumn} exclusive.
*
* @param fromRow the beginning row index, inclusive
* @param fromColumn the beginning column index, inclusive
* @param toRow the end row index, exclusive
* @param toColumn the end column index, exclusive
* @return the specified sub table
* @throws IndexOutOfBoundsException when any endpoint is outside
* the table.
* @throws IllegalArgumentException when a from endpoint comes
* after an to endpoint
*/
public DataTable subTable(int fromRow, int fromColumn, int toRow, int toColumn) {
return new DataTable(new RawDataTableView(fromRow, fromColumn, toColumn, toRow), tableConverter);
}
/**
* Returns the number of rows in the table.
*
* @return the number of rows in the table
*/
public int height() {
return raw.size();
}
/**
* Returns the number of columns in the table.
*
* @return the number of columns in the table
*/
public int width() {
return raw.isEmpty() ? 0 : raw.get(0).size();
}
/**
* Returns a string representation of the this
* table.
*/
@Override
public String toString() {
StringBuilder result = new StringBuilder();
print(result);
return result.toString();
}
/**
* Prints a string representation of this
* table to the {@code appendable}.
*
* @param appendable to append the string representation
* of this table to.
* @throws IOException If an I/O error occurs
*/
public void print(Appendable appendable) throws IOException {
TablePrinter printer = new TablePrinter();
printer.printTable(raw, appendable);
}
/**
* Prints a string representation of this
* table to the {@code appendable}.
*
* @param appendable to append the string representation
* of this table to.
*/
public void print(StringBuilder appendable) {
TablePrinter printer = new TablePrinter();
printer.printTable(raw, appendable);
}
/**
* Returns a transposed view on this table. Example:
* <p>
* <pre>
* | a | 7 | 4 |
* | b | 9 | 2 |
* </pre>
* <p>
* becomes:
* <pre>
* | a | b |
* | 7 | 9 |
* | 4 | 2 |
* </pre>
*
* @return a transposed view of the table
*/
public DataTable transpose() {
if (raw instanceof TransposedRawDataTableView) {
TransposedRawDataTableView transposed = (TransposedRawDataTableView) this.raw;
return transposed.dataTable();
}
return new DataTable(new TransposedRawDataTableView(), tableConverter);
}
/**
* Converts a {@link DataTable} to another type.
* <p>
* There are three ways in which a table might be mapped to a certain type. The table converter considers the
* possible conversions in this order:
* <ol>
* <li>
* Using the whole table to create a single instance.
* </li>
* <li>
* Using individual rows to create a collection of instances. The first row may be used as header.
* </li>
* <li>
* Using individual cells to a create a collection of instances.
* </li>
* </ol>
*/
public interface TableConverter {
/**
* Converts a {@link DataTable} to another type.
* <p>
* Delegates to <code>toList</code>, <code>toLists</code>, <code>toMap</code> and <code>toMaps</code>
* for <code>List<T></code>, <code>List<List<T>></code>, <code>Map<K,V></code> and
* <code>List<Map<K,V>></code> respectively.
*
* @param dataTable the table to convert
* @param type the type to convert to
* @return an object of type
*/
<T> T convert(DataTable dataTable, Type type);
/**
* Converts a {@link DataTable} to another type.
* <p>
* Delegates to <code>toList</code>, <code>toLists</code>, <code>toMap</code> and <code>toMaps</code>
* for <code>List<T></code>, <code>List<List<T>></code>, <code>Map<K,V></code> and
* <code>List<Map<K,V>></code> respectively.
*
* @param dataTable the table to convert
* @param type the type to convert to
* @param transposed whether the table should be transposed first.
* @return an object of type
*/
<T> T convert(DataTable dataTable, Type type, boolean transposed);
/**
* Converts a {@link DataTable} to a list.
* <p>
* A table converter may either map each row or each individual cell to a list element.
* <p>
* For example:
* <p>
* <pre>
* | Annie M. G. Schmidt | 1911-03-20 |
* | Roald Dahl | 1916-09-13 |
*
* convert.toList(table, String.class);
* </pre>
* can become
* <pre>
* [ "Annie M. G. Schmidt", "1911-03-20", "Roald Dahl", "1916-09-13" ]
* </pre>
* <p>
* While:
* <pre>
* convert.toList(table, Author.class);
* </pre>
* <p>
* can become:
* <p>
* <pre>
* [
* Author[ name: Annie M. G. Schmidt, birthDate: 1911-03-20 ],
* Author[ name: Roald Dahl, birthDate: 1916-09-13 ]
* ]
* </pre>
* <p>
* Likewise:
* <p>
* <pre>
* | firstName | lastName | birthDate |
* | Annie M. G. | Schmidt | 1911-03-20 |
* | Roald | Dahl | 1916-09-13 |
*
* convert.toList(table, Authors.class);
* </pre>
* can become:
* <pre>
* [
* Author[ firstName: Annie M. G., lastName: Schmidt, birthDate: 1911-03-20 ],
* Author[ firstName: Roald, lastName: Dahl, birthDate: 1916-09-13 ]
* ]
* </pre>
*
* @param dataTable the table to convert
* @param itemType the list item type to convert to
* @return a list of objects of <code>itemType</code>
*/
<T> List<T> toList(DataTable dataTable, Type itemType);
/**
* Converts a {@link DataTable} to a list of lists.
* <p>
* Each row maps to a list, each table cell a list entry.
* <p>
* For example:
* <p>
* <pre>
* | Annie M. G. Schmidt | 1911-03-20 |
* | Roald Dahl | 1916-09-13 |
*
* convert.toLists(table, String.class);
* </pre>
* can become
* <pre>
* [
* [ "Annie M. G. Schmidt", "1911-03-20" ],
* [ "Roald Dahl", "1916-09-13" ]
* ]
* </pre>
* <p>
*
* @param dataTable the table to convert
* @param itemType the list item type to convert to
* @return a list of lists of objects of <code>itemType</code>
*/
<T> List<List<T>> toLists(DataTable dataTable, Type itemType);
/**
* Converts a {@link DataTable} to a map.
* <p>
* The left column of the table is used to instantiate the key values. The other columns are used to instantiate
* the values.
* <p>
* For example:
* <p>
* <pre>
* | 4a1 | Annie M. G. Schmidt | 1911-03-20 |
* | c92 | Roald Dahl | 1916-09-13 |
*
* convert.toMap(table, Id.class, Authors.class);
* </pre>
* can become:
* <pre>
* {
* Id[ 4a1 ]: Author[ name: Annie M. G. Schmidt, birthDate: 1911-03-20 ],
* Id[ c92 ]: Author[ name: Roald Dahl, birthDate: 1916-09-13 ]
* }
* </pre>
* <p>
* The header cells may be used to map values into the types. When doing so the first header cell may be
* left blank.
* <p>
* For example:
* <p>
* <pre>
* | | firstName | lastName | birthDate |
* | 4a1 | Annie M. G. | Schmidt | 1911-03-20 |
* | c92 | Roald | Dahl | 1916-09-13 |
*
* convert.toMap(table, Id.class, Authors.class);
* </pre>
* can becomes:
* <pre>
* {
* Id[ 4a1 ]: Author[ firstName: Annie M. G., lastName: Schmidt, birthDate: 1911-03-20 ],
* Id[ c92 ]: Author[ firstName: Roald, lastName: Dahl, birthDate: 1916-09-13 ]
* }
* </pre>
*
* @param dataTable the table to convert
* @param keyType the key type to convert to
* @param valueType the value to convert to
* @return a map of <code>keyType</code> <code>valueType</code>
*/
<K, V> Map<K, V> toMap(DataTable dataTable, Type keyType, Type valueType);
/**
* Converts a {@link DataTable} to a list of maps.
* <p>
* Each map represents a row in the table. The map keys are the column headers.
* <p>
* For example:
* <p>
* <pre>
* | firstName | lastName | birthDate |
* | Annie M. G. | Schmidt | 1911-03-20 |
* | Roald | Dahl | 1916-09-13 |
* </pre>
* can become:
* <pre>
* [
* {firstName: Annie M. G., lastName: Schmidt, birthDate: 1911-03-20 }
* {firstName: Roald, lastName: Dahl, birthDate: 1916-09-13 }
* ]
* </pre>
*
* @param dataTable the table to convert
* @param keyType the key type to convert to
* @param valueType the value to convert to
* @return a list of maps of <code>keyType</code> <code>valueType</code>
*/
<K, V> List<Map<K, V>> toMaps(DataTable dataTable, Type keyType, Type valueType);
}
static abstract class AbstractTableConverter implements TableConverter {
AbstractTableConverter() {
}
static Type listItemType(Type type) {
return typeArg(type, List.class, 0);
}
static Type typeArg(Type type, Class<?> wantedRawType, int index) {
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
Type rawType = parameterizedType.getRawType();
if (rawType instanceof Class && wantedRawType.isAssignableFrom((Class) rawType)) {
Type result = parameterizedType.getActualTypeArguments()[index];
if (result instanceof TypeVariable) {
throw new CucumberDataTableException("Generic types must be explicit");
}
return result;
} else {
return null;
}
}
return null;
}
static Type mapKeyType(Type type) {
return typeArg(type, Map.class, 0);
}
static Type mapValueType(Type type) {
return typeArg(type, Map.class, 1);
}
}
static final class NoConverterDefined implements TableConverter {
NoConverterDefined() {
}
@Override
public <T> T convert(DataTable dataTable, Type type) {
return convert(dataTable, type, false);
}
@Override
public <T> T convert(DataTable dataTable, Type type, boolean transposed) {
throw new CucumberDataTableException(String.format("Can't convert DataTable to %s. DataTable was created without a converter", type));
}
@Override
public <T> List<T> toList(DataTable dataTable, Type itemType) {
throw new CucumberDataTableException(String.format("Can't convert DataTable to List<%s>. DataTable was created without a converter", itemType));
}
@Override
public <T> List<List<T>> toLists(DataTable dataTable, Type itemType) {
throw new CucumberDataTableException(String.format("Can't convert DataTable to List<List<%s>>. DataTable was created without a converter", itemType));
}
@Override
public <K, V> Map<K, V> toMap(DataTable dataTable, Type keyType, Type valueType) {
throw new CucumberDataTableException(String.format("Can't convert DataTable to Map<%s,%s>. DataTable was created without a converter", keyType, valueType));
}
@Override
public <K, V> List<Map<K, V>> toMaps(DataTable dataTable, Type keyType, Type valueType) {
throw new CucumberDataTableException(String.format("Can't convert DataTable to List<Map<%s,%s>>. DataTable was created without a converter", keyType, valueType));
}
}
private final class RawDataTableView extends AbstractList<List<String>> implements RandomAccess {
private final int fromRow;
private final int fromColumn;
private final int toColumn;
private final int toRow;
RawDataTableView(int fromRow, int fromColumn, int toColumn, int toRow) {
if (fromRow < 0)
throw new IndexOutOfBoundsException("fromRow: " + fromRow);
if (fromColumn < 0)
throw new IndexOutOfBoundsException("fromColumn: " + fromColumn);
if (toRow > height())
throw new IndexOutOfBoundsException("toRow: " + toRow + ", Height: " + height());
if (toColumn > width())
throw new IndexOutOfBoundsException("toColumn: " + toColumn + ", Width: " + width());
if (fromRow > toRow)
throw new IllegalArgumentException("fromRow(" + fromRow + ") > toRow(" + toRow + ")");
if (fromColumn > toColumn)
throw new IllegalArgumentException("fromColumn(" + fromColumn + ") > toColumn(" + toColumn + ")");
this.fromRow = fromRow;
this.fromColumn = fromColumn;
this.toColumn = toColumn;
this.toRow = toRow;
}
@Override
public List<String> get(final int row) {
rangeCheckRow(row, size());
return new AbstractList<String>() {
@Override
public String get(final int column) {
rangeCheckColumn(column, size());
return raw.get(fromRow + row).get(fromColumn + column);
}
@Override
public int size() {
return toColumn - fromColumn;
}
};
}
@Override
public int size() {
// If there are no columns this is an empty table. An empty table has no rows.
return fromColumn == toColumn ? 0 : toRow - fromRow;
}
}
private final class ListView extends AbstractList<String> {
int width = width();
int height = height();
@Override
public String get(int index) {
rangeCheck(index, size());
return raw.get(index / width).get(index % width);
}
@Override
public int size() {
return height * width;
}
}
private final class ColumnView extends AbstractList<String> implements RandomAccess {
private final int column;
ColumnView(int column) {
rangeCheckColumn(column, width());
this.column = column;
}
@Override
public String get(final int row) {
rangeCheckRow(row, size());
return raw.get(row).get(column);
}
@Override
public int size() {
return height();
}
}
private final class TransposedRawDataTableView extends AbstractList<List<String>> implements RandomAccess {
DataTable dataTable() {
return DataTable.this;
}
@Override
public List<String> get(final int row) {
rangeCheckRow(row, size());
return new AbstractList<String>() {
@Override
public String get(final int column) {
rangeCheckColumn(column, size());
return raw.get(column).get(row);
}
@Override
public int size() {
return height();
}
};
}
@Override
public int size() {
return width();
}
}
} | java/src/main/java/io/cucumber/datatable/DataTable.java | package io.cucumber.datatable;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.RandomAccess;
import static java.util.Collections.emptyList;
import static java.util.Collections.unmodifiableList;
import static java.util.Collections.unmodifiableMap;
/**
* A DataTable is an m-by-n table that contains string values. For example:
* <p>
* <pre>
* | | firstName | lastName | birthDate |
* | 4a1 | Annie M. G. | Schmidt | 1911-03-20 |
* | c92 | Roald | Dahl | 1916-09-13 |
* </pre>
* <p>
* A table can be converted into an objects of an arbitrary type by a {@link TableConverter}.
* <p>
* A DataTable is immutable.
*/
public final class DataTable {
private final List<List<String>> raw;
private final TableConverter tableConverter;
/**
* Creates an empty DataTable.
*
* @return an empty DataTable
*/
public static DataTable emptyDataTable() {
return new DataTable(Collections.<List<String>>emptyList(), new NoConverterDefined());
}
/**
* Creates a new DataTable.
*
* @param raw the underlying table
* @return an new data table containing the raw values
* @throws IllegalArgumentException when the table is not balanced
*/
public static DataTable create(List<List<String>> raw) {
return create(raw, new NoConverterDefined());
}
/**
* Creates a new DataTable.
*
* @param raw the underlying table
* @param tableConverter to transform the table
* @return an new data table containing the raw values
* @throws IllegalArgumentException when the table is not balanced
*/
public static DataTable create(List<List<String>> raw, TableConverter tableConverter) {
return new DataTable(copy(requireBalancedTable(raw)), tableConverter);
}
/**
* Creates a new DataTable.
* <p>
* To improve performance this constructor assumes the provided raw table
* is balanced, immutable and a safe copy.
*
* @param raw the underlying table
* @param tableConverter to transform the table
*/
private DataTable(List<List<String>> raw, TableConverter tableConverter) {
if (raw == null) throw new CucumberDataTableException("cells can not be null");
if (tableConverter == null) throw new CucumberDataTableException("tableConverter can not be null");
this.raw = raw;
this.tableConverter = tableConverter;
}
private static List<List<String>> copy(List<List<String>> balanced) {
List<List<String>> rawCopy = new ArrayList<>(balanced.size());
for (List<String> row : balanced) {
// A table without columns is an empty table and has no rows.
if (row.isEmpty()) {
return emptyList();
}
List<String> rowCopy = new ArrayList<>(row.size());
rowCopy.addAll(row);
rawCopy.add(unmodifiableList(rowCopy));
}
return unmodifiableList(rawCopy);
}
private static List<List<String>> requireBalancedTable(List<List<String>> table) {
int columns = table.isEmpty() ? 0 : table.get(0).size();
for (List<String> row : table) {
if (columns != row.size()) {
throw new IllegalArgumentException(String.format("Table is unbalanced: expected %s column(s) but found %s.", columns, row.size()));
}
}
return table;
}
/**
* Converts the table to a list of maps of strings. The top row is used as keys in the maps,
* and the rows below are used as values.
*
* @return a list of maps.
*/
public List<Map<String, String>> asMaps() {
if (raw.isEmpty()) return emptyList();
List<String> headers = raw.get(0);
List<Map<String, String>> headersAndRows = new ArrayList<>();
for (int i = 1; i < raw.size(); i++) {
List<String> row = raw.get(i);
LinkedHashMap<String, String> headersAndRow = new LinkedHashMap<>();
for (int j = 0; j < headers.size(); j++) {
headersAndRow.put(headers.get(j), row.get(j));
}
headersAndRows.add(unmodifiableMap(headersAndRow));
}
return unmodifiableList(headersAndRows);
}
/**
* Converts the table to a list of maps. The top row is used as keys in the maps,
* and the rows below are used as values.
*
* @param <K> key type
* @param <V> value type
* @param keyType key type
* @param valueType value type
* @return a list of maps.
*/
public <K, V> List<Map<K, V>> asMaps(Type keyType, Type valueType) {
return tableConverter.toMaps(this, keyType, valueType);
}
/**
* Converts the table to a single map. The left column is used as keys, the right column as values.
*
* @param <K> key type
* @param <V> value type
* @param keyType key type
* @param valueType value type
* @return a Map.
*/
public <K, V> Map<K, V> asMap(Type keyType, Type valueType) {
return tableConverter.toMap(this, keyType, valueType);
}
public List<String> asList() {
return new ListView();
}
/**
* Converts the table to a list of list of string.
*
* @return a List of List of objects
*/
public List<List<String>> asLists() {
return cells();
}
/**
* Converts the table to a List of List of scalar.
*
* @param itemType the type of the list items
* @param <T> the type of the list items
* @return a List of List of objects
*/
public <T> List<List<T>> asLists(Type itemType) {
return tableConverter.toLists(this, itemType);
}
/**
* Converts the table to a List.
* <p>
* If {@code itemType} is a scalar type the table is flattened.
* <p>
* Otherwise, the top row is used to name the fields/properties and the remaining
* rows are turned into list items.
*
* @param itemType the type of the list items
* @param <T> the type of the list items
* @return a List of objects
*/
public <T> List<T> asList(Type itemType) {
return tableConverter.toList(this, itemType);
}
public List<List<String>> cells() {
return raw;
}
public DataTable subTable(int fromRow, int fromColumn) {
return subTable(fromRow, fromColumn, height(), width());
}
public DataTable subTable(int fromRow, int fromColumn, int toRow, int toColumn) {
return new DataTable(new RawDataTableView(fromRow, fromColumn, toColumn, toRow), tableConverter);
}
public String cell(int row, int column) {
rangeCheckRow(row, height());
rangeCheckColumn(column, width());
return raw.get(row).get(column);
}
public List<String> row(int row) {
rangeCheckRow(row, height());
return raw.get(row);
}
public DataTable rows(int fromRow) {
return rows(fromRow, height());
}
public DataTable rows(int fromRow, int toRow) {
return subTable(fromRow, 0, toRow, width());
}
public List<String> column(final int column) {
return new ColumnView(column);
}
public DataTable columns(final int fromColumn) {
return columns(fromColumn, width());
}
public DataTable columns(final int fromColumn, final int toColumn) {
return subTable(0, fromColumn, height(), toColumn);
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
print(result);
return result.toString();
}
public void print(StringBuilder appendable) {
TablePrinter printer = new TablePrinter();
printer.printTable(raw, appendable);
}
public void print(Appendable appendable) throws IOException {
TablePrinter printer = new TablePrinter();
printer.printTable(raw, appendable);
}
public DataTable transpose() {
if (raw instanceof TransposedRawDataTableView) {
TransposedRawDataTableView tranposed = (TransposedRawDataTableView) this.raw;
return tranposed.dataTable();
}
return new DataTable(new TransposedRawDataTableView(), tableConverter);
}
public <T> T convert(Type type, boolean transposed) {
return tableConverter.convert(this, type, transposed);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DataTable dataTable = (DataTable) o;
return raw.equals(dataTable.raw);
}
public boolean isEmpty() {
return raw.isEmpty();
}
public int width() {
return raw.isEmpty() ? 0 : raw.get(0).size();
}
public int height() {
return raw.size();
}
@Override
public int hashCode() {
return raw.hashCode();
}
static abstract class AbstractTableConverter implements TableConverter {
AbstractTableConverter() {
}
static Type listItemType(Type type) {
return typeArg(type, List.class, 0);
}
static Type mapKeyType(Type type) {
return typeArg(type, Map.class, 0);
}
static Type mapValueType(Type type) {
return typeArg(type, Map.class, 1);
}
static Type typeArg(Type type, Class<?> wantedRawType, int index) {
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
Type rawType = parameterizedType.getRawType();
if (rawType instanceof Class && wantedRawType.isAssignableFrom((Class) rawType)) {
Type result = parameterizedType.getActualTypeArguments()[index];
if (result instanceof TypeVariable) {
throw new CucumberDataTableException("Generic types must be explicit");
}
return result;
} else {
return null;
}
}
return null;
}
}
static final class NoConverterDefined implements TableConverter {
NoConverterDefined() {
}
@Override
public <T> T convert(DataTable dataTable, Type type) {
return convert(dataTable, type, false);
}
@Override
public <T> T convert(DataTable dataTable, Type type, boolean transposed) {
throw new CucumberDataTableException(String.format("Can't convert DataTable to %s. DataTable was created without a converter", type));
}
@Override
public <T> List<T> toList(DataTable dataTable, Type itemType) {
throw new CucumberDataTableException(String.format("Can't convert DataTable to List<%s>. DataTable was created without a converter", itemType));
}
@Override
public <T> List<List<T>> toLists(DataTable dataTable, Type itemType) {
throw new CucumberDataTableException(String.format("Can't convert DataTable to List<List<%s>>. DataTable was created without a converter", itemType));
}
@Override
public <K, V> Map<K, V> toMap(DataTable dataTable, Type keyType, Type valueType) {
throw new CucumberDataTableException(String.format("Can't convert DataTable to Map<%s,%s>. DataTable was created without a converter", keyType, valueType));
}
@Override
public <K, V> List<Map<K, V>> toMaps(DataTable dataTable, Type keyType, Type valueType) {
throw new CucumberDataTableException(String.format("Can't convert DataTable to List<Map<%s,%s>>. DataTable was created without a converter", keyType, valueType));
}
}
/**
* Converts a {@link DataTable} to another type.
* <p>
* There are three ways in which a table might be mapped to a certain type. The table converter considers the
* possible conversions in this order:
* <ol>
* <li>
* Using the whole table to create a single instance.
* </li>
* <li>
* Using individual rows to create a collection of instances. The first row may be used as header.
* </li>
* <li>
* Using individual cells to a create a collection of instances.
* </li>
* </ol>
*/
public interface TableConverter {
/**
* Converts a {@link DataTable} to another type.
* <p>
* Delegates to <code>toList</code>, <code>toLists</code>, <code>toMap</code> and <code>toMaps</code>
* for <code>List<T></code>, <code>List<List<T>></code>, <code>Map<K,V></code> and
* <code>List<Map<K,V>></code> respectively.
*
* @param dataTable the table to convert
* @param type the type to convert to
* @return an object of type
*/
<T> T convert(DataTable dataTable, Type type);
/**
* Converts a {@link DataTable} to another type.
* <p>
* Delegates to <code>toList</code>, <code>toLists</code>, <code>toMap</code> and <code>toMaps</code>
* for <code>List<T></code>, <code>List<List<T>></code>, <code>Map<K,V></code> and
* <code>List<Map<K,V>></code> respectively.
*
* @param dataTable the table to convert
* @param type the type to convert to
* @param transposed whether the table should be transposed first.
* @return an object of type
*/
<T> T convert(DataTable dataTable, Type type, boolean transposed);
/**
* Converts a {@link DataTable} to a list.
* <p>
* A table converter may either map each row or each individual cell to a list element.
* <p>
* For example:
* <p>
* <pre>
* | Annie M. G. Schmidt | 1911-03-20 |
* | Roald Dahl | 1916-09-13 |
*
* convert.toList(table, String.class);
* </pre>
* can become
* <pre>
* [ "Annie M. G. Schmidt", "1911-03-20", "Roald Dahl", "1916-09-13" ]
* </pre>
* <p>
* While:
* <pre>
* convert.toList(table, Author.class);
* </pre>
* <p>
* can become:
* <p>
* <pre>
* [
* Author[ name: Annie M. G. Schmidt, birthDate: 1911-03-20 ],
* Author[ name: Roald Dahl, birthDate: 1916-09-13 ]
* ]
* </pre>
* <p>
* Likewise:
* <p>
* <pre>
* | firstName | lastName | birthDate |
* | Annie M. G. | Schmidt | 1911-03-20 |
* | Roald | Dahl | 1916-09-13 |
*
* convert.toList(table, Authors.class);
* </pre>
* can become:
* <pre>
* [
* Author[ firstName: Annie M. G., lastName: Schmidt, birthDate: 1911-03-20 ],
* Author[ firstName: Roald, lastName: Dahl, birthDate: 1916-09-13 ]
* ]
* </pre>
*
* @param dataTable the table to convert
* @param itemType the list item type to convert to
* @return a list of objects of <code>itemType</code>
*/
<T> List<T> toList(DataTable dataTable, Type itemType);
/**
* Converts a {@link DataTable} to a list of lists.
* <p>
* Each row maps to a list, each table cell a list entry.
* <p>
* For example:
* <p>
* <pre>
* | Annie M. G. Schmidt | 1911-03-20 |
* | Roald Dahl | 1916-09-13 |
*
* convert.toLists(table, String.class);
* </pre>
* can become
* <pre>
* [
* [ "Annie M. G. Schmidt", "1911-03-20" ],
* [ "Roald Dahl", "1916-09-13" ]
* ]
* </pre>
* <p>
*
* @param dataTable the table to convert
* @param itemType the list item type to convert to
* @return a list of lists of objects of <code>itemType</code>
*/
<T> List<List<T>> toLists(DataTable dataTable, Type itemType);
/**
* Converts a {@link DataTable} to a map.
* <p>
* The left column of the table is used to instantiate the key values. The other columns are used to instantiate
* the values.
* <p>
* For example:
* <p>
* <pre>
* | 4a1 | Annie M. G. Schmidt | 1911-03-20 |
* | c92 | Roald Dahl | 1916-09-13 |
*
* convert.toMap(table, Id.class, Authors.class);
* </pre>
* can become:
* <pre>
* {
* Id[ 4a1 ]: Author[ name: Annie M. G. Schmidt, birthDate: 1911-03-20 ],
* Id[ c92 ]: Author[ name: Roald Dahl, birthDate: 1916-09-13 ]
* }
* </pre>
* <p>
* The header cells may be used to map values into the types. When doing so the first header cell may be
* left blank.
* <p>
* For example:
* <p>
* <pre>
* | | firstName | lastName | birthDate |
* | 4a1 | Annie M. G. | Schmidt | 1911-03-20 |
* | c92 | Roald | Dahl | 1916-09-13 |
*
* convert.toMap(table, Id.class, Authors.class);
* </pre>
* can becomes:
* <pre>
* {
* Id[ 4a1 ]: Author[ firstName: Annie M. G., lastName: Schmidt, birthDate: 1911-03-20 ],
* Id[ c92 ]: Author[ firstName: Roald, lastName: Dahl, birthDate: 1916-09-13 ]
* }
* </pre>
*
* @param dataTable the table to convert
* @param keyType the key type to convert to
* @param valueType the value to convert to
* @return a map of <code>keyType</code> <code>valueType</code>
*/
<K, V> Map<K, V> toMap(DataTable dataTable, Type keyType, Type valueType);
/**
* Converts a {@link DataTable} to a list of maps.
* <p>
* Each map represents a row in the table. The map keys are the column headers.
* <p>
* For example:
* <p>
* <pre>
* | firstName | lastName | birthDate |
* | Annie M. G. | Schmidt | 1911-03-20 |
* | Roald | Dahl | 1916-09-13 |
* </pre>
* can become:
* <pre>
* [
* {firstName: Annie M. G., lastName: Schmidt, birthDate: 1911-03-20 }
* {firstName: Roald, lastName: Dahl, birthDate: 1916-09-13 }
* ]
* </pre>
*
* @param dataTable the table to convert
* @param keyType the key type to convert to
* @param valueType the value to convert to
* @return a list of maps of <code>keyType</code> <code>valueType</code>
*/
<K, V> List<Map<K, V>> toMaps(DataTable dataTable, Type keyType, Type valueType);
}
private final class RawDataTableView extends AbstractList<List<String>> implements RandomAccess {
private final int fromRow;
private final int fromColumn;
private final int toColumn;
private final int toRow;
RawDataTableView(int fromRow, int fromColumn, int toColumn, int toRow) {
if (fromRow < 0)
throw new IndexOutOfBoundsException("fromRow: " + fromRow);
if (fromColumn < 0)
throw new IndexOutOfBoundsException("fromColumn: " + fromColumn);
if (toRow > height())
throw new IndexOutOfBoundsException("toRow: " + toRow + ", Height: " + height());
if (toColumn > width())
throw new IndexOutOfBoundsException("toColumn: " + toColumn + ", Width: " + width());
if (fromRow > toRow)
throw new IllegalArgumentException("fromRow(" + fromRow + ") > toRow(" + toRow + ")");
if (fromColumn > toColumn)
throw new IllegalArgumentException("fromColumn(" + fromColumn + ") > toColumn(" + toColumn + ")");
this.fromRow = fromRow;
this.fromColumn = fromColumn;
this.toColumn = toColumn;
this.toRow = toRow;
}
@Override
public List<String> get(final int row) {
rangeCheckRow(row, size());
return new AbstractList<String>() {
@Override
public String get(final int column) {
rangeCheckColumn(column, size());
return raw.get(fromRow + row).get(fromColumn + column);
}
@Override
public int size() {
return toColumn - fromColumn;
}
};
}
@Override
public int size() {
// If there are no columns this is an empty table. An empty table has no rows.
return fromColumn == toColumn ? 0 : toRow - fromRow;
}
}
private final class ListView extends AbstractList<String> {
int width = width();
int height = height();
@Override
public String get(int index) {
rangeCheck(index, size());
return raw.get(index / width).get(index % width);
}
@Override
public int size() {
return height * width;
}
}
private final class ColumnView extends AbstractList<String> implements RandomAccess {
private final int column;
ColumnView(int column) {
rangeCheckColumn(column, width());
this.column = column;
}
@Override
public String get(final int row) {
rangeCheckRow(row, size());
return raw.get(row).get(column);
}
@Override
public int size() {
return height();
}
}
private final class TransposedRawDataTableView extends AbstractList<List<String>> implements RandomAccess {
@Override
public List<String> get(final int row) {
rangeCheckRow(row, size());
return new AbstractList<String>() {
@Override
public String get(final int column) {
rangeCheckColumn(column, size());
return raw.get(column).get(row);
}
@Override
public int size() {
return height();
}
};
}
@Override
public int size() {
return width();
}
DataTable dataTable() {
return DataTable.this;
}
}
private static void rangeCheck(int index, int size) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("index: " + index + ", Size: " + size);
}
private static void rangeCheckRow(int row, int height) {
if (row < 0 || row >= height)
throw new IndexOutOfBoundsException("row: " + row + ", Height: " + height);
}
private static void rangeCheckColumn(int column, int width) {
if (column < 0 || column >= width)
throw new IndexOutOfBoundsException("column: " + column + ", Width: " + width);
}
} | Document data table
| java/src/main/java/io/cucumber/datatable/DataTable.java | Document data table |
|
Java | mit | 2f46e8f0ea11a62c1df3d3da5874b1868eb845f9 | 0 | nallar/TickThreading | package nallar.tickthreading.minecraft;
import java.util.ArrayList;
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.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.Lock;
import nallar.collections.ConcurrentIterableArrayList;
import nallar.collections.ConcurrentUnsafeIterableArrayList;
import nallar.collections.ContainedRemoveSet;
import nallar.tickthreading.Log;
import nallar.tickthreading.minecraft.commands.TPSCommand;
import nallar.tickthreading.minecraft.tickregion.EntityTickRegion;
import nallar.tickthreading.minecraft.tickregion.TickRegion;
import nallar.tickthreading.minecraft.tickregion.TileEntityTickRegion;
import nallar.tickthreading.util.CollectionsUtil;
import nallar.tickthreading.util.MappingUtil;
import nallar.tickthreading.util.TableFormatter;
import nallar.unsafe.UnsafeUtil;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityCreature;
import net.minecraft.entity.IProjectile;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.server.MinecraftServer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.WorldServer;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.gen.ChunkProviderServer;
public final class TickManager {
private static final byte lockXPlus = 1 << 1;
private static final byte lockXMinus = 1 << 2;
private static final byte lockZPlus = 1 << 3;
private static final byte lockZMinus = 1 << 4;
public static final int regionSize = TickThreading.instance.regionSize;
public static final int regionSizePower = 31 - Integer.numberOfLeadingZeros(regionSize);
public boolean profilingEnabled = false;
private double averageTickLength = 0;
private long lastTickLength = 0;
private long lastStartTime = 0;
private static final int shuffleInterval = 3600;
private int shuffleCount;
private final boolean waitForCompletion;
private final WorldServer world;
public final ConcurrentUnsafeIterableArrayList<TileEntity> tileEntityList = new ConcurrentUnsafeIterableArrayList<TileEntity>();
public final ConcurrentUnsafeIterableArrayList<Entity> entityList = new ConcurrentUnsafeIterableArrayList<Entity>();
public Object tileEntityLock = new Object();
public Object entityLock = new Object();
private final Map<Integer, TileEntityTickRegion> tileEntityCallables = new HashMap<Integer, TileEntityTickRegion>();
private final Map<Integer, EntityTickRegion> entityCallables = new HashMap<Integer, EntityTickRegion>();
private final ConcurrentIterableArrayList<TickRegion> tickRegions = new ConcurrentIterableArrayList<TickRegion>();
private final ThreadManager threadManager;
private final Map<Class<?>, Integer> entityClassToCountMap = new ConcurrentHashMap<Class<?>, Integer>();
private final ConcurrentLinkedQueue<TickRegion> removalQueue = new ConcurrentLinkedQueue<TickRegion>();
public TickManager(WorldServer world, int threads, boolean waitForCompletion) {
this.waitForCompletion = waitForCompletion;
threadManager = new ThreadManager(threads, "Entities in " + Log.name(world));
this.world = world;
shuffleCount = world.rand.nextInt(shuffleInterval);
}
public TileEntityTickRegion getTileEntityRegion(int hashCode) {
return tileEntityCallables.get(hashCode);
}
@SuppressWarnings ("NumericCastThatLosesPrecision")
private TileEntityTickRegion getOrCreateRegion(TileEntity tileEntity) {
int regionX = tileEntity.xCoord >> regionSizePower;
int regionZ = tileEntity.zCoord >> regionSizePower;
int hashCode = getHashCodeFromRegionCoords(regionX, regionZ);
TileEntityTickRegion callable = tileEntityCallables.get(hashCode);
if (callable == null) {
synchronized (tickRegions) {
callable = tileEntityCallables.get(hashCode);
if (callable == null) {
callable = new TileEntityTickRegion(world, this, regionX, regionZ);
tileEntityCallables.put(hashCode, callable);
tickRegions.add(callable);
}
}
}
return callable;
}
public EntityTickRegion getEntityRegion(int hashCode) {
return entityCallables.get(hashCode);
}
@SuppressWarnings ("NumericCastThatLosesPrecision")
private EntityTickRegion getOrCreateRegion(Entity entity) {
int regionX = (entity.chunkCoordX << 4) >> regionSizePower;
int regionZ = (entity.chunkCoordZ << 4) >> regionSizePower;
int hashCode = getHashCodeFromRegionCoords(regionX, regionZ);
EntityTickRegion callable = entityCallables.get(hashCode);
if (callable == null) {
synchronized (tickRegions) {
callable = entityCallables.get(hashCode);
if (callable == null) {
callable = new EntityTickRegion(world, this, regionX, regionZ);
entityCallables.put(hashCode, callable);
tickRegions.add(callable);
}
}
}
return callable;
}
public static int getHashCode(TileEntity tileEntity) {
return getHashCode(tileEntity.xCoord, tileEntity.zCoord);
}
public static int getHashCode(Entity entity) {
return getHashCode(entity.chunkCoordX << 4, entity.chunkCoordZ << 4);
}
public static int getHashCode(int x, int z) {
return getHashCodeFromRegionCoords(x >> regionSizePower, z >> regionSizePower);
}
public static int getHashCodeFromRegionCoords(int x, int z) {
return x + (z << 16);
}
public void queueForRemoval(TickRegion tickRegion) {
removalQueue.add(tickRegion);
}
private void processChanges() {
TickRegion tickRegion;
while ((tickRegion = removalQueue.poll()) != null) {
if (tickRegion.isEmpty()) {
synchronized (tickRegions) {
if ((tickRegion instanceof EntityTickRegion ? entityCallables.remove(tickRegion.hashCode) : tileEntityCallables.remove(tickRegion.hashCode)) == tickRegion) {
tickRegions.remove(tickRegion);
}
}
}
}
}
public boolean add(TileEntity tileEntity, boolean newEntity) {
TileEntityTickRegion tileEntityTickRegion = getOrCreateRegion(tileEntity);
if (tileEntityTickRegion.add(tileEntity)) {
tileEntity.tickRegion = tileEntityTickRegion;
if (newEntity) {
synchronized (tileEntityLock) {
tileEntityList.add(tileEntity);
}
}
return true;
}
return false;
}
public boolean add(Entity entity, boolean newEntity) {
EntityTickRegion entityTickRegion = getOrCreateRegion(entity);
if (entityTickRegion.add(entity)) {
entity.tickRegion = entityTickRegion;
if (newEntity) {
synchronized (entityLock) {
entityList.add(entity);
}
synchronized (entityClassToCountMap) {
Class entityClass = entity.getClass();
Integer count = entityClassToCountMap.get(entityClass);
if (count == null) {
count = 0;
}
entityClassToCountMap.put(entityClass, count + 1);
}
}
return true;
}
return false;
}
public void batchRemoveEntities(HashSet<Entity> entities) {
entities = safeCopyClear(entities);
if (entities == null) {
return;
}
synchronized (entityLock) {
entityList.removeAll(entities);
}
ChunkProviderServer chunkProviderServer = world.theChunkProviderServer;
for (Entity entity : entities) {
if (entity == null) {
continue;
}
int x = entity.chunkCoordX;
int z = entity.chunkCoordZ;
if (entity.addedToChunk) {
Chunk chunk = chunkProviderServer.getChunkIfExists(x, z);
if (chunk != null) {
chunk.removeEntity(entity);
}
}
world.releaseEntitySkin(entity);
EntityTickRegion tickRegion = entity.tickRegion;
if (tickRegion != null) {
tickRegion.remove(entity);
entity.tickRegion = null;
Class entityClass = entity.getClass();
synchronized (entityClassToCountMap) {
Integer count = entityClassToCountMap.get(entityClass);
if (count == null) {
throw new IllegalStateException("Removed an entity which should not have been in the entityList");
}
entityClassToCountMap.put(entityClass, count - 1);
}
}
}
}
public void batchRemoveTileEntities(HashSet<TileEntity> tileEntities) {
tileEntities = safeCopyClear(tileEntities);
if (tileEntities == null) {
return;
}
for (TileEntity tileEntity : tileEntities) {
TileEntityTickRegion tickRegion = tileEntity.tickRegion;
if (tickRegion != null) {
tickRegion.remove(tileEntity);
tileEntity.tickRegion = null;
tileEntity.onChunkUnload();
}
unlock(tileEntity);
}
synchronized (tileEntityLock) {
tileEntityList.removeAll(tileEntities);
}
}
private static <T> HashSet<T> safeCopyClear(HashSet<T> c) {
synchronized (c) {
if (c.isEmpty()) {
return null;
}
HashSet<T> copy = new HashSet<T>(c);
c.clear();
return copy;
}
}
public void remove(TileEntity tileEntity) {
TileEntityTickRegion tileEntityTickRegion = tileEntity.tickRegion;
if (tileEntityTickRegion == null) {
tileEntityTickRegion = getOrCreateRegion(tileEntity);
}
tileEntityTickRegion.remove(tileEntity);
removed(tileEntity);
}
public void remove(Entity entity) {
EntityTickRegion entityTickRegion = entity.tickRegion;
if (entityTickRegion == null) {
entityTickRegion = getOrCreateRegion(entity);
}
entityTickRegion.remove(entity);
removed(entity);
}
public void removed(TileEntity tileEntity) {
tileEntity.tickRegion = null;
synchronized (tileEntityLock) {
tileEntityList.remove(tileEntity);
}
unlock(tileEntity);
}
public void removed(Entity entity) {
boolean removed;
entity.tickRegion = null;
synchronized (entityLock) {
removed = entityList.remove(entity);
}
if (removed) {
Class entityClass = entity.getClass();
synchronized (entityClassToCountMap) {
Integer count = entityClassToCountMap.get(entityClass);
if (count == null) {
throw new IllegalStateException("Removed an entity which should not have been in the entityList");
}
entityClassToCountMap.put(entityClass, count - 1);
}
}
}
/* Oh, Java.
Explicit MONITORENTER/EXIT should really be part of the language, there are just some cases like this where synchronized blocks get too messy,
and performance is bad if using other locks.
.lock/unlock calls here are replaced with MONITORENTER/EXIT.
*/
void unlock(TileEntity tE) {
Lock lock = tE.lockManagementLock;
lock.lock();
byte locks = tE.usedLocks;
boolean xM = ((locks & lockXMinus) != 0) || tE.xMinusLock != null;
boolean xP = ((locks & lockXPlus) != 0) || tE.xPlusLock != null;
boolean zM = ((locks & lockZMinus) != 0) || tE.zMinusLock != null;
boolean zP = ((locks & lockZPlus) != 0) || tE.zPlusLock != null;
tE.xPlusLock = null;
tE.xMinusLock = null;
tE.zPlusLock = null;
tE.zMinusLock = null;
tE.usedLocks = 0;
if (tE.thisLock == null) {
lock.unlock();
return;
}
int xPos = tE.lastTTX;
int yPos = tE.lastTTY;
int zPos = tE.lastTTZ;
TileEntity xMTE = xM ? world.getTEWithoutLoad(xPos - 1, yPos, zPos) : null;
TileEntity xPTE = xP ? world.getTEWithoutLoad(xPos + 1, yPos, zPos) : null;
TileEntity zMTE = zM ? world.getTEWithoutLoad(xPos, yPos, zPos - 1) : null;
TileEntity zPTE = zP ? world.getTEWithoutLoad(xPos, yPos, zPos + 1) : null;
if (xMTE == null) {
xM = false;
}
if (xPTE == null) {
xP = false;
}
if (zMTE == null) {
zM = false;
}
if (zPTE == null) {
zP = false;
}
lock.unlock();
if (!(xM || xP || zM || zP)) {
return;
}
if (xP) {
xPTE.lockManagementLock.lock();
}
if (zP) {
zPTE.lockManagementLock.lock();
}
lock.lock();
if (zM) {
zMTE.lockManagementLock.lock();
}
if (xM) {
xMTE.lockManagementLock.lock();
}
if (xM) {
xMTE.usedLocks &= ~lockXPlus;
xMTE.xPlusLock = null;
}
if (xP) {
xPTE.usedLocks &= ~lockXMinus;
xPTE.xMinusLock = null;
}
if (zM) {
zMTE.usedLocks &= ~lockZPlus;
zMTE.zPlusLock = null;
}
if (zP) {
zPTE.usedLocks &= ~lockZMinus;
zPTE.zMinusLock = null;
}
if (xM) {
xMTE.lockManagementLock.unlock();
}
if (zM) {
zMTE.lockManagementLock.unlock();
}
lock.unlock();
if (zP) {
zPTE.lockManagementLock.unlock();
}
if (xP) {
xPTE.lockManagementLock.unlock();
}
}
/*
.lock/unlock calls here are replaced with MONITORENTER/EXIT.
*/
public final void lock(TileEntity tE) {
unlock(tE);
Lock lock = tE.lockManagementLock;
lock.lock();
int maxPosition = (regionSize / 2) - 1;
int xPos = tE.xCoord;
int yPos = tE.yCoord;
int zPos = tE.zCoord;
tE.lastTTX = xPos;
tE.lastTTY = yPos;
tE.lastTTZ = zPos;
int relativeXPos = (xPos % regionSize) / 2;
int relativeZPos = (zPos % regionSize) / 2;
boolean onMinusX = relativeXPos == 0;
boolean onMinusZ = relativeZPos == 0;
boolean onPlusX = relativeXPos == maxPosition;
boolean onPlusZ = relativeZPos == maxPosition;
boolean xM = onMinusX || onMinusZ || onPlusZ;
boolean xP = onPlusX || onMinusZ || onPlusZ;
boolean zM = onMinusZ || onMinusX || onPlusX;
boolean zP = onPlusZ || onMinusX || onPlusX;
TileEntity xMTE = xM ? world.getTEWithoutLoad(xPos - 1, yPos, zPos) : null;
TileEntity xPTE = xP ? world.getTEWithoutLoad(xPos + 1, yPos, zPos) : null;
TileEntity zMTE = zM ? world.getTEWithoutLoad(xPos, yPos, zPos - 1) : null;
TileEntity zPTE = zP ? world.getTEWithoutLoad(xPos, yPos, zPos + 1) : null;
if (xMTE == null) {
xM = false;
}
if (xPTE == null) {
xP = false;
}
if (zMTE == null) {
zM = false;
}
if (zPTE == null) {
zP = false;
}
lock.unlock();
if (!(xM || xP || zM || zP)) {
return;
}
Lock thisLock = tE.thisLock;
if (xP) {
xPTE.lockManagementLock.lock();
}
if (zP) {
zPTE.lockManagementLock.lock();
}
lock.lock();
if (zM) {
zMTE.lockManagementLock.lock();
}
if (xM) {
xMTE.lockManagementLock.lock();
}
byte usedLocks = tE.usedLocks;
if (xM) {
Lock otherLock = xMTE.thisLock;
if (otherLock != null) {
xMTE.usedLocks |= lockXPlus;
tE.xMinusLock = otherLock;
}
if (thisLock != null) {
usedLocks |= lockXMinus;
xMTE.xPlusLock = thisLock;
}
}
if (xP) {
Lock otherLock = xPTE.thisLock;
if (otherLock != null) {
xPTE.usedLocks |= lockXMinus;
tE.xPlusLock = otherLock;
}
if (thisLock != null) {
usedLocks |= lockXPlus;
xPTE.xMinusLock = thisLock;
}
}
if (zM) {
Lock otherLock = zMTE.thisLock;
if (otherLock != null) {
zMTE.usedLocks |= lockZPlus;
tE.zMinusLock = otherLock;
}
if (thisLock != null) {
usedLocks |= lockZMinus;
zMTE.zPlusLock = thisLock;
}
}
if (zP) {
Lock otherLock = zPTE.thisLock;
if (otherLock != null) {
zPTE.usedLocks |= lockZMinus;
tE.zPlusLock = otherLock;
}
if (thisLock != null) {
usedLocks |= lockZPlus;
zPTE.zMinusLock = thisLock;
}
}
tE.usedLocks = usedLocks;
if (xM) {
xMTE.lockManagementLock.unlock();
}
if (zM) {
zMTE.lockManagementLock.unlock();
}
lock.unlock();
if (zP) {
zPTE.lockManagementLock.unlock();
}
if (xP) {
xPTE.lockManagementLock.unlock();
}
}
public void doTick() {
boolean previousProfiling = world.theProfiler.profilingEnabled;
lastStartTime = System.nanoTime();
threadManager.waitForCompletion();
if (previousProfiling) {
world.theProfiler.profilingEnabled = false;
}
threadManager.runList(tickRegions);
if (previousProfiling || waitForCompletion) {
postTick();
}
if (previousProfiling) {
world.theProfiler.profilingEnabled = true;
}
}
public void tickEnd() {
if (!waitForCompletion) {
postTick();
}
}
private void postTick() {
lastTickLength = (threadManager.waitForCompletion() - lastStartTime);
averageTickLength = ((averageTickLength * 127) + lastTickLength) / 128;
if (!removalQueue.isEmpty()) {
threadManager.run(new Runnable() {
@Override
public void run() {
processChanges();
if (shuffleCount++ % shuffleInterval == 0) {
synchronized (tickRegions) {
Collections.shuffle(tickRegions);
if (tickRegions.removeAll(Collections.singleton(null))) {
Log.severe("Something broke, tickRegions for " + world.getName() + " contained null!");
}
}
MinecraftServer.runQueue.add(new FixDiscrepanciesTask());
}
}
});
}
}
public void unload() {
threadManager.stop();
synchronized (tickRegions) {
for (TickRegion tickRegion : tickRegions) {
tickRegion.die();
}
tickRegions.clear();
}
entityList.clear();
entityClassToCountMap.clear();
UnsafeUtil.clean(this);
}
public void fixDiscrepancies(StringBuilder sb) {
long startTime = System.nanoTime();
int fixed = 0;
int missingEntities = 0;
int missingTiles = 0;
int duplicateEntities = 0;
int duplicateTiles = 0;
int invalidTiles = 0;
int unloadedEntities = 0;
int unloadedTiles = 0;
ChunkProviderServer chunkProviderServer = world.theChunkProviderServer;
{
Set<Entity> contained = new HashSet<Entity>();
Set<Entity> toRemove = new ContainedRemoveSet<Entity>();
List<Entity> unloaded = new ArrayList<Entity>();
synchronized (entityLock) {
for (Entity e : entityList) {
if (add(e, false)) {
missingEntities++;
fixed++;
} else if (!contained.add(e)) {
toRemove.add(e);
duplicateEntities++;
fixed++;
} else if (e instanceof IProjectile || e instanceof EntityCreature || e instanceof EntityMob) {
synchronized (e) {
Chunk chunk = world.getChunkIfExists(e.chunkCoordX, e.chunkCoordZ);
if (chunk == null || !chunk.entityLists[e.chunkCoordY].contains(e)) {
unloaded.add(e);
unloadedEntities++;
}
}
}
}
for (Entity e : unloaded) {
remove(e);
}
entityList.removeAll(toRemove);
}
}
{
Set<TileEntity> contained = new HashSet<TileEntity>();
Set<TileEntity> toRemove = new ContainedRemoveSet<TileEntity>();
List<TileEntity> copy = new ArrayList<TileEntity>(tileEntityList.size());
synchronized (tileEntityLock) {
for (TileEntity te : tileEntityList) {
copy.add(te);
if (add(te, false)) {
missingTiles++;
fixed++;
}
if (!contained.add(te)) {
toRemove.add(te);
duplicateTiles++;
fixed++;
}
}
tileEntityList.removeAll(toRemove);
}
for (TileEntity te : copy) {
Chunk chunk;
boolean invalid = te.isInvalid();
if (te.yCoord < 0 || te.yCoord > 255) {
sb.append("TileEntity ").append(Log.toString(te)).append(" has an invalid y coordinate.\n");
invalid = true;
}
if (invalid || (chunk = chunkProviderServer.getChunkIfExists(te.xCoord >> 4, te.zCoord >> 4)) == null || chunk.getChunkBlockTileEntity(te.xCoord & 15, te.yCoord, te.zCoord & 15) != te) {
if (invalid) {
invalidTiles++;
sb.append("Removed ").append(Log.toString(te)).append(" as it is invalid.\n");
} else {
unloadedTiles++;
te.invalidate();
sb.append("Removed ").append(Log.toString(te)).append(" as it should have been unloaded.\n");
}
fixed++;
remove(te);
}
}
}
int totalSize = tickRegions.size();
int tESize = tileEntityCallables.size();
int eSize = entityCallables.size();
if (eSize + tESize != totalSize) {
sb.append("TickRegion list size mismatch, total: ").append(totalSize).append(", te: ").append(tESize).append(", e: ").append(eSize).append(", combined: ").append(tESize + eSize);
if (fixed != 0) {
sb.append('\n');
}
}
if (fixed != 0) {
sb.append("Found and fixed ").append(fixed).append(" discrepancies in tile/entity lists in ").append(Log.name(world))
.append("\ntiles - invalid: ").append(invalidTiles).append(", missing: ").append(missingTiles).append(", duplicate: ").append(duplicateTiles).append(", unloaded: ").append(unloadedTiles)
.append("\nentities - missing: ").append(missingEntities).append(", duplicate: ").append(duplicateEntities).append(", unloaded: ").append(unloadedEntities)
.append("\nTook ").append((System.nanoTime() - startTime) / 1000000l).append("ms");
}
}
public void recordStats(final TPSCommand.StatsHolder statsHolder) {
statsHolder.entities += entityList.size();
statsHolder.tileEntities += tileEntityList.size();
statsHolder.chunks += world.theChunkProviderServer.getLoadedChunkCount();
}
public void writeStats(TableFormatter tf, final TPSCommand.StatsHolder statsHolder) {
long timeTotal = 0;
double time = Double.NaN;
try {
long[] tickTimes = MinecraftServer.getServer().getTickTimes(world);
for (long tick : tickTimes) {
timeTotal += tick;
}
time = (timeTotal) / (double) tickTimes.length;
if (time == 0) {
time = 0.1;
}
} catch (NullPointerException ignored) {
}
int entities = entityList.size();
statsHolder.entities += entities;
int tileEntities = tileEntityList.size();
statsHolder.tileEntities += tileEntities;
int chunks = world.theChunkProviderServer.getLoadedChunkCount();
statsHolder.chunks += chunks;
tf
.row(Log.name(world))
.row(entities)
.row(tileEntities)
.row(chunks)
.row(world.playerEntities.size())
.row(TableFormatter.formatDoubleWithPrecision((time * 100f) / MinecraftServer.getTargetTickTime(), 2) + '%');
}
public TableFormatter writeDetailedStats(TableFormatter tf) {
@SuppressWarnings ("MismatchedQueryAndUpdateOfStringBuilder")
StringBuilder stats = tf.sb;
stats.append("World: ").append(Log.name(world)).append('\n');
stats.append("---- Slowest tick regions ----").append('\n');
// TODO: Rewrite this
float averageAverageTickTime = 0;
float maxTickTime = 0;
SortedMap<Float, TickRegion> sortedTickCallables = new TreeMap<Float, TickRegion>();
synchronized (tickRegions) {
for (TickRegion tickRegion : tickRegions) {
float averageTickTime = tickRegion.getAverageTickTime();
averageAverageTickTime += averageTickTime;
sortedTickCallables.put(averageTickTime, tickRegion);
if (averageTickTime > maxTickTime) {
maxTickTime = averageTickTime;
}
}
Collection<TickRegion> var = sortedTickCallables.values();
TickRegion[] sortedTickCallablesArray = var.toArray(new TickRegion[var.size()]);
tf
.heading("")
.heading("X")
.heading("Z")
.heading("N")
.heading("Time");
for (int i = sortedTickCallablesArray.length - 1; i >= sortedTickCallablesArray.length - 7; i--) {
if (i >= 0 && sortedTickCallablesArray[i].getAverageTickTime() > 0.2) {
sortedTickCallablesArray[i].writeStats(tf);
}
}
tf.finishTable();
averageAverageTickTime /= tickRegions.size();
stats.append("\n---- World stats ----");
stats.append('\n').append(world.getChunkProvider().makeString());
stats.append("\nAverage tick time: ").append(averageAverageTickTime).append("ms");
stats.append("\nMax tick time: ").append(maxTickTime).append("ms");
stats.append("\nEffective tick time: ").append(lastTickLength / 1000000f).append("ms");
stats.append("\nAverage effective tick time: ").append((float) averageTickLength / 1000000).append("ms");
stats.append("\nGlobal TPS: ").append(TableFormatter.formatDoubleWithPrecision(MinecraftServer.getTPS(), 2));
}
return tf;
}
public TableFormatter writeEntityStats(TableFormatter tf) {
tf
.heading("Main")
.heading("Map")
.heading("Region")
.heading("Player");
tf
.row(entityList.size())
.row(getTotalEntityCountFromMap())
.row(getTotalEntityCountFromRegions())
.row(getEntityCount(EntityPlayer.class));
tf.finishTable();
return tf;
}
private int getTotalEntityCountFromRegions() {
int count = 0;
for (EntityTickRegion entityTickRegion : entityCallables.values()) {
count += entityTickRegion.size();
}
return count;
}
private int getTotalEntityCountFromMap() {
int count = 0;
for (Map.Entry<Class<?>, Integer> entry : entityClassToCountMap.entrySet()) {
count += entry.getValue();
}
return count;
}
public int getEntityCount(Class<?> clazz) {
int count = 0;
for (Map.Entry<Class<?>, Integer> entry : entityClassToCountMap.entrySet()) {
if (clazz.isAssignableFrom(entry.getKey())) {
count += entry.getValue();
}
}
return count;
}
public TableFormatter writeRegionDetails(final TableFormatter tf, final int hashCode) {
int x = 0;
int z = 0;
TileEntityTickRegion tileEntityTickRegion = getTileEntityRegion(hashCode);
if (tileEntityTickRegion != null) {
tileEntityTickRegion.dump(tf);
x = tileEntityTickRegion.regionX;
z = tileEntityTickRegion.regionZ;
}
EntityTickRegion entityTickRegion = getEntityRegion(hashCode);
if (entityTickRegion != null) {
entityTickRegion.dump(tf);
x = entityTickRegion.regionX;
z = entityTickRegion.regionZ;
}
if (entityTickRegion == null && tileEntityTickRegion == null) {
tf.sb.append("tickRegion for ").append(hashCode).append(" does not exist");
} else {
tf.sb.append("Dumped tickRegions for ").append(hashCode).append(": ").append(x).append(", ").append(z);
}
return tf;
}
public TableFormatter writeTECounts(final TableFormatter tf) {
final Map<Class, ComparableIntegerHolder> counts = new HashMap<Class, ComparableIntegerHolder>() {
@Override
public ComparableIntegerHolder get(Object key_) {
Class key = (Class) key_;
ComparableIntegerHolder value = super.get(key);
if (value == null) {
value = new ComparableIntegerHolder();
put(key, value);
}
return value;
}
};
for (TileEntity tileEntity : tileEntityList.unsafe()) {
if (tileEntity == null) {
continue;
}
counts.get(tileEntity.getClass()).value++;
}
List<Class> sortedKeys = CollectionsUtil.sortedKeys(counts, 15);
tf
.heading("Type")
.heading("Number");
for (Class clazz : sortedKeys) {
tf
.row(MappingUtil.debobfuscate(clazz.getName()))
.row(counts.get(clazz).value);
}
tf.finishTable();
return tf;
}
private class ComparableIntegerHolder implements Comparable<ComparableIntegerHolder> {
public int value;
ComparableIntegerHolder() {
}
@Override
public int compareTo(final ComparableIntegerHolder comparableIntegerHolder) {
int otherValue = comparableIntegerHolder.value;
return (value < otherValue) ? -1 : ((value == otherValue) ? 0 : 1);
}
}
private class FixDiscrepanciesTask implements Runnable {
FixDiscrepanciesTask() {
}
@Override
public void run() {
StringBuilder sb = new StringBuilder();
fixDiscrepancies(sb);
if (sb.length() > 0) {
Log.severe(sb.toString());
}
}
}
}
| src/common/nallar/tickthreading/minecraft/TickManager.java | package nallar.tickthreading.minecraft;
import java.util.ArrayList;
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.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.Lock;
import nallar.collections.ConcurrentIterableArrayList;
import nallar.collections.ConcurrentUnsafeIterableArrayList;
import nallar.collections.ContainedRemoveSet;
import nallar.tickthreading.Log;
import nallar.tickthreading.minecraft.commands.TPSCommand;
import nallar.tickthreading.minecraft.tickregion.EntityTickRegion;
import nallar.tickthreading.minecraft.tickregion.TickRegion;
import nallar.tickthreading.minecraft.tickregion.TileEntityTickRegion;
import nallar.tickthreading.util.CollectionsUtil;
import nallar.tickthreading.util.TableFormatter;
import nallar.unsafe.UnsafeUtil;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityCreature;
import net.minecraft.entity.IProjectile;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.server.MinecraftServer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.WorldServer;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.gen.ChunkProviderServer;
public final class TickManager {
private static final byte lockXPlus = 1 << 1;
private static final byte lockXMinus = 1 << 2;
private static final byte lockZPlus = 1 << 3;
private static final byte lockZMinus = 1 << 4;
public static final int regionSize = TickThreading.instance.regionSize;
public static final int regionSizePower = 31 - Integer.numberOfLeadingZeros(regionSize);
public boolean profilingEnabled = false;
private double averageTickLength = 0;
private long lastTickLength = 0;
private long lastStartTime = 0;
private static final int shuffleInterval = 3600;
private int shuffleCount;
private final boolean waitForCompletion;
private final WorldServer world;
public final ConcurrentUnsafeIterableArrayList<TileEntity> tileEntityList = new ConcurrentUnsafeIterableArrayList<TileEntity>();
public final ConcurrentUnsafeIterableArrayList<Entity> entityList = new ConcurrentUnsafeIterableArrayList<Entity>();
public Object tileEntityLock = new Object();
public Object entityLock = new Object();
private final Map<Integer, TileEntityTickRegion> tileEntityCallables = new HashMap<Integer, TileEntityTickRegion>();
private final Map<Integer, EntityTickRegion> entityCallables = new HashMap<Integer, EntityTickRegion>();
private final ConcurrentIterableArrayList<TickRegion> tickRegions = new ConcurrentIterableArrayList<TickRegion>();
private final ThreadManager threadManager;
private final Map<Class<?>, Integer> entityClassToCountMap = new ConcurrentHashMap<Class<?>, Integer>();
private final ConcurrentLinkedQueue<TickRegion> removalQueue = new ConcurrentLinkedQueue<TickRegion>();
public TickManager(WorldServer world, int threads, boolean waitForCompletion) {
this.waitForCompletion = waitForCompletion;
threadManager = new ThreadManager(threads, "Entities in " + Log.name(world));
this.world = world;
shuffleCount = world.rand.nextInt(shuffleInterval);
}
public TileEntityTickRegion getTileEntityRegion(int hashCode) {
return tileEntityCallables.get(hashCode);
}
@SuppressWarnings ("NumericCastThatLosesPrecision")
private TileEntityTickRegion getOrCreateRegion(TileEntity tileEntity) {
int regionX = tileEntity.xCoord >> regionSizePower;
int regionZ = tileEntity.zCoord >> regionSizePower;
int hashCode = getHashCodeFromRegionCoords(regionX, regionZ);
TileEntityTickRegion callable = tileEntityCallables.get(hashCode);
if (callable == null) {
synchronized (tickRegions) {
callable = tileEntityCallables.get(hashCode);
if (callable == null) {
callable = new TileEntityTickRegion(world, this, regionX, regionZ);
tileEntityCallables.put(hashCode, callable);
tickRegions.add(callable);
}
}
}
return callable;
}
public EntityTickRegion getEntityRegion(int hashCode) {
return entityCallables.get(hashCode);
}
@SuppressWarnings ("NumericCastThatLosesPrecision")
private EntityTickRegion getOrCreateRegion(Entity entity) {
int regionX = (entity.chunkCoordX << 4) >> regionSizePower;
int regionZ = (entity.chunkCoordZ << 4) >> regionSizePower;
int hashCode = getHashCodeFromRegionCoords(regionX, regionZ);
EntityTickRegion callable = entityCallables.get(hashCode);
if (callable == null) {
synchronized (tickRegions) {
callable = entityCallables.get(hashCode);
if (callable == null) {
callable = new EntityTickRegion(world, this, regionX, regionZ);
entityCallables.put(hashCode, callable);
tickRegions.add(callable);
}
}
}
return callable;
}
public static int getHashCode(TileEntity tileEntity) {
return getHashCode(tileEntity.xCoord, tileEntity.zCoord);
}
public static int getHashCode(Entity entity) {
return getHashCode(entity.chunkCoordX << 4, entity.chunkCoordZ << 4);
}
public static int getHashCode(int x, int z) {
return getHashCodeFromRegionCoords(x >> regionSizePower, z >> regionSizePower);
}
public static int getHashCodeFromRegionCoords(int x, int z) {
return x + (z << 16);
}
public void queueForRemoval(TickRegion tickRegion) {
removalQueue.add(tickRegion);
}
private void processChanges() {
TickRegion tickRegion;
while ((tickRegion = removalQueue.poll()) != null) {
if (tickRegion.isEmpty()) {
synchronized (tickRegions) {
if ((tickRegion instanceof EntityTickRegion ? entityCallables.remove(tickRegion.hashCode) : tileEntityCallables.remove(tickRegion.hashCode)) == tickRegion) {
tickRegions.remove(tickRegion);
}
}
}
}
}
public boolean add(TileEntity tileEntity, boolean newEntity) {
TileEntityTickRegion tileEntityTickRegion = getOrCreateRegion(tileEntity);
if (tileEntityTickRegion.add(tileEntity)) {
tileEntity.tickRegion = tileEntityTickRegion;
if (newEntity) {
synchronized (tileEntityLock) {
tileEntityList.add(tileEntity);
}
}
return true;
}
return false;
}
public boolean add(Entity entity, boolean newEntity) {
EntityTickRegion entityTickRegion = getOrCreateRegion(entity);
if (entityTickRegion.add(entity)) {
entity.tickRegion = entityTickRegion;
if (newEntity) {
synchronized (entityLock) {
entityList.add(entity);
}
synchronized (entityClassToCountMap) {
Class entityClass = entity.getClass();
Integer count = entityClassToCountMap.get(entityClass);
if (count == null) {
count = 0;
}
entityClassToCountMap.put(entityClass, count + 1);
}
}
return true;
}
return false;
}
public void batchRemoveEntities(HashSet<Entity> entities) {
entities = safeCopyClear(entities);
if (entities == null) {
return;
}
synchronized (entityLock) {
entityList.removeAll(entities);
}
ChunkProviderServer chunkProviderServer = world.theChunkProviderServer;
for (Entity entity : entities) {
if (entity == null) {
continue;
}
int x = entity.chunkCoordX;
int z = entity.chunkCoordZ;
if (entity.addedToChunk) {
Chunk chunk = chunkProviderServer.getChunkIfExists(x, z);
if (chunk != null) {
chunk.removeEntity(entity);
}
}
world.releaseEntitySkin(entity);
EntityTickRegion tickRegion = entity.tickRegion;
if (tickRegion != null) {
tickRegion.remove(entity);
entity.tickRegion = null;
Class entityClass = entity.getClass();
synchronized (entityClassToCountMap) {
Integer count = entityClassToCountMap.get(entityClass);
if (count == null) {
throw new IllegalStateException("Removed an entity which should not have been in the entityList");
}
entityClassToCountMap.put(entityClass, count - 1);
}
}
}
}
public void batchRemoveTileEntities(HashSet<TileEntity> tileEntities) {
tileEntities = safeCopyClear(tileEntities);
if (tileEntities == null) {
return;
}
for (TileEntity tileEntity : tileEntities) {
TileEntityTickRegion tickRegion = tileEntity.tickRegion;
if (tickRegion != null) {
tickRegion.remove(tileEntity);
tileEntity.tickRegion = null;
tileEntity.onChunkUnload();
}
unlock(tileEntity);
}
synchronized (tileEntityLock) {
tileEntityList.removeAll(tileEntities);
}
}
private static <T> HashSet<T> safeCopyClear(HashSet<T> c) {
synchronized (c) {
if (c.isEmpty()) {
return null;
}
HashSet<T> copy = new HashSet<T>(c);
c.clear();
return copy;
}
}
public void remove(TileEntity tileEntity) {
TileEntityTickRegion tileEntityTickRegion = tileEntity.tickRegion;
if (tileEntityTickRegion == null) {
tileEntityTickRegion = getOrCreateRegion(tileEntity);
}
tileEntityTickRegion.remove(tileEntity);
removed(tileEntity);
}
public void remove(Entity entity) {
EntityTickRegion entityTickRegion = entity.tickRegion;
if (entityTickRegion == null) {
entityTickRegion = getOrCreateRegion(entity);
}
entityTickRegion.remove(entity);
removed(entity);
}
public void removed(TileEntity tileEntity) {
tileEntity.tickRegion = null;
synchronized (tileEntityLock) {
tileEntityList.remove(tileEntity);
}
unlock(tileEntity);
}
public void removed(Entity entity) {
boolean removed;
entity.tickRegion = null;
synchronized (entityLock) {
removed = entityList.remove(entity);
}
if (removed) {
Class entityClass = entity.getClass();
synchronized (entityClassToCountMap) {
Integer count = entityClassToCountMap.get(entityClass);
if (count == null) {
throw new IllegalStateException("Removed an entity which should not have been in the entityList");
}
entityClassToCountMap.put(entityClass, count - 1);
}
}
}
/* Oh, Java.
Explicit MONITORENTER/EXIT should really be part of the language, there are just some cases like this where synchronized blocks get too messy,
and performance is bad if using other locks.
.lock/unlock calls here are replaced with MONITORENTER/EXIT.
*/
void unlock(TileEntity tE) {
Lock lock = tE.lockManagementLock;
lock.lock();
byte locks = tE.usedLocks;
boolean xM = ((locks & lockXMinus) != 0) || tE.xMinusLock != null;
boolean xP = ((locks & lockXPlus) != 0) || tE.xPlusLock != null;
boolean zM = ((locks & lockZMinus) != 0) || tE.zMinusLock != null;
boolean zP = ((locks & lockZPlus) != 0) || tE.zPlusLock != null;
tE.xPlusLock = null;
tE.xMinusLock = null;
tE.zPlusLock = null;
tE.zMinusLock = null;
tE.usedLocks = 0;
if (tE.thisLock == null) {
lock.unlock();
return;
}
int xPos = tE.lastTTX;
int yPos = tE.lastTTY;
int zPos = tE.lastTTZ;
TileEntity xMTE = xM ? world.getTEWithoutLoad(xPos - 1, yPos, zPos) : null;
TileEntity xPTE = xP ? world.getTEWithoutLoad(xPos + 1, yPos, zPos) : null;
TileEntity zMTE = zM ? world.getTEWithoutLoad(xPos, yPos, zPos - 1) : null;
TileEntity zPTE = zP ? world.getTEWithoutLoad(xPos, yPos, zPos + 1) : null;
if (xMTE == null) {
xM = false;
}
if (xPTE == null) {
xP = false;
}
if (zMTE == null) {
zM = false;
}
if (zPTE == null) {
zP = false;
}
lock.unlock();
if (!(xM || xP || zM || zP)) {
return;
}
if (xP) {
xPTE.lockManagementLock.lock();
}
if (zP) {
zPTE.lockManagementLock.lock();
}
lock.lock();
if (zM) {
zMTE.lockManagementLock.lock();
}
if (xM) {
xMTE.lockManagementLock.lock();
}
if (xM) {
xMTE.usedLocks &= ~lockXPlus;
xMTE.xPlusLock = null;
}
if (xP) {
xPTE.usedLocks &= ~lockXMinus;
xPTE.xMinusLock = null;
}
if (zM) {
zMTE.usedLocks &= ~lockZPlus;
zMTE.zPlusLock = null;
}
if (zP) {
zPTE.usedLocks &= ~lockZMinus;
zPTE.zMinusLock = null;
}
if (xM) {
xMTE.lockManagementLock.unlock();
}
if (zM) {
zMTE.lockManagementLock.unlock();
}
lock.unlock();
if (zP) {
zPTE.lockManagementLock.unlock();
}
if (xP) {
xPTE.lockManagementLock.unlock();
}
}
/*
.lock/unlock calls here are replaced with MONITORENTER/EXIT.
*/
public final void lock(TileEntity tE) {
unlock(tE);
Lock lock = tE.lockManagementLock;
lock.lock();
int maxPosition = (regionSize / 2) - 1;
int xPos = tE.xCoord;
int yPos = tE.yCoord;
int zPos = tE.zCoord;
tE.lastTTX = xPos;
tE.lastTTY = yPos;
tE.lastTTZ = zPos;
int relativeXPos = (xPos % regionSize) / 2;
int relativeZPos = (zPos % regionSize) / 2;
boolean onMinusX = relativeXPos == 0;
boolean onMinusZ = relativeZPos == 0;
boolean onPlusX = relativeXPos == maxPosition;
boolean onPlusZ = relativeZPos == maxPosition;
boolean xM = onMinusX || onMinusZ || onPlusZ;
boolean xP = onPlusX || onMinusZ || onPlusZ;
boolean zM = onMinusZ || onMinusX || onPlusX;
boolean zP = onPlusZ || onMinusX || onPlusX;
TileEntity xMTE = xM ? world.getTEWithoutLoad(xPos - 1, yPos, zPos) : null;
TileEntity xPTE = xP ? world.getTEWithoutLoad(xPos + 1, yPos, zPos) : null;
TileEntity zMTE = zM ? world.getTEWithoutLoad(xPos, yPos, zPos - 1) : null;
TileEntity zPTE = zP ? world.getTEWithoutLoad(xPos, yPos, zPos + 1) : null;
if (xMTE == null) {
xM = false;
}
if (xPTE == null) {
xP = false;
}
if (zMTE == null) {
zM = false;
}
if (zPTE == null) {
zP = false;
}
lock.unlock();
if (!(xM || xP || zM || zP)) {
return;
}
Lock thisLock = tE.thisLock;
if (xP) {
xPTE.lockManagementLock.lock();
}
if (zP) {
zPTE.lockManagementLock.lock();
}
lock.lock();
if (zM) {
zMTE.lockManagementLock.lock();
}
if (xM) {
xMTE.lockManagementLock.lock();
}
byte usedLocks = tE.usedLocks;
if (xM) {
Lock otherLock = xMTE.thisLock;
if (otherLock != null) {
xMTE.usedLocks |= lockXPlus;
tE.xMinusLock = otherLock;
}
if (thisLock != null) {
usedLocks |= lockXMinus;
xMTE.xPlusLock = thisLock;
}
}
if (xP) {
Lock otherLock = xPTE.thisLock;
if (otherLock != null) {
xPTE.usedLocks |= lockXMinus;
tE.xPlusLock = otherLock;
}
if (thisLock != null) {
usedLocks |= lockXPlus;
xPTE.xMinusLock = thisLock;
}
}
if (zM) {
Lock otherLock = zMTE.thisLock;
if (otherLock != null) {
zMTE.usedLocks |= lockZPlus;
tE.zMinusLock = otherLock;
}
if (thisLock != null) {
usedLocks |= lockZMinus;
zMTE.zPlusLock = thisLock;
}
}
if (zP) {
Lock otherLock = zPTE.thisLock;
if (otherLock != null) {
zPTE.usedLocks |= lockZMinus;
tE.zPlusLock = otherLock;
}
if (thisLock != null) {
usedLocks |= lockZPlus;
zPTE.zMinusLock = thisLock;
}
}
tE.usedLocks = usedLocks;
if (xM) {
xMTE.lockManagementLock.unlock();
}
if (zM) {
zMTE.lockManagementLock.unlock();
}
lock.unlock();
if (zP) {
zPTE.lockManagementLock.unlock();
}
if (xP) {
xPTE.lockManagementLock.unlock();
}
}
public void doTick() {
boolean previousProfiling = world.theProfiler.profilingEnabled;
lastStartTime = System.nanoTime();
threadManager.waitForCompletion();
if (previousProfiling) {
world.theProfiler.profilingEnabled = false;
}
threadManager.runList(tickRegions);
if (previousProfiling || waitForCompletion) {
postTick();
}
if (previousProfiling) {
world.theProfiler.profilingEnabled = true;
}
}
public void tickEnd() {
if (!waitForCompletion) {
postTick();
}
}
private void postTick() {
lastTickLength = (threadManager.waitForCompletion() - lastStartTime);
averageTickLength = ((averageTickLength * 127) + lastTickLength) / 128;
if (!removalQueue.isEmpty()) {
threadManager.run(new Runnable() {
@Override
public void run() {
processChanges();
if (shuffleCount++ % shuffleInterval == 0) {
synchronized (tickRegions) {
Collections.shuffle(tickRegions);
if (tickRegions.removeAll(Collections.singleton(null))) {
Log.severe("Something broke, tickRegions for " + world.getName() + " contained null!");
}
}
MinecraftServer.runQueue.add(new FixDiscrepanciesTask());
}
}
});
}
}
public void unload() {
threadManager.stop();
synchronized (tickRegions) {
for (TickRegion tickRegion : tickRegions) {
tickRegion.die();
}
tickRegions.clear();
}
entityList.clear();
entityClassToCountMap.clear();
UnsafeUtil.clean(this);
}
public void fixDiscrepancies(StringBuilder sb) {
long startTime = System.nanoTime();
int fixed = 0;
int missingEntities = 0;
int missingTiles = 0;
int duplicateEntities = 0;
int duplicateTiles = 0;
int invalidTiles = 0;
int unloadedEntities = 0;
int unloadedTiles = 0;
ChunkProviderServer chunkProviderServer = world.theChunkProviderServer;
{
Set<Entity> contained = new HashSet<Entity>();
Set<Entity> toRemove = new ContainedRemoveSet<Entity>();
List<Entity> unloaded = new ArrayList<Entity>();
synchronized (entityLock) {
for (Entity e : entityList) {
if (add(e, false)) {
missingEntities++;
fixed++;
} else if (!contained.add(e)) {
toRemove.add(e);
duplicateEntities++;
fixed++;
} else if (e instanceof IProjectile || e instanceof EntityCreature || e instanceof EntityMob) {
synchronized (e) {
Chunk chunk = world.getChunkIfExists(e.chunkCoordX, e.chunkCoordZ);
if (chunk == null || !chunk.entityLists[e.chunkCoordY].contains(e)) {
unloaded.add(e);
unloadedEntities++;
}
}
}
}
for (Entity e : unloaded) {
remove(e);
}
entityList.removeAll(toRemove);
}
}
{
Set<TileEntity> contained = new HashSet<TileEntity>();
Set<TileEntity> toRemove = new ContainedRemoveSet<TileEntity>();
List<TileEntity> copy = new ArrayList<TileEntity>(tileEntityList.size());
synchronized (tileEntityLock) {
for (TileEntity te : tileEntityList) {
copy.add(te);
if (add(te, false)) {
missingTiles++;
fixed++;
}
if (!contained.add(te)) {
toRemove.add(te);
duplicateTiles++;
fixed++;
}
}
tileEntityList.removeAll(toRemove);
}
for (TileEntity te : copy) {
Chunk chunk;
boolean invalid = te.isInvalid();
if (te.yCoord < 0 || te.yCoord > 255) {
sb.append("TileEntity ").append(Log.toString(te)).append(" has an invalid y coordinate.\n");
invalid = true;
}
if (invalid || (chunk = chunkProviderServer.getChunkIfExists(te.xCoord >> 4, te.zCoord >> 4)) == null || chunk.getChunkBlockTileEntity(te.xCoord & 15, te.yCoord, te.zCoord & 15) != te) {
if (invalid) {
invalidTiles++;
sb.append("Removed ").append(Log.toString(te)).append(" as it is invalid.\n");
} else {
unloadedTiles++;
te.invalidate();
sb.append("Removed ").append(Log.toString(te)).append(" as it should have been unloaded.\n");
}
fixed++;
remove(te);
}
}
}
int totalSize = tickRegions.size();
int tESize = tileEntityCallables.size();
int eSize = entityCallables.size();
if (eSize + tESize != totalSize) {
sb.append("TickRegion list size mismatch, total: ").append(totalSize).append(", te: ").append(tESize).append(", e: ").append(eSize).append(", combined: ").append(tESize + eSize);
if (fixed != 0) {
sb.append('\n');
}
}
if (fixed != 0) {
sb.append("Found and fixed ").append(fixed).append(" discrepancies in tile/entity lists in ").append(Log.name(world))
.append("\ntiles - invalid: ").append(invalidTiles).append(", missing: ").append(missingTiles).append(", duplicate: ").append(duplicateTiles).append(", unloaded: ").append(unloadedTiles)
.append("\nentities - missing: ").append(missingEntities).append(", duplicate: ").append(duplicateEntities).append(", unloaded: ").append(unloadedEntities)
.append("\nTook ").append((System.nanoTime() - startTime) / 1000000l).append("ms");
}
}
public void recordStats(final TPSCommand.StatsHolder statsHolder) {
statsHolder.entities += entityList.size();
statsHolder.tileEntities += tileEntityList.size();
statsHolder.chunks += world.theChunkProviderServer.getLoadedChunkCount();
}
public void writeStats(TableFormatter tf, final TPSCommand.StatsHolder statsHolder) {
long timeTotal = 0;
double time = Double.NaN;
try {
long[] tickTimes = MinecraftServer.getServer().getTickTimes(world);
for (long tick : tickTimes) {
timeTotal += tick;
}
time = (timeTotal) / (double) tickTimes.length;
if (time == 0) {
time = 0.1;
}
} catch (NullPointerException ignored) {
}
int entities = entityList.size();
statsHolder.entities += entities;
int tileEntities = tileEntityList.size();
statsHolder.tileEntities += tileEntities;
int chunks = world.theChunkProviderServer.getLoadedChunkCount();
statsHolder.chunks += chunks;
tf
.row(Log.name(world))
.row(entities)
.row(tileEntities)
.row(chunks)
.row(world.playerEntities.size())
.row(TableFormatter.formatDoubleWithPrecision((time * 100f) / MinecraftServer.getTargetTickTime(), 2) + '%');
}
public TableFormatter writeDetailedStats(TableFormatter tf) {
@SuppressWarnings ("MismatchedQueryAndUpdateOfStringBuilder")
StringBuilder stats = tf.sb;
stats.append("World: ").append(Log.name(world)).append('\n');
stats.append("---- Slowest tick regions ----").append('\n');
// TODO: Rewrite this
float averageAverageTickTime = 0;
float maxTickTime = 0;
SortedMap<Float, TickRegion> sortedTickCallables = new TreeMap<Float, TickRegion>();
synchronized (tickRegions) {
for (TickRegion tickRegion : tickRegions) {
float averageTickTime = tickRegion.getAverageTickTime();
averageAverageTickTime += averageTickTime;
sortedTickCallables.put(averageTickTime, tickRegion);
if (averageTickTime > maxTickTime) {
maxTickTime = averageTickTime;
}
}
Collection<TickRegion> var = sortedTickCallables.values();
TickRegion[] sortedTickCallablesArray = var.toArray(new TickRegion[var.size()]);
tf
.heading("")
.heading("X")
.heading("Z")
.heading("N")
.heading("Time");
for (int i = sortedTickCallablesArray.length - 1; i >= sortedTickCallablesArray.length - 7; i--) {
if (i >= 0 && sortedTickCallablesArray[i].getAverageTickTime() > 0.2) {
sortedTickCallablesArray[i].writeStats(tf);
}
}
tf.finishTable();
averageAverageTickTime /= tickRegions.size();
stats.append("\n---- World stats ----");
stats.append('\n').append(world.getChunkProvider().makeString());
stats.append("\nAverage tick time: ").append(averageAverageTickTime).append("ms");
stats.append("\nMax tick time: ").append(maxTickTime).append("ms");
stats.append("\nEffective tick time: ").append(lastTickLength / 1000000f).append("ms");
stats.append("\nAverage effective tick time: ").append((float) averageTickLength / 1000000).append("ms");
stats.append("\nGlobal TPS: ").append(TableFormatter.formatDoubleWithPrecision(MinecraftServer.getTPS(), 2));
}
return tf;
}
public TableFormatter writeEntityStats(TableFormatter tf) {
tf
.heading("Main")
.heading("Map")
.heading("Region")
.heading("Player");
tf
.row(entityList.size())
.row(getTotalEntityCountFromMap())
.row(getTotalEntityCountFromRegions())
.row(getEntityCount(EntityPlayer.class));
tf.finishTable();
return tf;
}
private int getTotalEntityCountFromRegions() {
int count = 0;
for (EntityTickRegion entityTickRegion : entityCallables.values()) {
count += entityTickRegion.size();
}
return count;
}
private int getTotalEntityCountFromMap() {
int count = 0;
for (Map.Entry<Class<?>, Integer> entry : entityClassToCountMap.entrySet()) {
count += entry.getValue();
}
return count;
}
public int getEntityCount(Class<?> clazz) {
int count = 0;
for (Map.Entry<Class<?>, Integer> entry : entityClassToCountMap.entrySet()) {
if (clazz.isAssignableFrom(entry.getKey())) {
count += entry.getValue();
}
}
return count;
}
public TableFormatter writeRegionDetails(final TableFormatter tf, final int hashCode) {
int x = 0;
int z = 0;
TileEntityTickRegion tileEntityTickRegion = getTileEntityRegion(hashCode);
if (tileEntityTickRegion != null) {
tileEntityTickRegion.dump(tf);
x = tileEntityTickRegion.regionX;
z = tileEntityTickRegion.regionZ;
}
EntityTickRegion entityTickRegion = getEntityRegion(hashCode);
if (entityTickRegion != null) {
entityTickRegion.dump(tf);
x = entityTickRegion.regionX;
z = entityTickRegion.regionZ;
}
if (entityTickRegion == null && tileEntityTickRegion == null) {
tf.sb.append("tickRegion for ").append(hashCode).append(" does not exist");
} else {
tf.sb.append("Dumped tickRegions for ").append(hashCode).append(": ").append(x).append(", ").append(z);
}
return tf;
}
public TableFormatter writeTECounts(final TableFormatter tf) {
final Map<Class, ComparableIntegerHolder> counts = new HashMap<Class, ComparableIntegerHolder>() {
@Override
public ComparableIntegerHolder get(Object key_) {
Class key = (Class) key_;
ComparableIntegerHolder value = super.get(key);
if (value == null) {
value = new ComparableIntegerHolder();
put(key, value);
}
return value;
}
};
for (TileEntity tileEntity : tileEntityList.unsafe()) {
if (tileEntity == null) {
continue;
}
counts.get(tileEntity.getClass()).value++;
}
List<Class> sortedKeys = CollectionsUtil.sortedKeys(counts, 15);
tf
.heading("Type")
.heading("Number");
for (Class clazz : sortedKeys) {
tf
.row(clazz.getName())
.row(counts.get(clazz).value);
}
tf.finishTable();
return tf;
}
private class ComparableIntegerHolder implements Comparable<ComparableIntegerHolder> {
public int value;
ComparableIntegerHolder() {
}
@Override
public int compareTo(final ComparableIntegerHolder comparableIntegerHolder) {
int otherValue = comparableIntegerHolder.value;
return (value < otherValue) ? -1 : ((value == otherValue) ? 0 : 1);
}
}
private class FixDiscrepanciesTask implements Runnable {
FixDiscrepanciesTask() {
}
@Override
public void run() {
StringBuilder sb = new StringBuilder();
fixDiscrepancies(sb);
if (sb.length() > 0) {
Log.severe(sb.toString());
}
}
}
}
| Use deobfuscated class name in TE count profiling
Signed-off-by: Ross Allan <[email protected]>
| src/common/nallar/tickthreading/minecraft/TickManager.java | Use deobfuscated class name in TE count profiling |
|
Java | epl-1.0 | 73e1aec5aca941017537c05a71faf2656c93fcfb | 0 | rohitmohan96/ceylon-ide-eclipse,rohitmohan96/ceylon-ide-eclipse | package com.redhat.ceylon.eclipse.code.search;
import static com.redhat.ceylon.eclipse.code.editor.DynamicMenuItem.collapseMenuItems;
import static com.redhat.ceylon.eclipse.code.editor.EditorUtil.getCurrentEditor;
import static com.redhat.ceylon.eclipse.ui.CeylonPlugin.PLUGIN_ID;
import static com.redhat.ceylon.eclipse.ui.CeylonResources.CEYLON_DECS;
import static com.redhat.ceylon.eclipse.ui.CeylonResources.CEYLON_REFS;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.actions.CompoundContributionItem;
import com.redhat.ceylon.eclipse.code.editor.CeylonEditor;
import com.redhat.ceylon.eclipse.code.editor.DynamicMenuItem;
import com.redhat.ceylon.eclipse.ui.CeylonPlugin;
public class FindMenuItems extends CompoundContributionItem {
private static ImageRegistry imageRegistry = CeylonPlugin.getInstance()
.getImageRegistry();
private static ImageDescriptor REFS = imageRegistry.getDescriptor(CEYLON_REFS);
private static ImageDescriptor DECS = imageRegistry.getDescriptor(CEYLON_DECS);
public FindMenuItems() {}
public FindMenuItems(String id) {
super(id);
}
@Override
public IContributionItem[] getContributionItems() {
IContributionItem[] items = getItems(getCurrentEditor());
if (collapseMenuItems(getParent())) {
MenuManager submenu = new MenuManager("Find");
submenu.setActionDefinitionId(CeylonEditor.FIND_MENU_ID);
for (IContributionItem item: items) {
submenu.add(item);
}
return new IContributionItem[] { submenu };
}
else {
return items;
}
}
private IContributionItem[] getItems(IEditorPart editor) {
return new IContributionItem[] {
new DynamicMenuItem(PLUGIN_ID + ".action.findReferences",
"Find &References",
editor==null ? false : new FindReferencesAction(editor).isEnabled(),
REFS),
new DynamicMenuItem(PLUGIN_ID + ".action.findAssignments",
"Find Assignments",
editor==null ? false : new FindAssignmentsAction(editor).isEnabled(),
REFS),
new DynamicMenuItem(PLUGIN_ID + ".action.findRefinements",
"Find Refinements",
editor==null ? false : new FindRefinementsAction(editor).isEnabled(),
DECS),
new DynamicMenuItem(PLUGIN_ID + ".action.findSubtypes",
"Find Subtypes",
editor==null ? false : new FindSubtypesAction(editor).isEnabled(),
DECS),
new Separator(),
new DynamicMenuItem("org.eclipse.search.ui.performTextSearchWorkspace",
"Find Text in Workspace", true)
};
}
}
| plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/search/FindMenuItems.java | package com.redhat.ceylon.eclipse.code.search;
import static com.redhat.ceylon.eclipse.code.editor.DynamicMenuItem.collapseMenuItems;
import static com.redhat.ceylon.eclipse.code.editor.EditorUtil.getCurrentEditor;
import static com.redhat.ceylon.eclipse.code.editor.EditorUtil.getSelection;
import static com.redhat.ceylon.eclipse.ui.CeylonPlugin.PLUGIN_ID;
import static com.redhat.ceylon.eclipse.ui.CeylonResources.CEYLON_DECS;
import static com.redhat.ceylon.eclipse.ui.CeylonResources.CEYLON_REFS;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.actions.CompoundContributionItem;
import org.eclipse.ui.texteditor.ITextEditor;
import com.redhat.ceylon.eclipse.code.editor.CeylonEditor;
import com.redhat.ceylon.eclipse.code.editor.DynamicMenuItem;
import com.redhat.ceylon.eclipse.ui.CeylonPlugin;
public class FindMenuItems extends CompoundContributionItem {
private static ImageRegistry imageRegistry = CeylonPlugin.getInstance()
.getImageRegistry();
private static ImageDescriptor REFS = imageRegistry.getDescriptor(CEYLON_REFS);
private static ImageDescriptor DECS = imageRegistry.getDescriptor(CEYLON_DECS);
public FindMenuItems() {}
public FindMenuItems(String id) {
super(id);
}
@Override
public IContributionItem[] getContributionItems() {
IContributionItem[] items = getItems(getCurrentEditor());
if (collapseMenuItems(getParent())) {
MenuManager submenu = new MenuManager("Find");
submenu.setActionDefinitionId(CeylonEditor.FIND_MENU_ID);
for (IContributionItem item: items) {
submenu.add(item);
}
return new IContributionItem[] { submenu };
}
else {
return items;
}
}
private IContributionItem[] getItems(IEditorPart editor) {
return new IContributionItem[] {
new DynamicMenuItem(PLUGIN_ID + ".action.findReferences",
"Find &References",
editor==null ? false : new FindReferencesAction(editor).isEnabled(),
REFS),
new DynamicMenuItem(PLUGIN_ID + ".action.findAssignments",
"Find Assignments",
editor==null ? false : new FindAssignmentsAction(editor).isEnabled(),
REFS),
new DynamicMenuItem(PLUGIN_ID + ".action.findRefinements",
"Find Refinements",
editor==null ? false : new FindRefinementsAction(editor).isEnabled(),
DECS),
new DynamicMenuItem(PLUGIN_ID + ".action.findSubtypes",
"Find Subtypes",
editor==null ? false : new FindSubtypesAction(editor).isEnabled(),
DECS),
new Separator(),
new DynamicMenuItem("org.eclipse.search.ui.performTextSearchWorkspace",
"Find Text in Workspace",
editor instanceof ITextEditor && getSelection((ITextEditor)editor).getLength()>0)
};
}
}
| better | plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/search/FindMenuItems.java | better |
|
Java | epl-1.0 | 42f420dd7298d12d8677f1e0c544dff278707fec | 0 | gameduell/eclipselink.runtime,gameduell/eclipselink.runtime,gameduell/eclipselink.runtime,gameduell/eclipselink.runtime | /*******************************************************************************
* Copyright (c) 1998, 2009 Oracle. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.sdo.helper.delegates;
import commonj.sdo.DataObject;
import commonj.sdo.Property;
import commonj.sdo.helper.HelperContext;
import commonj.sdo.helper.XMLDocument;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.WeakHashMap;
import javax.xml.namespace.QName;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.eclipse.persistence.sdo.SDOConstants;
import org.eclipse.persistence.sdo.SDOType;
import org.eclipse.persistence.sdo.SDOXMLDocument;
import org.eclipse.persistence.sdo.helper.SDOUnmappedContentHandler;
import org.eclipse.persistence.sdo.helper.SDOClassLoader;
import org.eclipse.persistence.sdo.helper.SDOMarshalListener;
import org.eclipse.persistence.sdo.helper.SDOTypeHelper;
import org.eclipse.persistence.sdo.helper.SDOUnmarshalListener;
import org.eclipse.persistence.sdo.helper.SDOXMLHelper;
import org.eclipse.persistence.sdo.types.SDOPropertyType;
import org.eclipse.persistence.sdo.types.SDOTypeType;
import org.eclipse.persistence.exceptions.SDOException;
import org.eclipse.persistence.exceptions.XMLMarshalException;
import org.eclipse.persistence.internal.oxm.XMLConversionManager;
import org.eclipse.persistence.internal.sessions.AbstractSession;
import org.eclipse.persistence.oxm.NamespaceResolver;
import org.eclipse.persistence.oxm.XMLContext;
import org.eclipse.persistence.oxm.XMLDescriptor;
import org.eclipse.persistence.oxm.XMLLogin;
import org.eclipse.persistence.oxm.XMLMarshaller;
import org.eclipse.persistence.oxm.XMLRoot;
import org.eclipse.persistence.oxm.XMLUnmarshaller;
import org.eclipse.persistence.oxm.record.ContentHandlerRecord;
import org.eclipse.persistence.oxm.record.FormattedWriterRecord;
import org.eclipse.persistence.oxm.record.NodeRecord;
import org.eclipse.persistence.oxm.record.WriterRecord;
import org.eclipse.persistence.sessions.Project;
import org.xml.sax.InputSource;
/**
* <p><b>Purpose</b>: Helper to XML documents into DataObects and DataObjects into XML documents.
* <p><b>Responsibilities</b>:<ul>
* <li> Load methods create commonj.sdo.XMLDocument objects from XML (unmarshal)
* <li> Save methods create XML from commonj.sdo.XMLDocument and commonj.sdo.DataObject objects (marshal)
* </ul>
*/
public class SDOXMLHelperDelegate implements SDOXMLHelper {
private SDOClassLoader loader;
private XMLContext xmlContext;
private Map<Thread, XMLMarshaller> xmlMarshallerMap;
private Map<Thread, XMLUnmarshaller> xmlUnmarshallerMap;
private Project topLinkProject;
// hold the context containing all helpers so that we can preserve inter-helper relationships
private HelperContext aHelperContext;
public SDOXMLHelperDelegate(HelperContext aContext) {
this(aContext, Thread.currentThread().getContextClassLoader());
}
public SDOXMLHelperDelegate(HelperContext aContext, ClassLoader aClassLoader) {
aHelperContext = aContext;
// This ClassLoader is internal to SDO so no inter servlet-ejb container context issues should arise
loader = new SDOClassLoader(aClassLoader, aContext);
xmlMarshallerMap = new WeakHashMap<Thread, XMLMarshaller>();
xmlUnmarshallerMap = new WeakHashMap<Thread, XMLUnmarshaller>();
}
/**
* The specified TimeZone will be used for all String to date object
* conversions. By default the TimeZone from the JVM is used.
*/
public void setTimeZone(TimeZone timeZone) {
getXmlConversionManager().setTimeZone(timeZone);
}
/**
* By setting this flag to true the marshalled date objects marshalled to
* the XML schema types time and dateTime will be qualified by a time zone.
* By default time information is not time zone qualified.
*/
public void setTimeZoneQualified(boolean timeZoneQualified) {
getXmlConversionManager().setTimeZoneQualified(timeZoneQualified);
}
/**
* Creates and returns an XMLDocument from the input String.
* By default does not perform XSD validation.
* Same as
* load(new StringReader(inputString), null, null);
*
* @param inputString specifies the String to read from
* @return the new XMLDocument loaded
* @throws RuntimeException for errors in XML parsing or
* implementation-specific validation.
*/
public XMLDocument load(String inputString) {
StringReader reader = new StringReader(inputString);
try {
return load(reader, null, null);
} catch (IOException ioException) {
ioException.printStackTrace();
return null;
}
}
/**
* Creates and returns an XMLDocument from the inputStream.
* The InputStream will be closed after reading.
* By default does not perform XSD validation.
* Same as
* load(inputStream, null, null);
*
* @param inputStream specifies the InputStream to read from
* @return the new XMLDocument loaded
* @throws IOException for stream exceptions.
* @throws RuntimeException for errors in XML parsing or
* implementation-specific validation.
*/
public XMLDocument load(InputStream inputStream) throws IOException {
return load(inputStream, null, null);
}
/**
* Creates and returns an XMLDocument from the inputStream.
* The InputStream will be closed after reading.
* By default does not perform XSD validation.
* @param inputStream specifies the InputStream to read from
* @param locationURI specifies the URI of the document for relative schema locations
* @param options implementation-specific options.
* @return the new XMLDocument loaded
* @throws IOException for stream exceptions.
* @throws RuntimeException for errors in XML parsing or
* implementation-specific validation.
*/
public XMLDocument load(InputStream inputStream, String locationURI, Object options) throws IOException {
InputSource inputSource = new InputSource(inputStream);
return load(inputSource, locationURI, options);
}
/**
* Creates and returns an XMLDocument from the inputSource.
* The InputSource will be closed after reading.
* By default does not perform XSD validation.
* @param inputSource specifies the InputSource to read from
* @param locationURI specifies the URI of the document for relative schema locations
* @param options implementation-specific options.
* @return the new XMLDocument loaded
* @throws IOException for stream exceptions.
* @throws RuntimeException for errors in XML parsing or
* implementation-specific validation.
*/
public XMLDocument load(InputSource inputSource, String locationURI, Object options) throws IOException {
// get XMLUnmarshaller once - as we may create a new instance if this helper isDirty=true
XMLUnmarshaller anXMLUnmarshaller = getXmlUnmarshaller();
Object unmarshalledObject = null;
if (options == null) {
try {
unmarshalledObject = anXMLUnmarshaller.unmarshal(inputSource);
} catch(XMLMarshalException xmlException){
handleXMLMarshalException(xmlException);
}
} else {
try {
DataObject optionsDataObject = (DataObject)options;
try {
SDOType theType = (SDOType)optionsDataObject.get(SDOConstants.TYPE_LOAD_OPTION);
try{
if (theType != null) {
unmarshalledObject = anXMLUnmarshaller.unmarshal(inputSource, theType.getImplClass());
}else{
unmarshalledObject = anXMLUnmarshaller.unmarshal(inputSource);
}
} catch(XMLMarshalException xmlException){
handleXMLMarshalException(xmlException);
}
} catch (ClassCastException ccException) {
throw SDOException.typePropertyMustBeAType(ccException);
}
} catch (ClassCastException ccException) {
throw SDOException.optionsMustBeADataObject(ccException, SDOConstants.ORACLE_SDO_URL ,SDOConstants.XMLHELPER_LOAD_OPTIONS);
}
}
if (unmarshalledObject instanceof XMLRoot) {
XMLRoot xmlRoot = (XMLRoot)unmarshalledObject;
XMLDocument xmlDocument = createDocument((DataObject)((XMLRoot)unmarshalledObject).getObject(), ((XMLRoot)unmarshalledObject).getNamespaceURI(), ((XMLRoot)unmarshalledObject).getLocalName());
if(xmlRoot.getEncoding() != null) {
xmlDocument.setEncoding(xmlRoot.getEncoding());
}
if(xmlRoot.getXMLVersion() != null) {
xmlDocument.setXMLVersion(xmlRoot.getXMLVersion());
}
xmlDocument.setSchemaLocation(xmlRoot.getSchemaLocation());
xmlDocument.setNoNamespaceSchemaLocation(xmlRoot.getNoNamespaceSchemaLocation());
return xmlDocument;
} else if (unmarshalledObject instanceof DataObject) {
String localName = ((SDOType)((DataObject)unmarshalledObject).getType()).getXmlDescriptor().getDefaultRootElement();
if (localName == null) {
localName = ((SDOType)((DataObject)unmarshalledObject).getType()).getXsdLocalName();
}
return createDocument((DataObject)unmarshalledObject, ((DataObject)unmarshalledObject).getType().getURI(), localName);
} else if (unmarshalledObject instanceof XMLDocument) {
return (XMLDocument)unmarshalledObject;
}
return null;
}
/**
* Creates and returns an XMLDocument from the inputReader.
* The InputStream will be closed after reading.
* By default does not perform XSD validation.
* @param inputReader specifies the Reader to read from
* @param locationURI specifies the URI of the document for relative schema locations
* @param options implementation-specific options.
* @return the new XMLDocument loaded
* @throws IOException for stream exceptions.
* @throws RuntimeException for errors in XML parsing or
* implementation-specific validation.
*/
public XMLDocument load(Reader inputReader, String locationURI, Object options) throws IOException {
InputSource inputSource = new InputSource(inputReader);
return load(inputSource, locationURI, options);
}
public XMLDocument load(Source source, String locationURI, Object options) throws IOException {
// get XMLUnmarshaller once - as we may create a new instance if this helper isDirty=true
XMLUnmarshaller anXMLUnmarshaller = getXmlUnmarshaller();
Object unmarshalledObject = null;
if (options == null) {
try {
unmarshalledObject = anXMLUnmarshaller.unmarshal(source);
} catch(XMLMarshalException xmlException){
handleXMLMarshalException(xmlException);
}
} else {
try {
DataObject optionsDataObject = (DataObject)options;
try {
SDOType theType = (SDOType)optionsDataObject.get(SDOConstants.TYPE_LOAD_OPTION);
try{
if (theType != null) {
unmarshalledObject = anXMLUnmarshaller.unmarshal(source, theType.getImplClass());
}else{
unmarshalledObject = anXMLUnmarshaller.unmarshal(source);
}
} catch(XMLMarshalException xmlException){
handleXMLMarshalException(xmlException);
}
} catch (ClassCastException ccException) {
throw SDOException.typePropertyMustBeAType(ccException);
}
} catch (ClassCastException ccException) {
throw SDOException.optionsMustBeADataObject(ccException, SDOConstants.ORACLE_SDO_URL ,SDOConstants.XMLHELPER_LOAD_OPTIONS);
}
}
if (unmarshalledObject instanceof XMLRoot) {
XMLRoot xmlRoot = (XMLRoot)unmarshalledObject;
XMLDocument xmlDocument = createDocument((DataObject)((XMLRoot)unmarshalledObject).getObject(), ((XMLRoot)unmarshalledObject).getNamespaceURI(), ((XMLRoot)unmarshalledObject).getLocalName());
if(xmlRoot.getEncoding() != null) {
xmlDocument.setEncoding(xmlRoot.getEncoding());
}
if(xmlRoot.getXMLVersion() != null) {
xmlDocument.setXMLVersion(xmlRoot.getXMLVersion());
}
xmlDocument.setSchemaLocation(xmlRoot.getSchemaLocation());
xmlDocument.setNoNamespaceSchemaLocation(xmlRoot.getNoNamespaceSchemaLocation());
return xmlDocument;
} else if (unmarshalledObject instanceof DataObject) {
DataObject unmarshalledDataObject = (DataObject)unmarshalledObject;
String localName = ((SDOType)((DataObject)unmarshalledObject).getType()).getXmlDescriptor().getDefaultRootElement();
if (localName == null) {
localName = ((SDOType)((DataObject)unmarshalledObject).getType()).getXsdLocalName();
}
return createDocument(unmarshalledDataObject, unmarshalledDataObject.getType().getURI(), localName);
} else if (unmarshalledObject instanceof XMLDocument) {
return (XMLDocument)unmarshalledObject;
}
return null;
}
/**
* Returns the DataObject saved as an XML document with the specified root element.
* Same as
* StringWriter stringWriter = new StringWriter();
* save(createDocument(dataObject, rootElementURI, rootElementName),
* stringWriter, null);
* stringWriter.toString();
*
* @param dataObject specifies DataObject to be saved
* @param rootElementURI the Target Namespace URI of the root XML element
* @param rootElementName the Name of the root XML element
* @return the saved XML document as a string
* @throws IllegalArgumentException if the dataObject tree
* is not closed or has no container.
*/
public String save(DataObject dataObject, String rootElementURI, String rootElementName) {
try {
StringWriter writer = new StringWriter();
save(dataObject, rootElementURI, rootElementName, writer);
return writer.toString();
} catch (XMLMarshalException e) {
throw SDOException.xmlMarshalExceptionOccurred(e, rootElementURI, rootElementName);
}
}
/**
* Saves the DataObject as an XML document with the specified root element.
* Same as
* save(createDocument(dataObject, rootElementURI, rootElementName),
* outputStream, null);
*
* @param dataObject specifies DataObject to be saved
* @param rootElementURI the Target Namespace URI of the root XML element
* @param rootElementName the Name of the root XML element
* @param outputStream specifies the OutputStream to write to.
* @throws IOException for stream exceptions.
* @throws IllegalArgumentException if the dataObject tree
* is not closed or has no container.
*/
public void save(DataObject dataObject, String rootElementURI, String rootElementName, OutputStream outputStream) throws XMLMarshalException, IOException {
OutputStreamWriter writer = new OutputStreamWriter(outputStream, getXmlMarshaller().getEncoding());
save(dataObject, rootElementURI, rootElementName, writer);
}
/**
* Serializes an XMLDocument as an XML document into the outputStream.
* If the DataObject's Type was defined by an XSD, the serialization
* will follow the XSD.
* Otherwise the serialization will follow the format as if an XSD
* were generated as defined by the SDO specification.
* The OutputStream will be flushed after writing.
* Does not perform validation to ensure compliance with an XSD.
* @param xmlDocument specifies XMLDocument to be saved
* @param outputStream specifies the OutputStream to write to.
* @param options implementation-specific options.
* @throws IOException for stream exceptions.
* @throws IllegalArgumentException if the dataObject tree
* is not closed or has no container.
*/
public void save(XMLDocument xmlDocument, OutputStream outputStream, Object options) throws IOException {
if (xmlDocument == null) {
throw new IllegalArgumentException(SDOException.cannotPerformOperationWithNullInputParameter("save", "xmlDocument"));
}
String encoding = this.getXmlMarshaller().getEncoding();
if(xmlDocument.getEncoding() != null) {
encoding = xmlDocument.getEncoding();
}
OutputStreamWriter writer = new OutputStreamWriter(outputStream, encoding);
save(xmlDocument, writer, options);
}
/**
* Serializes an XMLDocument as an XML document into the outputWriter.
* If the DataObject's Type was defined by an XSD, the serialization
* will follow the XSD.
* Otherwise the serialization will follow the format as if an XSD
* were generated as defined by the SDO specification.
* The OutputStream will be flushed after writing.
* Does not perform validation to ensure compliance with an XSD.
* @param xmlDocument specifies XMLDocument to be saved
* @param outputWriter specifies the Writer to write to.
* @param options implementation-specific options.
* @throws IOException for stream exceptions.
* @throws IllegalArgumentException if the dataObject tree
* is not closed or has no container.
*/
public void save(XMLDocument xmlDocument, Writer outputWriter, Object options) throws IOException {
if (xmlDocument == null) {
throw new IllegalArgumentException(SDOException.cannotPerformOperationWithNullInputParameter("save", "xmlDocument"));
}
// get XMLMarshaller once - as we may create a new instance if this helper isDirty=true
XMLMarshaller anXMLMarshaller = getXmlMarshaller();
// Ask the SDOXMLDocument if we should include the XML declaration in the resulting XML
anXMLMarshaller.setFragment(!xmlDocument.isXMLDeclaration());
anXMLMarshaller.setEncoding(xmlDocument.getEncoding());
anXMLMarshaller.setSchemaLocation(xmlDocument.getSchemaLocation());
anXMLMarshaller.setNoNamespaceSchemaLocation(xmlDocument.getNoNamespaceSchemaLocation());
WriterRecord writerRecord;
if(anXMLMarshaller.isFormattedOutput()) {
writerRecord = new FormattedWriterRecord();
} else {
writerRecord = new WriterRecord();
}
writerRecord.setWriter(outputWriter);
writerRecord.setMarshaller(anXMLMarshaller);
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setMarshalledObject(xmlDocument.getRootObject());
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setMarshalledObjectRootQName(new QName(xmlDocument.getRootElementURI(), xmlDocument.getRootElementName()));
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setRootMarshalReocrd(writerRecord);
anXMLMarshaller.marshal(xmlDocument, writerRecord);
outputWriter.flush();
}
public void save(XMLDocument xmlDocument, Result result, Object options) throws IOException {
if (xmlDocument == null) {
throw new IllegalArgumentException(SDOException.cannotPerformOperationWithNullInputParameter("save", "xmlDocument"));
}
if (result instanceof StreamResult) {
StreamResult streamResult = (StreamResult)result;
Writer writer = streamResult.getWriter();
if (null == writer) {
save(xmlDocument, streamResult.getOutputStream(), options);
} else {
save(xmlDocument, writer, options);
}
} else {
// get XMLMarshaller once - as we may create a new instance if this helper isDirty=true
XMLMarshaller anXMLMarshaller = getXmlMarshaller();
// Ask the SDOXMLDocument if we should include the XML declaration in the resulting XML
anXMLMarshaller.setFragment(!xmlDocument.isXMLDeclaration());
anXMLMarshaller.setEncoding(xmlDocument.getEncoding());
anXMLMarshaller.setSchemaLocation(xmlDocument.getSchemaLocation());
anXMLMarshaller.setNoNamespaceSchemaLocation(xmlDocument.getNoNamespaceSchemaLocation());
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setMarshalledObject(xmlDocument.getRootObject());
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setMarshalledObjectRootQName(new QName(xmlDocument.getRootElementURI(), xmlDocument.getRootElementName()));
if(result instanceof SAXResult) {
ContentHandlerRecord marshalRecord = new ContentHandlerRecord();
marshalRecord.setContentHandler(((SAXResult)result).getHandler());
marshalRecord.setMarshaller(anXMLMarshaller);
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setRootMarshalReocrd(marshalRecord);
anXMLMarshaller.marshal(xmlDocument, marshalRecord);
} else if(result instanceof DOMResult) {
NodeRecord marshalRecord = new NodeRecord();
marshalRecord.setDOM(((DOMResult)result).getNode());
marshalRecord.setMarshaller(anXMLMarshaller);
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setRootMarshalReocrd(marshalRecord);
anXMLMarshaller.marshal(xmlDocument, marshalRecord);
} else {
StringWriter writer = new StringWriter();
this.save(xmlDocument, writer, options);
String xml = writer.toString();
StreamSource source = new StreamSource(new java.io.StringReader(xml));
anXMLMarshaller.getTransformer().transform(source, result);
}
}
}
/**
* Creates an XMLDocument with the specified XML rootElement for the DataObject.
* @param dataObject specifies DataObject to be saved
* @param rootElementURI the Target Namespace URI of the root XML element
* @param rootElementName the Name of the root XML element
* @return XMLDocument a new XMLDocument set with the specified parameters.
*/
public XMLDocument createDocument(DataObject dataObject, String rootElementURI, String rootElementName) {
SDOXMLDocument document = new SDOXMLDocument();
document.setRootObject(dataObject);
document.setRootElementURI(rootElementURI);
if (rootElementName != null) {
document.setRootElementName(rootElementName);
}
Property globalProp = getHelperContext().getXSDHelper().getGlobalProperty(rootElementURI, rootElementName, true);
if (null != globalProp) {
document.setSchemaType(((SDOType) globalProp.getType()).getXsdType());
}
document.setEncoding(SDOXMLDocument.DEFAULT_XML_ENCODING);
document.setXMLVersion(SDOXMLDocument.DEFAULT_XML_VERSION);
return document;
}
/**
* INTERNAL:
* Saves the DataObject as an XML document with the specified root element.
* Same as
* save(createDocument(dataObject, rootElementURI, rootElementName),
* writer, null);
*
* @param dataObject specifies DataObject to be saved
* @param rootElementURI the Target Namespace URI of the root XML element
* @param rootElementName the Name of the root XML element
* @param writer specifies the Writer to write to.
* @throws IOException for stream exceptions.
* @throws IllegalArgumentException if the dataObject tree
* is not closed or has no container.
*/
private void save(DataObject rootObject, String rootElementURI, String rootElementName, Writer writer) throws XMLMarshalException {
SDOXMLDocument xmlDocument = (SDOXMLDocument)createDocument(rootObject, rootElementURI, rootElementName);
// get XMLMarshaller once - as we may create a new instance if this helper isDirty=true
XMLMarshaller anXMLMarshaller = getXmlMarshaller();
// Ask the SDOXMLDocument if we should include the XML declaration in the resulting XML
anXMLMarshaller.setFragment(!xmlDocument.isXMLDeclaration());
WriterRecord writerRecord;
if(anXMLMarshaller.isFormattedOutput()) {
writerRecord = new FormattedWriterRecord();
} else {
writerRecord = new WriterRecord();
}
writerRecord.setWriter(writer);
writerRecord.setMarshaller(anXMLMarshaller);
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setMarshalledObject(rootObject);
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setMarshalledObjectRootQName(new QName(rootElementURI, rootElementName));
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setRootMarshalReocrd(writerRecord);
anXMLMarshaller.marshal(xmlDocument, writerRecord);
try {
writer.flush();
} catch(IOException ex) {
throw XMLMarshalException.marshalException(ex);
}
}
public void setLoader(SDOClassLoader loader) {
this.loader = loader;
getXmlConversionManager().setLoader(this.loader);
}
public SDOClassLoader getLoader() {
return loader;
}
public void setXmlContext(XMLContext xmlContext) {
this.xmlContext = xmlContext;
}
public synchronized XMLContext getXmlContext() {
if (xmlContext == null) {
xmlContext = new XMLContext(getTopLinkProject());
XMLConversionManager xmlConversionManager = getXmlConversionManager();
xmlConversionManager.setLoader(this.loader);
xmlConversionManager.setTimeZone(TimeZone.getTimeZone("GMT"));
xmlConversionManager.setTimeZoneQualified(true);
}
return xmlContext;
}
public void initializeDescriptor(XMLDescriptor descriptor){
AbstractSession theSession = (AbstractSession)getXmlContext().getSession(0);
//do initialization for new descriptor;
descriptor.preInitialize(theSession);
descriptor.initialize(theSession);
descriptor.postInitialize(theSession);
descriptor.getObjectBuilder().initializePrimaryKey(theSession);
getXmlContext().storeXMLDescriptorByQName(descriptor);
}
public void addDescriptors(List types) {
for (int i = 0; i < types.size(); i++) {
SDOType nextType = (SDOType)types.get(i);
if (!nextType.isDataType() && nextType.isFinalized()){
XMLDescriptor nextDescriptor = nextType.getXmlDescriptor();
getTopLinkProject().addDescriptor(nextDescriptor);
}
}
for (int i = 0; i < types.size(); i++) {
SDOType nextType = (SDOType)types.get(i);
if (!nextType.isDataType() && nextType.isFinalized()){
XMLDescriptor nextDescriptor = nextType.getXmlDescriptor();
initializeDescriptor(nextDescriptor);
}
}
}
public void setTopLinkProject(Project toplinkProject) {
this.topLinkProject = toplinkProject;
this.xmlContext = null;
this.xmlMarshallerMap.clear();
this.xmlUnmarshallerMap.clear();
}
public Project getTopLinkProject() {
if (topLinkProject == null) {
topLinkProject = new Project();
XMLLogin xmlLogin = new XMLLogin();
xmlLogin.setEqualNamespaceResolvers(false);
topLinkProject.setDatasourceLogin(xmlLogin);
// 200606_changeSummary
NamespaceResolver nr = new NamespaceResolver();
SDOTypeHelper sdoTypeHelper = (SDOTypeHelper) aHelperContext.getTypeHelper();
String sdoPrefix = sdoTypeHelper.getPrefix(SDOConstants.SDO_URL);
nr.put(sdoPrefix, SDOConstants.SDO_URL);
SDOType changeSummaryType = (SDOType) sdoTypeHelper.getType(SDOConstants.SDO_URL, SDOConstants.CHANGESUMMARY);
changeSummaryType.getXmlDescriptor().setNamespaceResolver(nr);
topLinkProject.addDescriptor(changeSummaryType.getXmlDescriptor());
SDOType openSequencedType = (SDOType) aHelperContext.getTypeHelper().getType(SDOConstants.ORACLE_SDO_URL, "OpenSequencedType");
topLinkProject.addDescriptor(openSequencedType.getXmlDescriptor());
SDOTypeType typeType = (SDOTypeType)aHelperContext.getTypeHelper().getType(SDOConstants.SDO_URL, SDOConstants.TYPE);
typeType.getXmlDescriptor().setNamespaceResolver(nr);
if(!typeType.isInitialized()) {
typeType.initializeMappings();
}
topLinkProject.addDescriptor(typeType.getXmlDescriptor());
SDOPropertyType propertyType = (SDOPropertyType)aHelperContext.getTypeHelper().getType(SDOConstants.SDO_URL, SDOConstants.PROPERTY);
if(!propertyType.isInitialized()) {
propertyType.initializeMappings();
}
topLinkProject.addDescriptor(propertyType.getXmlDescriptor());
((SDOTypeHelper)aHelperContext.getTypeHelper()).addWrappersToProject(topLinkProject);
}
return topLinkProject;
}
public void setXmlMarshaller(XMLMarshaller xmlMarshaller) {
this.xmlMarshallerMap.put(Thread.currentThread(), xmlMarshaller);
}
public XMLMarshaller getXmlMarshaller() {
XMLMarshaller marshaller = xmlMarshallerMap.get(Thread.currentThread());
if (marshaller == null) {
marshaller = getXmlContext().createMarshaller();
marshaller.setMarshalListener(new SDOMarshalListener(marshaller, (SDOTypeHelper) aHelperContext.getTypeHelper()));
xmlMarshallerMap.put(Thread.currentThread(), marshaller);
}
XMLContext context = getXmlContext();
if (marshaller.getXMLContext() != context) {
marshaller.setXMLContext(context);
}
return marshaller;
}
public void setXmlUnmarshaller(XMLUnmarshaller xmlUnmarshaller) {
this.xmlUnmarshallerMap.put(Thread.currentThread(), xmlUnmarshaller);
}
public XMLUnmarshaller getXmlUnmarshaller() {
XMLUnmarshaller unmarshaller = xmlUnmarshallerMap.get(Thread.currentThread());
if (unmarshaller == null) {
unmarshaller = getXmlContext().createUnmarshaller();
unmarshaller.getProperties().put(SDOConstants.SDO_HELPER_CONTEXT, aHelperContext);
unmarshaller.setUnmappedContentHandlerClass(SDOUnmappedContentHandler.class);
unmarshaller.setUnmarshalListener(new SDOUnmarshalListener(aHelperContext));
unmarshaller.setResultAlwaysXMLRoot(true);
xmlUnmarshallerMap.put(Thread.currentThread(), unmarshaller);
}
XMLContext context = getXmlContext();
if (unmarshaller.getXMLContext() != context) {
unmarshaller.setXMLContext(context);
}
return unmarshaller;
}
public void reset() {
setTopLinkProject(null);
setXmlContext(null);
this.xmlMarshallerMap.clear();
this.xmlUnmarshallerMap.clear();
setLoader(new SDOClassLoader(getClass().getClassLoader(), aHelperContext));
}
public HelperContext getHelperContext() {
return aHelperContext;
}
public void setHelperContext(HelperContext helperContext) {
aHelperContext = helperContext;
}
private void handleXMLMarshalException(XMLMarshalException xmlException) throws IOException {
if(xmlException.getErrorCode() == XMLMarshalException.NO_DESCRIPTOR_WITH_MATCHING_ROOT_ELEMENT || xmlException.getErrorCode() == XMLMarshalException.DESCRIPTOR_NOT_FOUND_IN_PROJECT){
throw SDOException.globalPropertyNotFound();
} else if (xmlException.getCause() instanceof IOException) {
throw (IOException) xmlException.getCause();
} else{
throw xmlException;
}
}
public XMLConversionManager getXmlConversionManager() {
return (XMLConversionManager)getXmlContext().getSession(0).getDatasourceLogin().getDatasourcePlatform().getConversionManager();
}
}
| sdo/org.eclipse.persistence.sdo/src/org/eclipse/persistence/sdo/helper/delegates/SDOXMLHelperDelegate.java | /*******************************************************************************
* Copyright (c) 1998, 2009 Oracle. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.sdo.helper.delegates;
import commonj.sdo.DataObject;
import commonj.sdo.Property;
import commonj.sdo.helper.HelperContext;
import commonj.sdo.helper.XMLDocument;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.WeakHashMap;
import javax.xml.namespace.QName;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.eclipse.persistence.sdo.SDOConstants;
import org.eclipse.persistence.sdo.SDOType;
import org.eclipse.persistence.sdo.SDOXMLDocument;
import org.eclipse.persistence.sdo.helper.SDOUnmappedContentHandler;
import org.eclipse.persistence.sdo.helper.SDOClassLoader;
import org.eclipse.persistence.sdo.helper.SDOMarshalListener;
import org.eclipse.persistence.sdo.helper.SDOTypeHelper;
import org.eclipse.persistence.sdo.helper.SDOUnmarshalListener;
import org.eclipse.persistence.sdo.helper.SDOXMLHelper;
import org.eclipse.persistence.sdo.types.SDOPropertyType;
import org.eclipse.persistence.sdo.types.SDOTypeType;
import org.eclipse.persistence.exceptions.SDOException;
import org.eclipse.persistence.exceptions.XMLMarshalException;
import org.eclipse.persistence.internal.oxm.XMLConversionManager;
import org.eclipse.persistence.internal.sessions.AbstractSession;
import org.eclipse.persistence.oxm.NamespaceResolver;
import org.eclipse.persistence.oxm.XMLContext;
import org.eclipse.persistence.oxm.XMLDescriptor;
import org.eclipse.persistence.oxm.XMLLogin;
import org.eclipse.persistence.oxm.XMLMarshaller;
import org.eclipse.persistence.oxm.XMLRoot;
import org.eclipse.persistence.oxm.XMLUnmarshaller;
import org.eclipse.persistence.oxm.record.ContentHandlerRecord;
import org.eclipse.persistence.oxm.record.FormattedWriterRecord;
import org.eclipse.persistence.oxm.record.NodeRecord;
import org.eclipse.persistence.oxm.record.WriterRecord;
import org.eclipse.persistence.sessions.Project;
import org.xml.sax.InputSource;
/**
* <p><b>Purpose</b>: Helper to XML documents into DataObects and DataObjects into XML documents.
* <p><b>Responsibilities</b>:<ul>
* <li> Load methods create commonj.sdo.XMLDocument objects from XML (unmarshal)
* <li> Save methods create XML from commonj.sdo.XMLDocument and commonj.sdo.DataObject objects (marshal)
* </ul>
*/
public class SDOXMLHelperDelegate implements SDOXMLHelper {
private SDOClassLoader loader;
private XMLContext xmlContext;
private Map<Thread, XMLMarshaller> xmlMarshallerMap;
private Map<Thread, XMLUnmarshaller> xmlUnmarshallerMap;
private Project topLinkProject;
// hold the context containing all helpers so that we can preserve inter-helper relationships
private HelperContext aHelperContext;
public SDOXMLHelperDelegate(HelperContext aContext) {
this(aContext, Thread.currentThread().getContextClassLoader());
}
public SDOXMLHelperDelegate(HelperContext aContext, ClassLoader aClassLoader) {
aHelperContext = aContext;
// This ClassLoader is internal to SDO so no inter servlet-ejb container context issues should arise
loader = new SDOClassLoader(aClassLoader, aContext);
xmlMarshallerMap = new WeakHashMap<Thread, XMLMarshaller>();
xmlUnmarshallerMap = new WeakHashMap<Thread, XMLUnmarshaller>();
}
/**
* The specified TimeZone will be used for all String to date object
* conversions. By default the TimeZone from the JVM is used.
*/
public void setTimeZone(TimeZone timeZone) {
getXmlConversionManager().setTimeZone(timeZone);
}
/**
* By setting this flag to true the marshalled date objects marshalled to
* the XML schema types time and dateTime will be qualified by a time zone.
* By default time information is not time zone qualified.
*/
public void setTimeZoneQualified(boolean timeZoneQualified) {
getXmlConversionManager().setTimeZoneQualified(timeZoneQualified);
}
/**
* Creates and returns an XMLDocument from the input String.
* By default does not perform XSD validation.
* Same as
* load(new StringReader(inputString), null, null);
*
* @param inputString specifies the String to read from
* @return the new XMLDocument loaded
* @throws RuntimeException for errors in XML parsing or
* implementation-specific validation.
*/
public XMLDocument load(String inputString) {
StringReader reader = new StringReader(inputString);
try {
return load(reader, null, null);
} catch (IOException ioException) {
ioException.printStackTrace();
return null;
}
}
/**
* Creates and returns an XMLDocument from the inputStream.
* The InputStream will be closed after reading.
* By default does not perform XSD validation.
* Same as
* load(inputStream, null, null);
*
* @param inputStream specifies the InputStream to read from
* @return the new XMLDocument loaded
* @throws IOException for stream exceptions.
* @throws RuntimeException for errors in XML parsing or
* implementation-specific validation.
*/
public XMLDocument load(InputStream inputStream) throws IOException {
return load(inputStream, null, null);
}
/**
* Creates and returns an XMLDocument from the inputStream.
* The InputStream will be closed after reading.
* By default does not perform XSD validation.
* @param inputStream specifies the InputStream to read from
* @param locationURI specifies the URI of the document for relative schema locations
* @param options implementation-specific options.
* @return the new XMLDocument loaded
* @throws IOException for stream exceptions.
* @throws RuntimeException for errors in XML parsing or
* implementation-specific validation.
*/
public XMLDocument load(InputStream inputStream, String locationURI, Object options) throws IOException {
InputSource inputSource = new InputSource(inputStream);
return load(inputSource, locationURI, options);
}
/**
* Creates and returns an XMLDocument from the inputSource.
* The InputSource will be closed after reading.
* By default does not perform XSD validation.
* @param inputSource specifies the InputSource to read from
* @param locationURI specifies the URI of the document for relative schema locations
* @param options implementation-specific options.
* @return the new XMLDocument loaded
* @throws IOException for stream exceptions.
* @throws RuntimeException for errors in XML parsing or
* implementation-specific validation.
*/
public XMLDocument load(InputSource inputSource, String locationURI, Object options) throws IOException {
// get XMLUnmarshaller once - as we may create a new instance if this helper isDirty=true
XMLUnmarshaller anXMLUnmarshaller = getXmlUnmarshaller();
Object unmarshalledObject = null;
if (options == null) {
try {
unmarshalledObject = anXMLUnmarshaller.unmarshal(inputSource);
} catch(XMLMarshalException xmlException){
handleXMLMarshalException(xmlException);
}
} else {
try {
DataObject optionsDataObject = (DataObject)options;
try {
SDOType theType = (SDOType)optionsDataObject.get(SDOConstants.TYPE_LOAD_OPTION);
try{
if (theType != null) {
unmarshalledObject = anXMLUnmarshaller.unmarshal(inputSource, theType.getImplClass());
}else{
unmarshalledObject = anXMLUnmarshaller.unmarshal(inputSource);
}
} catch(XMLMarshalException xmlException){
handleXMLMarshalException(xmlException);
}
} catch (ClassCastException ccException) {
throw SDOException.typePropertyMustBeAType(ccException);
}
} catch (ClassCastException ccException) {
throw SDOException.optionsMustBeADataObject(ccException, SDOConstants.ORACLE_SDO_URL ,SDOConstants.XMLHELPER_LOAD_OPTIONS);
}
}
if (unmarshalledObject instanceof XMLRoot) {
XMLRoot xmlRoot = (XMLRoot)unmarshalledObject;
XMLDocument xmlDocument = createDocument((DataObject)((XMLRoot)unmarshalledObject).getObject(), ((XMLRoot)unmarshalledObject).getNamespaceURI(), ((XMLRoot)unmarshalledObject).getLocalName());
if(xmlRoot.getEncoding() != null) {
xmlDocument.setEncoding(xmlRoot.getEncoding());
}
if(xmlRoot.getXMLVersion() != null) {
xmlDocument.setXMLVersion(xmlRoot.getXMLVersion());
}
xmlDocument.setSchemaLocation(xmlRoot.getSchemaLocation());
xmlDocument.setNoNamespaceSchemaLocation(xmlRoot.getNoNamespaceSchemaLocation());
return xmlDocument;
} else if (unmarshalledObject instanceof DataObject) {
String localName = ((SDOType)((DataObject)unmarshalledObject).getType()).getXmlDescriptor().getDefaultRootElement();
if (localName == null) {
localName = ((SDOType)((DataObject)unmarshalledObject).getType()).getXsdLocalName();
}
return createDocument((DataObject)unmarshalledObject, ((DataObject)unmarshalledObject).getType().getURI(), localName);
} else if (unmarshalledObject instanceof XMLDocument) {
return (XMLDocument)unmarshalledObject;
}
return null;
}
/**
* Creates and returns an XMLDocument from the inputReader.
* The InputStream will be closed after reading.
* By default does not perform XSD validation.
* @param inputReader specifies the Reader to read from
* @param locationURI specifies the URI of the document for relative schema locations
* @param options implementation-specific options.
* @return the new XMLDocument loaded
* @throws IOException for stream exceptions.
* @throws RuntimeException for errors in XML parsing or
* implementation-specific validation.
*/
public XMLDocument load(Reader inputReader, String locationURI, Object options) throws IOException {
InputSource inputSource = new InputSource(inputReader);
return load(inputSource, locationURI, options);
}
public XMLDocument load(Source source, String locationURI, Object options) throws IOException {
// get XMLUnmarshaller once - as we may create a new instance if this helper isDirty=true
XMLUnmarshaller anXMLUnmarshaller = getXmlUnmarshaller();
Object unmarshalledObject = null;
if (options == null) {
try {
unmarshalledObject = anXMLUnmarshaller.unmarshal(source);
} catch(XMLMarshalException xmlException){
handleXMLMarshalException(xmlException);
}
} else {
try {
DataObject optionsDataObject = (DataObject)options;
try {
SDOType theType = (SDOType)optionsDataObject.get(SDOConstants.TYPE_LOAD_OPTION);
try{
if (theType != null) {
unmarshalledObject = anXMLUnmarshaller.unmarshal(source, theType.getImplClass());
}else{
unmarshalledObject = anXMLUnmarshaller.unmarshal(source);
}
} catch(XMLMarshalException xmlException){
handleXMLMarshalException(xmlException);
}
} catch (ClassCastException ccException) {
throw SDOException.typePropertyMustBeAType(ccException);
}
} catch (ClassCastException ccException) {
throw SDOException.optionsMustBeADataObject(ccException, SDOConstants.ORACLE_SDO_URL ,SDOConstants.XMLHELPER_LOAD_OPTIONS);
}
}
if (unmarshalledObject instanceof XMLRoot) {
XMLRoot xmlRoot = (XMLRoot)unmarshalledObject;
XMLDocument xmlDocument = createDocument((DataObject)((XMLRoot)unmarshalledObject).getObject(), ((XMLRoot)unmarshalledObject).getNamespaceURI(), ((XMLRoot)unmarshalledObject).getLocalName());
if(xmlRoot.getEncoding() != null) {
xmlDocument.setEncoding(xmlRoot.getEncoding());
}
if(xmlRoot.getXMLVersion() != null) {
xmlDocument.setXMLVersion(xmlRoot.getXMLVersion());
}
xmlDocument.setSchemaLocation(xmlRoot.getSchemaLocation());
xmlDocument.setNoNamespaceSchemaLocation(xmlRoot.getNoNamespaceSchemaLocation());
return xmlDocument;
} else if (unmarshalledObject instanceof DataObject) {
DataObject unmarshalledDataObject = (DataObject)unmarshalledObject;
String localName = ((SDOType)((DataObject)unmarshalledObject).getType()).getXmlDescriptor().getDefaultRootElement();
if (localName == null) {
localName = ((SDOType)((DataObject)unmarshalledObject).getType()).getXsdLocalName();
}
return createDocument(unmarshalledDataObject, unmarshalledDataObject.getType().getURI(), localName);
} else if (unmarshalledObject instanceof XMLDocument) {
return (XMLDocument)unmarshalledObject;
}
return null;
}
/**
* Returns the DataObject saved as an XML document with the specified root element.
* Same as
* StringWriter stringWriter = new StringWriter();
* save(createDocument(dataObject, rootElementURI, rootElementName),
* stringWriter, null);
* stringWriter.toString();
*
* @param dataObject specifies DataObject to be saved
* @param rootElementURI the Target Namespace URI of the root XML element
* @param rootElementName the Name of the root XML element
* @return the saved XML document as a string
* @throws IllegalArgumentException if the dataObject tree
* is not closed or has no container.
*/
public String save(DataObject dataObject, String rootElementURI, String rootElementName) {
try {
StringWriter writer = new StringWriter();
save(dataObject, rootElementURI, rootElementName, writer);
return writer.toString();
} catch (XMLMarshalException e) {
throw SDOException.xmlMarshalExceptionOccurred(e, rootElementURI, rootElementName);
}
}
/**
* Saves the DataObject as an XML document with the specified root element.
* Same as
* save(createDocument(dataObject, rootElementURI, rootElementName),
* outputStream, null);
*
* @param dataObject specifies DataObject to be saved
* @param rootElementURI the Target Namespace URI of the root XML element
* @param rootElementName the Name of the root XML element
* @param outputStream specifies the OutputStream to write to.
* @throws IOException for stream exceptions.
* @throws IllegalArgumentException if the dataObject tree
* is not closed or has no container.
*/
public void save(DataObject dataObject, String rootElementURI, String rootElementName, OutputStream outputStream) throws XMLMarshalException, IOException {
OutputStreamWriter writer = new OutputStreamWriter(outputStream, getXmlMarshaller().getEncoding());
save(dataObject, rootElementURI, rootElementName, writer);
}
/**
* Serializes an XMLDocument as an XML document into the outputStream.
* If the DataObject's Type was defined by an XSD, the serialization
* will follow the XSD.
* Otherwise the serialization will follow the format as if an XSD
* were generated as defined by the SDO specification.
* The OutputStream will be flushed after writing.
* Does not perform validation to ensure compliance with an XSD.
* @param xmlDocument specifies XMLDocument to be saved
* @param outputStream specifies the OutputStream to write to.
* @param options implementation-specific options.
* @throws IOException for stream exceptions.
* @throws IllegalArgumentException if the dataObject tree
* is not closed or has no container.
*/
public void save(XMLDocument xmlDocument, OutputStream outputStream, Object options) throws IOException {
if (xmlDocument == null) {
throw new IllegalArgumentException(SDOException.cannotPerformOperationWithNullInputParameter("save", "xmlDocument"));
}
String encoding = this.getXmlMarshaller().getEncoding();
if(xmlDocument.getEncoding() != null) {
encoding = xmlDocument.getEncoding();
}
OutputStreamWriter writer = new OutputStreamWriter(outputStream, encoding);
save(xmlDocument, writer, options);
}
/**
* Serializes an XMLDocument as an XML document into the outputWriter.
* If the DataObject's Type was defined by an XSD, the serialization
* will follow the XSD.
* Otherwise the serialization will follow the format as if an XSD
* were generated as defined by the SDO specification.
* The OutputStream will be flushed after writing.
* Does not perform validation to ensure compliance with an XSD.
* @param xmlDocument specifies XMLDocument to be saved
* @param outputWriter specifies the Writer to write to.
* @param options implementation-specific options.
* @throws IOException for stream exceptions.
* @throws IllegalArgumentException if the dataObject tree
* is not closed or has no container.
*/
public void save(XMLDocument xmlDocument, Writer outputWriter, Object options) throws IOException {
if (xmlDocument == null) {
throw new IllegalArgumentException(SDOException.cannotPerformOperationWithNullInputParameter("save", "xmlDocument"));
}
// get XMLMarshaller once - as we may create a new instance if this helper isDirty=true
XMLMarshaller anXMLMarshaller = getXmlMarshaller();
// Ask the SDOXMLDocument if we should include the XML declaration in the resulting XML
anXMLMarshaller.setFragment(!xmlDocument.isXMLDeclaration());
anXMLMarshaller.setEncoding(xmlDocument.getEncoding());
anXMLMarshaller.setSchemaLocation(xmlDocument.getSchemaLocation());
anXMLMarshaller.setNoNamespaceSchemaLocation(xmlDocument.getNoNamespaceSchemaLocation());
WriterRecord writerRecord;
if(anXMLMarshaller.isFormattedOutput()) {
writerRecord = new FormattedWriterRecord();
} else {
writerRecord = new WriterRecord();
}
writerRecord.setWriter(outputWriter);
writerRecord.setMarshaller(anXMLMarshaller);
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setMarshalledObject(xmlDocument.getRootObject());
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setMarshalledObjectRootQName(new QName(xmlDocument.getRootElementURI(), xmlDocument.getRootElementName()));
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setRootMarshalReocrd(writerRecord);
anXMLMarshaller.marshal(xmlDocument, writerRecord);
outputWriter.flush();
}
public void save(XMLDocument xmlDocument, Result result, Object options) throws IOException {
if (xmlDocument == null) {
throw new IllegalArgumentException(SDOException.cannotPerformOperationWithNullInputParameter("save", "xmlDocument"));
}
if (result instanceof StreamResult) {
StreamResult streamResult = (StreamResult)result;
Writer writer = streamResult.getWriter();
if (null == writer) {
save(xmlDocument, streamResult.getOutputStream(), options);
} else {
save(xmlDocument, writer, options);
}
} else {
// get XMLMarshaller once - as we may create a new instance if this helper isDirty=true
XMLMarshaller anXMLMarshaller = getXmlMarshaller();
// Ask the SDOXMLDocument if we should include the XML declaration in the resulting XML
anXMLMarshaller.setFragment(!xmlDocument.isXMLDeclaration());
anXMLMarshaller.setEncoding(xmlDocument.getEncoding());
anXMLMarshaller.setSchemaLocation(xmlDocument.getSchemaLocation());
anXMLMarshaller.setNoNamespaceSchemaLocation(xmlDocument.getNoNamespaceSchemaLocation());
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setMarshalledObject(xmlDocument.getRootObject());
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setMarshalledObjectRootQName(new QName(xmlDocument.getRootElementURI(), xmlDocument.getRootElementName()));
if(result instanceof SAXResult) {
ContentHandlerRecord marshalRecord = new ContentHandlerRecord();
marshalRecord.setContentHandler(((SAXResult)result).getHandler());
marshalRecord.setMarshaller(anXMLMarshaller);
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setRootMarshalReocrd(marshalRecord);
anXMLMarshaller.marshal(xmlDocument, marshalRecord);
} else if(result instanceof DOMResult) {
NodeRecord marshalRecord = new NodeRecord();
marshalRecord.setDOM(((DOMResult)result).getNode());
marshalRecord.setMarshaller(anXMLMarshaller);
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setRootMarshalReocrd(marshalRecord);
anXMLMarshaller.marshal(xmlDocument, marshalRecord);
} else {
StringWriter writer = new StringWriter();
this.save(xmlDocument, writer, options);
String xml = writer.toString();
StreamSource source = new StreamSource(new java.io.StringReader(xml));
anXMLMarshaller.getTransformer().transform(source, result);
}
}
}
/**
* Creates an XMLDocument with the specified XML rootElement for the DataObject.
* @param dataObject specifies DataObject to be saved
* @param rootElementURI the Target Namespace URI of the root XML element
* @param rootElementName the Name of the root XML element
* @return XMLDocument a new XMLDocument set with the specified parameters.
*/
public XMLDocument createDocument(DataObject dataObject, String rootElementURI, String rootElementName) {
SDOXMLDocument document = new SDOXMLDocument();
document.setRootObject(dataObject);
document.setRootElementURI(rootElementURI);
if (rootElementName != null) {
document.setRootElementName(rootElementName);
}
Property globalProp = getHelperContext().getXSDHelper().getGlobalProperty(rootElementURI, rootElementName, true);
if (null != globalProp) {
document.setSchemaType(((SDOType) globalProp.getType()).getXsdType());
}
document.setEncoding(SDOXMLDocument.DEFAULT_XML_ENCODING);
document.setXMLVersion(SDOXMLDocument.DEFAULT_XML_VERSION);
return document;
}
/**
* INTERNAL:
* Saves the DataObject as an XML document with the specified root element.
* Same as
* save(createDocument(dataObject, rootElementURI, rootElementName),
* writer, null);
*
* @param dataObject specifies DataObject to be saved
* @param rootElementURI the Target Namespace URI of the root XML element
* @param rootElementName the Name of the root XML element
* @param writer specifies the Writer to write to.
* @throws IOException for stream exceptions.
* @throws IllegalArgumentException if the dataObject tree
* is not closed or has no container.
*/
private void save(DataObject rootObject, String rootElementURI, String rootElementName, Writer writer) throws XMLMarshalException {
SDOXMLDocument xmlDocument = (SDOXMLDocument)createDocument(rootObject, rootElementURI, rootElementName);
// get XMLMarshaller once - as we may create a new instance if this helper isDirty=true
XMLMarshaller anXMLMarshaller = getXmlMarshaller();
// Ask the SDOXMLDocument if we should include the XML declaration in the resulting XML
anXMLMarshaller.setFragment(!xmlDocument.isXMLDeclaration());
WriterRecord writerRecord;
if(anXMLMarshaller.isFormattedOutput()) {
writerRecord = new FormattedWriterRecord();
} else {
writerRecord = new WriterRecord();
}
writerRecord.setWriter(writer);
writerRecord.setMarshaller(anXMLMarshaller);
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setMarshalledObject(rootObject);
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setMarshalledObjectRootQName(new QName(rootElementURI, rootElementName));
((SDOMarshalListener)anXMLMarshaller.getMarshalListener()).setRootMarshalReocrd(writerRecord);
anXMLMarshaller.marshal(xmlDocument, writerRecord);
try {
writer.flush();
} catch(IOException ex) {
throw XMLMarshalException.marshalException(ex);
}
}
public void setLoader(SDOClassLoader loader) {
this.loader = loader;
getXmlConversionManager().setLoader(this.loader);
}
public SDOClassLoader getLoader() {
return loader;
}
public void setXmlContext(XMLContext xmlContext) {
this.xmlContext = xmlContext;
}
public synchronized XMLContext getXmlContext() {
if (xmlContext == null) {
xmlContext = new XMLContext(getTopLinkProject());
XMLConversionManager xmlConversionManager = getXmlConversionManager();
xmlConversionManager.setLoader(this.loader);
xmlConversionManager.setTimeZone(TimeZone.getTimeZone("GMT"));
xmlConversionManager.setTimeZoneQualified(true);
}
return xmlContext;
}
public void initializeDescriptor(XMLDescriptor descriptor){
AbstractSession theSession = (AbstractSession)getXmlContext().getSession(0);
//do initialization for new descriptor;
descriptor.preInitialize(theSession);
descriptor.initialize(theSession);
descriptor.postInitialize(theSession);
descriptor.getObjectBuilder().initializePrimaryKey(theSession);
getXmlContext().storeXMLDescriptorByQName(descriptor);
}
public void addDescriptors(List types) {
for (int i = 0; i < types.size(); i++) {
SDOType nextType = (SDOType)types.get(i);
if (!nextType.isDataType() && nextType.isFinalized()){
XMLDescriptor nextDescriptor = nextType.getXmlDescriptor();
getTopLinkProject().addDescriptor(nextDescriptor);
}
}
for (int i = 0; i < types.size(); i++) {
SDOType nextType = (SDOType)types.get(i);
if (!nextType.isDataType() && nextType.isFinalized()){
XMLDescriptor nextDescriptor = nextType.getXmlDescriptor();
initializeDescriptor(nextDescriptor);
}
}
}
public void setTopLinkProject(Project toplinkProject) {
this.topLinkProject = toplinkProject;
this.xmlContext = null;
this.xmlMarshallerMap.clear();
this.xmlUnmarshallerMap.clear();
}
public Project getTopLinkProject() {
if (topLinkProject == null) {
topLinkProject = new Project();
XMLLogin xmlLogin = new XMLLogin();
xmlLogin.setEqualNamespaceResolvers(false);
topLinkProject.setDatasourceLogin(xmlLogin);
// 200606_changeSummary
NamespaceResolver nr = new NamespaceResolver();
SDOTypeHelper sdoTypeHelper = (SDOTypeHelper) aHelperContext.getTypeHelper();
String sdoPrefix = sdoTypeHelper.getPrefix(SDOConstants.SDO_URL);
nr.put(sdoPrefix, SDOConstants.SDO_URL);
SDOType changeSummaryType = (SDOType) sdoTypeHelper.getType(SDOConstants.SDO_URL, SDOConstants.CHANGESUMMARY);
changeSummaryType.getXmlDescriptor().setNamespaceResolver(nr);
topLinkProject.addDescriptor(changeSummaryType.getXmlDescriptor());
SDOType openSequencedType = (SDOType) aHelperContext.getTypeHelper().getType(SDOConstants.ORACLE_SDO_URL, "OpenSequencedType");
topLinkProject.addDescriptor(openSequencedType.getXmlDescriptor());
SDOTypeType typeType = (SDOTypeType)aHelperContext.getTypeHelper().getType(SDOConstants.SDO_URL, SDOConstants.TYPE);
if(!typeType.isInitialized()) {
typeType.initializeMappings();
}
topLinkProject.addDescriptor(typeType.getXmlDescriptor());
SDOPropertyType propertyType = (SDOPropertyType)aHelperContext.getTypeHelper().getType(SDOConstants.SDO_URL, SDOConstants.PROPERTY);
if(!propertyType.isInitialized()) {
propertyType.initializeMappings();
}
topLinkProject.addDescriptor(propertyType.getXmlDescriptor());
((SDOTypeHelper)aHelperContext.getTypeHelper()).addWrappersToProject(topLinkProject);
}
return topLinkProject;
}
public void setXmlMarshaller(XMLMarshaller xmlMarshaller) {
this.xmlMarshallerMap.put(Thread.currentThread(), xmlMarshaller);
}
public XMLMarshaller getXmlMarshaller() {
XMLMarshaller marshaller = xmlMarshallerMap.get(Thread.currentThread());
if (marshaller == null) {
marshaller = getXmlContext().createMarshaller();
marshaller.setMarshalListener(new SDOMarshalListener(marshaller, (SDOTypeHelper) aHelperContext.getTypeHelper()));
xmlMarshallerMap.put(Thread.currentThread(), marshaller);
}
XMLContext context = getXmlContext();
if (marshaller.getXMLContext() != context) {
marshaller.setXMLContext(context);
}
return marshaller;
}
public void setXmlUnmarshaller(XMLUnmarshaller xmlUnmarshaller) {
this.xmlUnmarshallerMap.put(Thread.currentThread(), xmlUnmarshaller);
}
public XMLUnmarshaller getXmlUnmarshaller() {
XMLUnmarshaller unmarshaller = xmlUnmarshallerMap.get(Thread.currentThread());
if (unmarshaller == null) {
unmarshaller = getXmlContext().createUnmarshaller();
unmarshaller.getProperties().put(SDOConstants.SDO_HELPER_CONTEXT, aHelperContext);
unmarshaller.setUnmappedContentHandlerClass(SDOUnmappedContentHandler.class);
unmarshaller.setUnmarshalListener(new SDOUnmarshalListener(aHelperContext));
unmarshaller.setResultAlwaysXMLRoot(true);
xmlUnmarshallerMap.put(Thread.currentThread(), unmarshaller);
}
XMLContext context = getXmlContext();
if (unmarshaller.getXMLContext() != context) {
unmarshaller.setXMLContext(context);
}
return unmarshaller;
}
public void reset() {
setTopLinkProject(null);
setXmlContext(null);
this.xmlMarshallerMap.clear();
this.xmlUnmarshallerMap.clear();
setLoader(new SDOClassLoader(getClass().getClassLoader(), aHelperContext));
}
public HelperContext getHelperContext() {
return aHelperContext;
}
public void setHelperContext(HelperContext helperContext) {
aHelperContext = helperContext;
}
private void handleXMLMarshalException(XMLMarshalException xmlException) throws IOException {
if(xmlException.getErrorCode() == XMLMarshalException.NO_DESCRIPTOR_WITH_MATCHING_ROOT_ELEMENT || xmlException.getErrorCode() == XMLMarshalException.DESCRIPTOR_NOT_FOUND_IN_PROJECT){
throw SDOException.globalPropertyNotFound();
} else if (xmlException.getCause() instanceof IOException) {
throw (IOException) xmlException.getCause();
} else{
throw xmlException;
}
}
public XMLConversionManager getXmlConversionManager() {
return (XMLConversionManager)getXmlContext().getSession(0).getDatasourceLogin().getDatasourcePlatform().getConversionManager();
}
}
| Fix for failing SDO tests in the continuous build
Reviewed by Rick Barkhouse
| sdo/org.eclipse.persistence.sdo/src/org/eclipse/persistence/sdo/helper/delegates/SDOXMLHelperDelegate.java | Fix for failing SDO tests in the continuous build Reviewed by Rick Barkhouse |
|
Java | epl-1.0 | 5a0309ffeb2a770a3a5f750f32085bb3d90e70c4 | 0 | tx1103mark/controller,mandeepdhami/controller,aryantaheri/monitoring-controller,522986491/controller,aryantaheri/monitoring-controller,Sushma7785/OpenDayLight-Load-Balancer,tx1103mark/controller,my76128/controller,my76128/controller,tx1103mark/controller,Johnson-Chou/test,tx1103mark/controller,my76128/controller,aryantaheri/monitoring-controller,mandeepdhami/controller,my76128/controller,opendaylight/controller,Sushma7785/OpenDayLight-Load-Balancer,mandeepdhami/controller,522986491/controller,mandeepdhami/controller,aryantaheri/monitoring-controller,inocybe/odl-controller,Johnson-Chou/test,inocybe/odl-controller | /*
* Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.controller.md.sal.dom.api;
import com.google.common.base.Preconditions;
import java.io.Serializable;
import java.util.Iterator;
import javax.annotation.Nonnull;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.yangtools.concepts.Immutable;
import org.opendaylight.yangtools.concepts.Path;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
/**
* A unique identifier for a particular subtree. It is composed of the logical
* data store type and the instance identifier of the root node.
*/
public final class DOMDataTreeIdentifier implements Immutable, Path<DOMDataTreeIdentifier>, Serializable, Comparable<DOMDataTreeIdentifier> {
private static final long serialVersionUID = 1L;
private final YangInstanceIdentifier rootIdentifier;
private final LogicalDatastoreType datastoreType;
public DOMDataTreeIdentifier(final LogicalDatastoreType datastoreType, final YangInstanceIdentifier rootIdentifier) {
this.datastoreType = Preconditions.checkNotNull(datastoreType);
this.rootIdentifier = Preconditions.checkNotNull(rootIdentifier);
}
/**
* Return the logical data store type.
*
* @return Logical data store type. Guaranteed to be non-null.
*/
public @Nonnull LogicalDatastoreType getDatastoreType() {
return datastoreType;
}
/**
* Return the {@link YangInstanceIdentifier} of the root node.
*
* @return Instance identifier corresponding to the root node.
*/
public @Nonnull YangInstanceIdentifier getRootIdentifier() {
return rootIdentifier;
}
@Override
public boolean contains(final DOMDataTreeIdentifier other) {
return datastoreType == other.datastoreType && rootIdentifier.contains(other.rootIdentifier);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + datastoreType.hashCode();
result = prime * result + rootIdentifier.hashCode();
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof DOMDataTreeIdentifier)) {
return false;
}
DOMDataTreeIdentifier other = (DOMDataTreeIdentifier) obj;
if (datastoreType != other.datastoreType) {
return false;
}
return rootIdentifier.equals(other.rootIdentifier);
}
@Override
public int compareTo(final DOMDataTreeIdentifier o) {
int i = datastoreType.compareTo(o.datastoreType);
if (i != 0) {
return i;
}
final Iterator<PathArgument> mi = rootIdentifier.getPathArguments().iterator();
final Iterator<PathArgument> oi = o.rootIdentifier.getPathArguments().iterator();
while (mi.hasNext()) {
if (!oi.hasNext()) {
return 1;
}
final PathArgument ma = mi.next();
final PathArgument oa = oi.next();
i = ma.compareTo(oa);
if (i != 0) {
return i;
}
}
return oi.hasNext() ? -1 : 0;
}
}
| opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/md/sal/dom/api/DOMDataTreeIdentifier.java | /*
* Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.controller.md.sal.dom.api;
import com.google.common.base.Preconditions;
import java.io.Serializable;
import javax.annotation.Nonnull;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.yangtools.concepts.Immutable;
import org.opendaylight.yangtools.concepts.Path;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
/**
* A unique identifier for a particular subtree. It is composed of the logical
* data store type and the instance identifier of the root node.
*/
public final class DOMDataTreeIdentifier implements Immutable, Path<DOMDataTreeIdentifier>, Serializable {
private static final long serialVersionUID = 1L;
private final YangInstanceIdentifier rootIdentifier;
private final LogicalDatastoreType datastoreType;
public DOMDataTreeIdentifier(final LogicalDatastoreType datastoreType, final YangInstanceIdentifier rootIdentifier) {
this.datastoreType = Preconditions.checkNotNull(datastoreType);
this.rootIdentifier = Preconditions.checkNotNull(rootIdentifier);
}
/**
* Return the logical data store type.
*
* @return Logical data store type. Guaranteed to be non-null.
*/
public @Nonnull LogicalDatastoreType getDatastoreType() {
return datastoreType;
}
/**
* Return the {@link YangInstanceIdentifier} of the root node.
*
* @return Instance identifier corresponding to the root node.
*/
public @Nonnull YangInstanceIdentifier getRootIdentifier() {
return rootIdentifier;
}
@Override
public boolean contains(final DOMDataTreeIdentifier other) {
return datastoreType == other.datastoreType && rootIdentifier.contains(other.rootIdentifier);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + datastoreType.hashCode();
result = prime * result + rootIdentifier.hashCode();
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof DOMDataTreeIdentifier)) {
return false;
}
DOMDataTreeIdentifier other = (DOMDataTreeIdentifier) obj;
if (datastoreType != other.datastoreType) {
return false;
}
return rootIdentifier.equals(other.rootIdentifier);
}
}
| Make DOMDataTreeIdentifier implement Comparable
We can easily define total ordering on this class, which is useful for
maintaining order so that we can find the longest-prefix match easily by
iterating over the keys in the natural ordering.
Change-Id: Ie2f83ea494fe278df4acc1cb6059dae440ef8f37
Signed-off-by: Robert Varga <[email protected]>
| opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/md/sal/dom/api/DOMDataTreeIdentifier.java | Make DOMDataTreeIdentifier implement Comparable |
|
Java | mpl-2.0 | 68f12a3065fb18dacc934cf38fb46ac7f9968fd8 | 0 | PawelGutkowski/openmrs-module-webservices.rest,PawelGutkowski/openmrs-module-webservices.rest,PawelGutkowski/openmrs-module-webservices.rest | /**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.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://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.module.webservices.rest.web.v1_0.resource.openmrs1_10;
import java.util.Date;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.openmrs.CareSetting;
import org.openmrs.Order;
import org.openmrs.OrderType;
import org.openmrs.Patient;
import org.openmrs.api.OrderService;
import org.openmrs.api.context.Context;
public class OrderUtil {
private static final String INACTIVE = "inactive";
private static final String ANY = "any";
/**
* Gets the inactive orders of the specified patient as of the specified date, defaults to
* current date if no date is specified
*
* @param patient
* @param careSetting
* @param orderType
* @param asOfDate
* @return
*/
public static List<Order> getOrders(Patient patient, CareSetting careSetting, OrderType orderType, String status,
Date asOfDate, boolean includeVoided) {
OrderService os = Context.getOrderService();
if (!INACTIVE.equals(status) && !ANY.equals(status)) {
return os.getActiveOrders(patient, orderType, careSetting, asOfDate);
}
if (INACTIVE.equals(status)) {
includeVoided = false;
}
List<Order> orders = os.getOrders(patient, careSetting, orderType, includeVoided);
if (INACTIVE.equals(status)) {
removeActiveOrders(orders, asOfDate);
}
return orders;
}
private static void removeActiveOrders(List<Order> orders, final Date asOfDate) {
CollectionUtils.filter(orders, new Predicate() {
@Override
public boolean evaluate(Object object) {
return isDiscontinued((Order) object, asOfDate);
}
});
}
private static boolean isDiscontinued(Order order, Date asOfDate) {
if (asOfDate == null) {
asOfDate = new Date();
}
Date effectiveEndDate = order.getEffectiveStopDate();
if (effectiveEndDate == null) {
return false;
}
return effectiveEndDate.before(asOfDate);
}
}
| omod-1.10/src/main/java/org/openmrs/module/webservices/rest/web/v1_0/resource/openmrs1_10/OrderUtil.java | /**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.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://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.module.webservices.rest.web.v1_0.resource.openmrs1_10;
import java.util.Date;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.openmrs.CareSetting;
import org.openmrs.Order;
import org.openmrs.OrderType;
import org.openmrs.Patient;
import org.openmrs.api.OrderService;
import org.openmrs.api.context.Context;
public class OrderUtil {
private static final String INACTIVE = "inactive";
/**
* Gets the inactive orders of the specified patient as of the specified date, defaults to
* current date if no date is specified
*
* @param patient
* @param careSetting
* @param orderType
* @param asOfDate
* @return
*/
public static List<Order> getOrders(Patient patient, CareSetting careSetting, OrderType orderType, String status,
Date asOfDate, boolean includeVoided) {
OrderService os = Context.getOrderService();
if (!INACTIVE.equals(status) && !"any".equals(status)) {
return os.getActiveOrders(patient, orderType, careSetting, asOfDate);
}
if (INACTIVE.equals(status)) {
includeVoided = false;
}
List<Order> orders = os.getOrders(patient, careSetting, orderType, includeVoided);
if (INACTIVE.equals(status)) {
removeActiveOrders(orders, asOfDate);
}
return orders;
}
private static void removeActiveOrders(List<Order> orders, final Date asOfDate) {
CollectionUtils.filter(orders, new Predicate() {
@Override
public boolean evaluate(Object object) {
return isDiscontinued((Order) object, asOfDate);
}
});
}
private static boolean isDiscontinued(Order order, Date asOfDate) {
if (asOfDate == null) {
asOfDate = new Date();
}
Date effectiveEndDate = order.getEffectiveStopDate();
if (effectiveEndDate == null) {
return false;
}
return effectiveEndDate.before(asOfDate);
}
}
| Follow up to add constant for any in OrderUtil - RESTWS-465
| omod-1.10/src/main/java/org/openmrs/module/webservices/rest/web/v1_0/resource/openmrs1_10/OrderUtil.java | Follow up to add constant for any in OrderUtil - RESTWS-465 |
|
Java | agpl-3.0 | b3357e97e35d8e20a2f444d695a82afdf68229e7 | 0 | rakam-io/rakam,buremba/rakam,buremba/rakam,buremba/rakam,buremba/rakam,buremba/rakam,rakam-io/rakam,rakam-io/rakam | package org.rakam.postgresql.analysis;
import com.facebook.presto.sql.RakamSqlFormatter;
import com.google.common.collect.ImmutableList;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.rakam.analysis.FunnelQueryExecutor;
import org.rakam.collection.SchemaField;
import org.rakam.config.ProjectConfig;
import org.rakam.report.DelegateQueryExecution;
import org.rakam.report.QueryExecution;
import org.rakam.report.QueryExecutorService;
import org.rakam.report.QueryResult;
import org.rakam.util.RakamException;
import org.rakam.util.ValidationUtil;
import javax.inject.Inject;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static com.facebook.presto.sql.RakamExpressionFormatter.formatIdentifier;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static java.lang.String.format;
import static org.rakam.collection.FieldType.LONG;
import static org.rakam.collection.FieldType.STRING;
import static org.rakam.util.DateTimeUtils.TIMESTAMP_FORMATTER;
import static org.rakam.util.ValidationUtil.checkCollection;
import static org.rakam.util.ValidationUtil.checkTableColumn;
public class FastGenericFunnelQueryExecutor
implements FunnelQueryExecutor
{
private final ProjectConfig projectConfig;
private final QueryExecutorService executor;
@Inject
public FastGenericFunnelQueryExecutor(QueryExecutorService executor, ProjectConfig projectConfig)
{
this.projectConfig = projectConfig;
this.executor = executor;
}
@Override
public QueryExecution query(String project, List<FunnelStep> steps, Optional<String> dimension, LocalDate startDate, LocalDate endDate, Optional<FunnelWindow> window, ZoneId zoneId, Optional<List<String>> connectors, Optional<Boolean> ordered)
{
if (ordered.isPresent() && ordered.get()) {
throw new RakamException("Strict ordered funnel query is not supported", BAD_REQUEST);
}
if (dimension.isPresent() && connectors.isPresent() && connectors.get().contains(dimension)) {
throw new RakamException("Dimension and connector field cannot be equal", BAD_REQUEST);
}
List<String> selects = new ArrayList<>();
List<String> insideSelect = new ArrayList<>();
List<String> mainSelect = new ArrayList<>();
String connectorString = connectors.map(item -> item.stream().map(ValidationUtil::checkTableColumn).collect(Collectors.joining(", ")))
.orElse(checkTableColumn(projectConfig.getUserColumn()));
for (int i = 0; i < steps.size(); i++) {
Optional<String> filterExp = steps.get(i).getExpression().map(value -> RakamSqlFormatter.formatExpression(value,
name -> name.getParts().stream().map(e -> formatIdentifier(e, '"')).collect(Collectors.joining(".")),
name -> name.getParts().stream()
.map(e -> formatIdentifier(e, '"')).collect(Collectors.joining(".")), '"'));
if (i == 0) {
selects.add(format("sum(case when ts_event%d is not null then 1 else 0 end) as event%d_count", i, i));
}
else {
selects.add(format("sum(case when ts_event%d >= ts_event%d then 1 else 0 end) as event%d_count", i, i - 1, i));
}
insideSelect.add(format("min(case when step = %d then %s end) as ts_event%d", i, checkTableColumn(projectConfig.getTimeColumn()), i));
mainSelect.add(format("select %s %d as step, %s, %s from %s where %s between timestamp '%s' and timestamp '%s' and %s",
dimension.map(v -> v + ", ").orElse(""),
i,
connectorString,
checkTableColumn(projectConfig.getTimeColumn()),
checkCollection(steps.get(i).getCollection()),
checkTableColumn(projectConfig.getTimeColumn()),
TIMESTAMP_FORMATTER.format(startDate.atStartOfDay(zoneId)),
TIMESTAMP_FORMATTER.format(endDate.plusDays(1).atStartOfDay(zoneId)),
filterExp.orElse("true")));
}
String query = format("select %s %s\n" +
"from (select %s,\n" +
" %s %s" +
" from (\n" +
" %s" +
" ) t \n" +
" group by %s %s\n" +
" ) t %s",
dimension.map(v -> v + ", ").orElse(""),
selects.stream().collect(Collectors.joining(",\n")),
connectorString,
dimension.map(v -> v + ", ").orElse(""),
insideSelect.stream().collect(Collectors.joining(",\n")),
mainSelect.stream().collect(Collectors.joining(" UNION ALL\n")),
dimension.map(v -> v + ", ").orElse(""),
connectorString,
dimension.map(v -> " group by 1").orElse(""));
QueryExecution queryExecution = executor.executeQuery(project, query);
return new DelegateQueryExecution(queryExecution,
result -> {
if (result.isFailed()) {
return result;
}
List<List<Object>> newResult = new ArrayList<>();
List<SchemaField> metadata;
if (dimension.isPresent()) {
metadata = ImmutableList.of(
new SchemaField("step", STRING),
new SchemaField("dimension", STRING),
new SchemaField("count", LONG));
for (List<Object> objects : result.getResult()) {
for (int i = 0; i < steps.size(); i++) {
newResult.add(ImmutableList.of("Step " + (i + 1),
Optional.ofNullable(objects.get(0)).orElse("(not set)"),
Optional.ofNullable(objects.get(i + 1)).orElse(0)));
}
}
}
else {
metadata = ImmutableList.of(
new SchemaField("step", STRING),
new SchemaField("count", LONG));
List<Object> stepCount = result.getResult().get(0);
for (int i = 0; i < steps.size(); i++) {
Object value = stepCount.get(i);
newResult.add(ImmutableList.of("Step " + (i + 1), value == null ? 0 : value));
}
}
return new QueryResult(metadata, newResult, result.getProperties());
});
}
}
| rakam-postgresql/src/main/java/org/rakam/postgresql/analysis/FastGenericFunnelQueryExecutor.java | package org.rakam.postgresql.analysis;
import com.facebook.presto.sql.RakamSqlFormatter;
import com.google.common.collect.ImmutableList;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.rakam.analysis.FunnelQueryExecutor;
import org.rakam.collection.SchemaField;
import org.rakam.config.ProjectConfig;
import org.rakam.report.DelegateQueryExecution;
import org.rakam.report.QueryExecution;
import org.rakam.report.QueryExecutorService;
import org.rakam.report.QueryResult;
import org.rakam.util.RakamException;
import org.rakam.util.ValidationUtil;
import javax.inject.Inject;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static com.facebook.presto.sql.RakamExpressionFormatter.formatIdentifier;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static java.lang.String.format;
import static org.rakam.collection.FieldType.LONG;
import static org.rakam.collection.FieldType.STRING;
import static org.rakam.util.DateTimeUtils.TIMESTAMP_FORMATTER;
import static org.rakam.util.ValidationUtil.checkCollection;
import static org.rakam.util.ValidationUtil.checkTableColumn;
public class FastGenericFunnelQueryExecutor
implements FunnelQueryExecutor
{
private final ProjectConfig projectConfig;
private final QueryExecutorService executor;
@Inject
public FastGenericFunnelQueryExecutor(QueryExecutorService executor, ProjectConfig projectConfig)
{
this.projectConfig = projectConfig;
this.executor = executor;
}
@Override
public QueryExecution query(String project, List<FunnelStep> steps, Optional<String> dimension, LocalDate startDate, LocalDate endDate, Optional<FunnelWindow> window, ZoneId zoneId, Optional<List<String>> connectors, Optional<Boolean> ordered)
{
if(ordered.isPresent() && ordered.get()) {
throw new RakamException("Strict ordered funnel query is not supported", BAD_REQUEST);
}
if (dimension.isPresent() && connectors.isPresent() && connectors.get().contains(dimension)) {
throw new RakamException("Dimension and connector field cannot be equal", BAD_REQUEST);
}
List<String> selects = new ArrayList<>();
List<String> insideSelect = new ArrayList<>();
List<String> mainSelect = new ArrayList<>();
String connectorString = connectors.map(item -> item.stream().map(ValidationUtil::checkTableColumn).collect(Collectors.joining(", ")))
.orElse(checkTableColumn(projectConfig.getUserColumn()));
for (int i = 0; i < steps.size(); i++) {
Optional<String> filterExp = steps.get(i).getExpression().map(value -> RakamSqlFormatter.formatExpression(value,
name -> name.getParts().stream().map(e -> formatIdentifier(e, '"')).collect(Collectors.joining(".")),
name -> name.getParts().stream()
.map(e -> formatIdentifier(e, '"')).collect(Collectors.joining(".")), '"'));
selects.add(format("sum(case when ts_event%d is not null then 1 else 0 end) as event%d_count", i, i));
// selects.add(format("count(case when ts_event%d is not null then 1 else 0 end) as event%d_count", i, i));
insideSelect.add(format("min(case when step = %d then %s end) as ts_event%d", i, checkTableColumn(projectConfig.getTimeColumn()), i));
mainSelect.add(format("select %s %d as step, %s, %s from %s where %s between timestamp '%s' and timestamp '%s' and %s",
dimension.map(v -> v + ", ").orElse(""),
i,
connectorString,
checkTableColumn(projectConfig.getTimeColumn()),
checkCollection(steps.get(i).getCollection()),
checkTableColumn(projectConfig.getTimeColumn()),
TIMESTAMP_FORMATTER.format(startDate.atStartOfDay(zoneId)),
TIMESTAMP_FORMATTER.format(endDate.plusDays(1).atStartOfDay(zoneId)),
filterExp.orElse("true")));
}
String query = format("select %s %s\n" +
"from (select %s,\n" +
" %s %s" +
" from (\n" +
" %s" +
" ) t \n" +
" group by %s %s\n" +
" ) t %s",
dimension.map(v -> v + ", ").orElse(""),
selects.stream().collect(Collectors.joining(",\n")),
connectorString,
dimension.map(v -> v + ", ").orElse(""),
insideSelect.stream().collect(Collectors.joining(",\n")),
mainSelect.stream().collect(Collectors.joining(" UNION ALL\n")),
dimension.map(v -> v + ", ").orElse(""),
connectorString,
dimension.map(v -> " group by 1").orElse(""));
QueryExecution queryExecution = executor.executeQuery(project, query);
return new DelegateQueryExecution(queryExecution,
result -> {
if (result.isFailed()) {
return result;
}
List<List<Object>> newResult = new ArrayList<>();
List<SchemaField> metadata;
if (dimension.isPresent()) {
metadata = ImmutableList.of(
new SchemaField("step", STRING),
new SchemaField("dimension", STRING),
new SchemaField("count", LONG));
for (List<Object> objects : result.getResult()) {
for (int i = 0; i < steps.size(); i++) {
newResult.add(ImmutableList.of("Step " + (i + 1),
Optional.ofNullable(objects.get(0)).orElse("(not set)"),
Optional.ofNullable(objects.get(i + 1)).orElse(0)));
}
}
}
else {
metadata = ImmutableList.of(
new SchemaField("step", STRING),
new SchemaField("count", LONG));
List<Object> stepCount = result.getResult().get(0);
for (int i = 0; i < steps.size(); i++) {
Object value = stepCount.get(i);
newResult.add(ImmutableList.of("Step " + (i + 1), value == null ? 0 : value));
}
}
return new QueryResult(metadata, newResult, result.getProperties());
});
}
}
| Fix funnel query builder
| rakam-postgresql/src/main/java/org/rakam/postgresql/analysis/FastGenericFunnelQueryExecutor.java | Fix funnel query builder |
|
Java | agpl-3.0 | 0d61439aadadf4dfa0831855d90552bd618f6b28 | 0 | graknlabs/grakn,lolski/grakn,graknlabs/grakn,graknlabs/grakn,graknlabs/grakn,lolski/grakn,lolski/grakn,lolski/grakn | /*
* Copyright (C) 2020 Grakn Labs
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
package grakn.core.concept.impl;
import grakn.core.core.Schema;
import grakn.core.kb.concept.api.Casting;
import grakn.core.kb.concept.api.GraknConceptException;
import grakn.core.kb.concept.api.Relation;
import grakn.core.kb.concept.api.RelationType;
import grakn.core.kb.concept.api.Role;
import grakn.core.kb.concept.api.Thing;
import grakn.core.kb.concept.manager.ConceptManager;
import grakn.core.kb.concept.manager.ConceptNotificationChannel;
import grakn.core.kb.concept.structure.EdgeElement;
import grakn.core.kb.concept.structure.VertexElement;
import org.apache.tinkerpop.gremlin.structure.Direction;
import java.util.ArrayList;
import java.util.Arrays;
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.stream.Collectors;
import java.util.stream.Stream;
/**
* Encapsulates relations between Thing
* A relation which is an instance of a RelationType defines how instances may relate to one another.
*/
public class RelationImpl extends ThingImpl<Relation, RelationType> implements Relation, ConceptVertex {
public RelationImpl(VertexElement vertexElement, ConceptManager conceptManager, ConceptNotificationChannel conceptNotificationChannel){
super(vertexElement, conceptManager, conceptNotificationChannel);
}
public static RelationImpl from(Relation relation) {
return (RelationImpl) relation;
}
/**
* Retrieve a list of all Thing involved in the Relation, and the Role they play.
*
* @return A list of all the Roles and the Things playing them in this Relation.
* see Role
*/
@Override
public Map<Role, List<Thing>> rolePlayersMap() {
HashMap<Role, List<Thing>> roleMap = new HashMap<>();
//We add the role types explicitly so we can return them when there are no roleplayers
// type().roles().forEach(roleType -> roleMap.put(roleType, new ArrayList<>()));
//All castings are used here because we need to iterate over all of them anyway
castingsRelation().forEach(rp -> roleMap.computeIfAbsent(rp.getRole(), (k) -> new ArrayList<>()).add(rp.getRolePlayer()));
return roleMap;
}
/**
* Expands this Relation to include a new role player which is playing a specific Role.
*
* @param role The role of the new role player.
* @param player The new role player.
* @return The Relation itself
*/
@Override
public Relation assign(Role role, Thing player) {
addRolePlayer(role, player);
return this;
}
@Override
public void unassign(Role role, Thing player) {
removeRolePlayerIfPresent(role, player);
// may need to clean up relation
cleanUp();
}
/**
* Remove this relation if there are no more role player present
*/
void cleanUp() {
boolean performDeletion = !rolePlayers().findAny().isPresent();
if (performDeletion) delete();
}
@Override
public Stream<Thing> rolePlayers(Role... roles) {
return castingsRelation(roles).map(Casting::getRolePlayer);
}
/**
* Remove a single single instance of specific role player playing a given role in this relation
* We could have duplicates, so we only operate on a single casting that is found
*/
private void removeRolePlayerIfPresent(Role role, Thing thing) {
castingsRelation(role)
.filter(casting -> casting.getRole().equals(role) && casting.getRolePlayer().equals(thing))
.findAny()
.ifPresent(casting -> {
casting.delete();
conceptNotificationChannel.castingDeleted(casting);
});
}
private void addRolePlayer(Role role, Thing thing) {
Objects.requireNonNull(role);
Objects.requireNonNull(thing);
if (Schema.MetaSchema.isMetaLabel(role.label())) throw GraknConceptException.metaTypeImmutable(role.label());
//Do the actual put of the role and role player
EdgeElement edge = this.addEdge(ConceptVertex.from(thing), Schema.EdgeLabel.ROLE_PLAYER);
edge.property(Schema.EdgeProperty.RELATION_TYPE_LABEL_ID, this.type().labelId().getValue());
edge.property(Schema.EdgeProperty.ROLE_LABEL_ID, role.labelId().getValue());
Casting casting = CastingImpl.create(edge, this, role, thing, conceptManager);
conceptNotificationChannel.rolePlayerCreated(casting);
}
/**
* Castings are retrieved from the perspective of the Relation
*
* @param roles The Role which the Things are playing
* @return The Casting which unify a Role and Thing with this Relation
*/
@Override
public Stream<Casting> castingsRelation(Role... roles) {
Set<Role> roleSet = new HashSet<>(Arrays.asList(roles));
if (roleSet.isEmpty()) {
return vertex().getEdgesOfType(Direction.OUT, Schema.EdgeLabel.ROLE_PLAYER)
.map(edge -> CastingImpl.withRelation(edge, this, conceptManager));
}
//Traversal is used so we can potentially optimise on the index
Set<Integer> roleTypesIds = roleSet.stream().map(r -> r.labelId().getValue()).collect(Collectors.toSet());
Stream<EdgeElement> castingsEdges = vertex().roleCastingsEdges(type().labelId().getValue(), roleTypesIds);
return castingsEdges.map(edge -> CastingImpl.withRelation(edge, this, conceptManager));
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
return id().equals(((RelationImpl) object).id());
}
@Override
public int hashCode() {
return id().hashCode();
}
@Override
public String innerToString() {
StringBuilder description = new StringBuilder();
description.append("ID [").append(id()).append("] Type [").append(type().label()).append("] Roles and Role Players: \n");
for (Map.Entry<Role, List<Thing>> entry : rolePlayersMap().entrySet()) {
if (entry.getValue().isEmpty()) {
description.append(" Role [").append(entry.getKey().label()).append("] not played by any instance \n");
} else {
StringBuilder instancesString = new StringBuilder();
for (Thing thing : entry.getValue()) {
instancesString.append(thing.id()).append(",");
}
description.append(" Role [").append(entry.getKey().label()).append("] played by [").
append(instancesString.toString()).append("] \n");
}
}
return description.toString();
}
}
| concept/impl/RelationImpl.java | /*
* Copyright (C) 2020 Grakn Labs
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
package grakn.core.concept.impl;
import grakn.core.core.Schema;
import grakn.core.kb.concept.api.Casting;
import grakn.core.kb.concept.api.GraknConceptException;
import grakn.core.kb.concept.api.Relation;
import grakn.core.kb.concept.api.RelationType;
import grakn.core.kb.concept.api.Role;
import grakn.core.kb.concept.api.Thing;
import grakn.core.kb.concept.manager.ConceptManager;
import grakn.core.kb.concept.manager.ConceptNotificationChannel;
import grakn.core.kb.concept.structure.EdgeElement;
import grakn.core.kb.concept.structure.VertexElement;
import org.apache.tinkerpop.gremlin.structure.Direction;
import java.util.ArrayList;
import java.util.Arrays;
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.stream.Collectors;
import java.util.stream.Stream;
/**
* Encapsulates relations between Thing
* A relation which is an instance of a RelationType defines how instances may relate to one another.
*/
public class RelationImpl extends ThingImpl<Relation, RelationType> implements Relation, ConceptVertex {
public RelationImpl(VertexElement vertexElement, ConceptManager conceptManager, ConceptNotificationChannel conceptNotificationChannel){
super(vertexElement, conceptManager, conceptNotificationChannel);
}
public static RelationImpl from(Relation relation) {
return (RelationImpl) relation;
}
/**
* Retrieve a list of all Thing involved in the Relation, and the Role they play.
*
* @return A list of all the Roles and the Things playing them in this Relation.
* see Role
*/
@Override
public Map<Role, List<Thing>> rolePlayersMap() {
return allRolePlayers();
}
/**
* Expands this Relation to include a new role player which is playing a specific Role.
*
* @param role The role of the new role player.
* @param player The new role player.
* @return The Relation itself
*/
@Override
public Relation assign(Role role, Thing player) {
addRolePlayer(role, player);
return this;
}
@Override
public void unassign(Role role, Thing player) {
removeRolePlayerIfPresent(role, player);
// may need to clean up relation
cleanUp();
}
/**
* Remove this relation if there are no more role player present
*/
void cleanUp() {
boolean performDeletion = !rolePlayers().findAny().isPresent();
if (performDeletion) delete();
}
@Override
public Stream<Thing> rolePlayers(Role... roles) {
return castingsRelation(roles).map(Casting::getRolePlayer);
}
private Map<Role, List<Thing>> allRolePlayers() {
HashMap<Role, List<Thing>> roleMap = new HashMap<>();
//We add the role types explicitly so we can return them when there are no roleplayers
type().roles().forEach(roleType -> roleMap.put(roleType, new ArrayList<>()));
//All castings are used here because we need to iterate over all of them anyway
castingsRelation().forEach(rp -> roleMap.computeIfAbsent(rp.getRole(), (k) -> new ArrayList<>()).add(rp.getRolePlayer()));
return roleMap;
}
/**
* Remove a single single instance of specific role player playing a given role in this relation
* We could have duplicates, so we only operate on a single casting that is found
*/
private void removeRolePlayerIfPresent(Role role, Thing thing) {
castingsRelation(role)
.filter(casting -> casting.getRole().equals(role) && casting.getRolePlayer().equals(thing))
.findAny()
.ifPresent(casting -> {
casting.delete();
conceptNotificationChannel.castingDeleted(casting);
});
}
private void addRolePlayer(Role role, Thing thing) {
Objects.requireNonNull(role);
Objects.requireNonNull(thing);
if (Schema.MetaSchema.isMetaLabel(role.label())) throw GraknConceptException.metaTypeImmutable(role.label());
//Do the actual put of the role and role player
EdgeElement edge = this.addEdge(ConceptVertex.from(thing), Schema.EdgeLabel.ROLE_PLAYER);
edge.property(Schema.EdgeProperty.RELATION_TYPE_LABEL_ID, this.type().labelId().getValue());
edge.property(Schema.EdgeProperty.ROLE_LABEL_ID, role.labelId().getValue());
Casting casting = CastingImpl.create(edge, this, role, thing, conceptManager);
conceptNotificationChannel.rolePlayerCreated(casting);
}
/**
* Castings are retrieved from the perspective of the Relation
*
* @param roles The Role which the Things are playing
* @return The Casting which unify a Role and Thing with this Relation
*/
@Override
public Stream<Casting> castingsRelation(Role... roles) {
Set<Role> roleSet = new HashSet<>(Arrays.asList(roles));
if (roleSet.isEmpty()) {
return vertex().getEdgesOfType(Direction.OUT, Schema.EdgeLabel.ROLE_PLAYER)
.map(edge -> CastingImpl.withRelation(edge, this, conceptManager));
}
//Traversal is used so we can potentially optimise on the index
Set<Integer> roleTypesIds = roleSet.stream().map(r -> r.labelId().getValue()).collect(Collectors.toSet());
Stream<EdgeElement> castingsEdges = vertex().roleCastingsEdges(type().labelId().getValue(), roleTypesIds);
return castingsEdges.map(edge -> CastingImpl.withRelation(edge, this, conceptManager));
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
return id().equals(((RelationImpl) object).id());
}
@Override
public int hashCode() {
return id().hashCode();
}
@Override
public String innerToString() {
StringBuilder description = new StringBuilder();
description.append("ID [").append(id()).append("] Type [").append(type().label()).append("] Roles and Role Players: \n");
for (Map.Entry<Role, List<Thing>> entry : allRolePlayers().entrySet()) {
if (entry.getValue().isEmpty()) {
description.append(" Role [").append(entry.getKey().label()).append("] not played by any instance \n");
} else {
StringBuilder instancesString = new StringBuilder();
for (Thing thing : entry.getValue()) {
instancesString.append(thing.id()).append(",");
}
description.append(" Role [").append(entry.getKey().label()).append("] played by [").
append(instancesString.toString()).append("] \n");
}
}
return description.toString();
}
}
| Don't return unplayed role types in a relation role players map
| concept/impl/RelationImpl.java | Don't return unplayed role types in a relation role players map |
|
Java | agpl-3.0 | 172014a94ea41331d1b1e0f5375e09fd383be0b8 | 0 | geothomasp/kcmit,iu-uits-es/kc,jwillia/kc-old1,mukadder/kc,kuali/kc,iu-uits-es/kc,geothomasp/kcmit,mukadder/kc,jwillia/kc-old1,geothomasp/kcmit,kuali/kc,geothomasp/kcmit,ColostateResearchServices/kc,UniversityOfHawaiiORS/kc,UniversityOfHawaiiORS/kc,jwillia/kc-old1,geothomasp/kcmit,iu-uits-es/kc,ColostateResearchServices/kc,UniversityOfHawaiiORS/kc,jwillia/kc-old1,ColostateResearchServices/kc,kuali/kc,mukadder/kc | /*
* Copyright 2006-2008 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kra.proposaldevelopment.document.authorizer;
import java.util.LinkedList;
import java.util.List;
import org.jmock.Expectations;
import org.jmock.MockObjectTestCase;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kuali.kra.KraTestBase;
import org.kuali.kra.infrastructure.PermissionConstants;
import org.kuali.kra.infrastructure.TaskName;
import org.kuali.kra.proposaldevelopment.document.ProposalDevelopmentDocument;
import org.kuali.kra.proposaldevelopment.document.authorization.ProposalTask;
import org.kuali.kra.proposaldevelopment.service.ProposalAuthorizationService;
import org.kuali.kra.service.KraWorkflowService;
import org.kuali.rice.lifecycle.Lifecycle;
@RunWith(JMock.class)
public class ModifyProposalPermissionsAuthorizerTest extends KraTestBase {
private Mockery context = new JUnit4Mockery();
private ProposalDevelopmentDocument doc;
private ProposalTask task;
@Test
public void testSimpleSuccess() {
doc = new ProposalDevelopmentDocument();
doc.setSubmitFlag(false);
task = new ProposalTask(TaskName.MODIFY_PROPOSAL_ROLES, doc);
ModifyProposalPermissionsAuthorizer mpa = new ModifyProposalPermissionsAuthorizer();
final ProposalAuthorizationService authorizationService = context.mock(ProposalAuthorizationService.class);
context.checking(new Expectations() {{
one(authorizationService).hasPermission(TaskName.MODIFY_PROPOSAL_ROLES,
doc,
PermissionConstants.MAINTAIN_PROPOSAL_ACCESS);
will(returnValue(true));
}});
mpa.setProposalAuthorizationService(authorizationService);
final KraWorkflowService workflowService = context.mock(KraWorkflowService.class);
context.checking(new Expectations() {{
one(workflowService).isInWorkflow(doc);
will(returnValue(false));
}});
mpa.setKraWorkflowService(workflowService);
assertTrue(mpa.isAuthorized(TaskName.MODIFY_PROPOSAL_ROLES, task));
}
@Test
public void testNegativeSubmittedToSponsor() {
doc = new ProposalDevelopmentDocument();
doc.setSubmitFlag(true);
task = new ProposalTask(TaskName.MODIFY_PROPOSAL_ROLES, doc);
ModifyProposalPermissionsAuthorizer mpa = new ModifyProposalPermissionsAuthorizer();
final ProposalAuthorizationService authorizationService = context.mock(ProposalAuthorizationService.class);
context.checking(new Expectations() {{
one(authorizationService).hasPermission(TaskName.MODIFY_PROPOSAL_ROLES,
doc,
PermissionConstants.MAINTAIN_PROPOSAL_ACCESS);
will(returnValue(true));
}});
mpa.setProposalAuthorizationService(authorizationService);
final KraWorkflowService workflowService = context.mock(KraWorkflowService.class);
context.checking(new Expectations() {{
one(workflowService).isInWorkflow(doc);
will(returnValue(false));
}});
mpa.setKraWorkflowService(workflowService);
assertFalse(mpa.isAuthorized(TaskName.MODIFY_PROPOSAL_ROLES, task));
}
@Test
public void testNegativeSubmittedToWorkflow() {
doc = new ProposalDevelopmentDocument();
doc.setSubmitFlag(false);
task = new ProposalTask(TaskName.MODIFY_PROPOSAL_ROLES, doc);
ModifyProposalPermissionsAuthorizer mpa = new ModifyProposalPermissionsAuthorizer();
final ProposalAuthorizationService authorizationService = context.mock(ProposalAuthorizationService.class);
context.checking(new Expectations() {{
one(authorizationService).hasPermission(TaskName.MODIFY_PROPOSAL_ROLES,
doc,
PermissionConstants.MAINTAIN_PROPOSAL_ACCESS);
will(returnValue(true));
}});
mpa.setProposalAuthorizationService(authorizationService);
final KraWorkflowService workflowService = context.mock(KraWorkflowService.class);
context.checking(new Expectations() {{
one(workflowService).isInWorkflow(doc);
will(returnValue(true));
}});
mpa.setKraWorkflowService(workflowService);
assertFalse(mpa.isAuthorized(TaskName.MODIFY_PROPOSAL_ROLES, task));
}
@Test
public void testNegativeNotPermitted() {
doc = new ProposalDevelopmentDocument();
doc.setSubmitFlag(false);
task = new ProposalTask(TaskName.MODIFY_PROPOSAL_ROLES, doc);
ModifyProposalPermissionsAuthorizer mpa = new ModifyProposalPermissionsAuthorizer();
final ProposalAuthorizationService authorizationService = context.mock(ProposalAuthorizationService.class);
context.checking(new Expectations() {{
one(authorizationService).hasPermission(TaskName.MODIFY_PROPOSAL_ROLES,
doc,
PermissionConstants.MAINTAIN_PROPOSAL_ACCESS);
will(returnValue(false));
}});
mpa.setProposalAuthorizationService(authorizationService);
final KraWorkflowService workflowService = context.mock(KraWorkflowService.class);
context.checking(new Expectations() {{
ignoring(workflowService).isInWorkflow(doc);
will(returnValue(false));
}});
mpa.setKraWorkflowService(workflowService);
assertFalse(mpa.isAuthorized(TaskName.MODIFY_PROPOSAL_ROLES, task));
}
protected List<Lifecycle> getDefaultPerTestLifecycles() {
List<Lifecycle> lifecycles = new LinkedList<Lifecycle>();
return lifecycles;
}
}
| src/test/java/org/kuali/kra/proposaldevelopment/document/authorizer/ModifyProposalPermissionsAuthorizerTest.java | /*
* Copyright 2006-2008 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kra.proposaldevelopment.document.authorizer;
import org.jmock.Expectations;
import org.jmock.MockObjectTestCase;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.Test;
import org.kuali.kra.infrastructure.PermissionConstants;
import org.kuali.kra.infrastructure.TaskName;
import org.kuali.kra.proposaldevelopment.document.ProposalDevelopmentDocument;
import org.kuali.kra.proposaldevelopment.document.authorization.ProposalTask;
import org.kuali.kra.proposaldevelopment.service.ProposalAuthorizationService;
import org.kuali.kra.service.KraWorkflowService;
public class ModifyProposalPermissionsAuthorizerTest extends MockObjectTestCase {
private Mockery context = new JUnit4Mockery();
private ProposalDevelopmentDocument doc;
private ProposalTask task;
boolean inWorkFlow = false;
boolean submittedToSponsor = false;
boolean permitted=true;
@Test
public void testSimpleSuccess() {
doc = new ProposalDevelopmentDocument();
doc.setSubmitFlag(submittedToSponsor);
task = new ProposalTask(TaskName.MODIFY_PROPOSAL_ROLES, doc);
ModifyProposalPermissionsAuthorizer mpa = new ModifyProposalPermissionsAuthorizer();
final ProposalAuthorizationService authorizationService = context.mock(ProposalAuthorizationService.class);
context.checking(new Expectations() {{
one(authorizationService).hasPermission(TaskName.MODIFY_PROPOSAL_ROLES,
doc,
PermissionConstants.MAINTAIN_PROPOSAL_ACCESS);
will(returnValue(true));
}});
mpa.setProposalAuthorizationService(authorizationService);
final KraWorkflowService workflowService = context.mock(KraWorkflowService.class);
context.checking(new Expectations() {{
one(workflowService).isInWorkflow(doc);
will(returnValue(inWorkFlow));
}});
mpa.setKraWorkflowService(workflowService);
assertTrue(mpa.isAuthorized(TaskName.MODIFY_PROPOSAL_ROLES, task));
}
@Test
public void testNegativeSubmittedToSponsor() {
submittedToSponsor=true;
doc = new ProposalDevelopmentDocument();
doc.setSubmitFlag(submittedToSponsor);
task = new ProposalTask(TaskName.MODIFY_PROPOSAL_ROLES, doc);
ModifyProposalPermissionsAuthorizer mpa = new ModifyProposalPermissionsAuthorizer();
final ProposalAuthorizationService authorizationService = context.mock(ProposalAuthorizationService.class);
context.checking(new Expectations() {{
one(authorizationService).hasPermission(TaskName.MODIFY_PROPOSAL_ROLES,
doc,
PermissionConstants.MAINTAIN_PROPOSAL_ACCESS);
will(returnValue(true));
}});
mpa.setProposalAuthorizationService(authorizationService);
final KraWorkflowService workflowService = context.mock(KraWorkflowService.class);
context.checking(new Expectations() {{
one(workflowService).isInWorkflow(doc);
will(returnValue(inWorkFlow));
}});
mpa.setKraWorkflowService(workflowService);
assertFalse(mpa.isAuthorized(TaskName.MODIFY_PROPOSAL_ROLES, task));
}
@Test
public void testNegativeSubmittedToWorkflow() {
inWorkFlow=true;
doc = new ProposalDevelopmentDocument();
doc.setSubmitFlag(submittedToSponsor);
task = new ProposalTask(TaskName.MODIFY_PROPOSAL_ROLES, doc);
ModifyProposalPermissionsAuthorizer mpa = new ModifyProposalPermissionsAuthorizer();
final ProposalAuthorizationService authorizationService = context.mock(ProposalAuthorizationService.class);
context.checking(new Expectations() {{
one(authorizationService).hasPermission(TaskName.MODIFY_PROPOSAL_ROLES,
doc,
PermissionConstants.MAINTAIN_PROPOSAL_ACCESS);
will(returnValue(true));
}});
mpa.setProposalAuthorizationService(authorizationService);
final KraWorkflowService workflowService = context.mock(KraWorkflowService.class);
context.checking(new Expectations() {{
one(workflowService).isInWorkflow(doc);
will(returnValue(inWorkFlow));
}});
mpa.setKraWorkflowService(workflowService);
assertFalse(mpa.isAuthorized(TaskName.MODIFY_PROPOSAL_ROLES, task));
}
@Test
public void testNegativeNotPermitted() {
permitted=false;
doc = new ProposalDevelopmentDocument();
doc.setSubmitFlag(submittedToSponsor);
task = new ProposalTask(TaskName.MODIFY_PROPOSAL_ROLES, doc);
ModifyProposalPermissionsAuthorizer mpa = new ModifyProposalPermissionsAuthorizer();
final ProposalAuthorizationService authorizationService = context.mock(ProposalAuthorizationService.class);
context.checking(new Expectations() {{
one(authorizationService).hasPermission(TaskName.MODIFY_PROPOSAL_ROLES,
doc,
PermissionConstants.MAINTAIN_PROPOSAL_ACCESS);
will(returnValue(false));
}});
mpa.setProposalAuthorizationService(authorizationService);
final KraWorkflowService workflowService = context.mock(KraWorkflowService.class);
context.checking(new Expectations() {{
one(workflowService).isInWorkflow(doc);
will(returnValue(permitted));
}});
mpa.setKraWorkflowService(workflowService);
assertFalse(mpa.isAuthorized(TaskName.MODIFY_PROPOSAL_ROLES, task));
}
}
| KRACOEUS-2069 : Fix more unit tests
| src/test/java/org/kuali/kra/proposaldevelopment/document/authorizer/ModifyProposalPermissionsAuthorizerTest.java | KRACOEUS-2069 : Fix more unit tests |
|
Java | lgpl-2.1 | cfe168a89b076a011af7f4d1b3bbbd71e8dae2b5 | 0 | jfdenise/wildfly-core,ivassile/wildfly-core,aloubyansky/wildfly-core,darranl/wildfly-core,yersan/wildfly-core,JiriOndrusek/wildfly-core,aloubyansky/wildfly-core,JiriOndrusek/wildfly-core,jfdenise/wildfly-core,yersan/wildfly-core,ivassile/wildfly-core,jamezp/wildfly-core,darranl/wildfly-core,bstansberry/wildfly-core,luck3y/wildfly-core,jamezp/wildfly-core,luck3y/wildfly-core,darranl/wildfly-core,JiriOndrusek/wildfly-core,soul2zimate/wildfly-core,bstansberry/wildfly-core,soul2zimate/wildfly-core,bstansberry/wildfly-core,jfdenise/wildfly-core,aloubyansky/wildfly-core,ivassile/wildfly-core,jamezp/wildfly-core,yersan/wildfly-core,luck3y/wildfly-core,soul2zimate/wildfly-core | /*
* JBoss, Home of Professional Open Source
* Copyright 2017, Red Hat, Inc., and individual contributors as indicated
* by the @authors tag.
*
* 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.jboss.as.test.integration.domain.cacheddc;
import static org.jboss.as.controller.client.helpers.ClientConstants.OUTCOME;
import static org.jboss.as.controller.client.helpers.ClientConstants.SUCCESS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILED;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILURE_DESCRIPTION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST_STATE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.LOGGER;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROFILE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import org.jboss.as.controller.ControlledProcessState;
import org.jboss.as.controller.client.helpers.Operations;
import org.jboss.as.controller.client.helpers.domain.DomainClient;
import org.jboss.as.controller.client.helpers.domain.impl.DomainClientImpl;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.test.integration.domain.management.util.DomainLifecycleUtil;
import org.jboss.as.test.integration.domain.management.util.DomainTestSupport;
import org.jboss.as.test.integration.domain.management.util.WildFlyManagedConfiguration;
import org.jboss.as.test.shared.TimeoutUtil;
import org.jboss.dmr.ModelNode;
import org.jboss.logging.Logger;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Testing <code>--cached-dc</code> configuration option.<br>
* Tests shows that <code>domain.cached-remote.xml</code> is created on slave HC
* and that slave HC is capable to start when that file exists even DC is down.
*
* @author <a href="[email protected]">Ondra Chaloupka</a>
*/
public class CachedDcDomainTestCase {
private static Logger log = Logger.getLogger(CachedDcDomainTestCase.class);
private static final long TIMEOUT_S = TimeoutUtil.adjust(30);
private static final long NOT_STARTED_TIMEOUT_S = TimeoutUtil.adjust(7);
private static final int TIMEOUT_SLEEP_MILLIS = 50;
private static final String TEST_LOGGER_NAME = "org.jboss.test";
private static final String DOMAIN_CACHED_REMOTE_XML_FILE_NAME = "domain.cached-remote.xml";
private DomainTestSupport.Configuration domainConfig;
private DomainTestSupport domainManager;
@Before
public void specifyDomainConfig() throws Exception {
domainConfig = DomainTestSupport.Configuration.create(CachedDcDomainTestCase.class.getSimpleName(),
"domain-configs/domain-minimal.xml", "host-configs/host-master-cacheddc.xml", "host-configs/host-slave-cacheddc.xml");
// removing domain.cached-remote.xml if exists
getDomainCachedRemoteXmlFile(domainConfig.getSlaveConfiguration()).delete();
}
@After
public void stopDomain() {
if(domainManager != null) {
domainManager.stop();
}
}
/**
* DC is down, HC successfully starts if parameter <code>--cached-dc</code> is used
* and cached configuration is available
*/
@Test
public void hcStartsWhenCachedConfigAvailable_CachedDCParamIsSet() throws Exception {
domainConfig.getSlaveConfiguration()
.setCachedDC(true)
.setBackupDC(false);
test_hcStartsWhenCachedConfigAvailable(domainConfig);
}
/**
* DC is down, HC successfully starts if parameters <code>--backup --cached-dc</code> is used together
* and cached configuration is available (see WFCORE-317)
*/
@Test
public void hcStartsWhenCachedConfigAvailable_CachedAndBackupDCParamIsSet() throws Exception {
domainConfig.getSlaveConfiguration()
.setCachedDC(true)
.setBackupDC(true);
test_hcStartsWhenCachedConfigAvailable(domainConfig);
}
/**
* DC is up, HC successfully starts if parameter --backup, both HC and DC is put down
* and when HC is subsequently started with --cached-dc it uses cached file created during start-up
* with --backup param and HC is succesfully started
*/
@Test
public void hcStartsWhenCachedConfigAvailable_BackupDCParamIsSet() throws Exception {
domainConfig.getSlaveConfiguration()
.setCachedDC(false)
.setBackupDC(true);
test_hcStartsWhenCachedConfigAvailable(domainConfig);
}
/**
* DC is down, HC fails to start if parameter <code>--cached-dc</code> is used but
* no cached configuration is available
*/
@Test
public void hcNotStartsWhenCachedConfigNotAvailable_CachedDCParamIsSet() throws Exception {
domainConfig.getSlaveConfiguration()
.setCachedDC(true)
.setBackupDC(false);
domainManager = DomainTestSupport.create(domainConfig);
domainManager.getDomainSlaveLifecycleUtil().startAsync();
// expecting that HC is not started
try (final DomainClient client = getDomainClient(domainConfig.getSlaveConfiguration())) {
waitForHostControllerBeingStarted(NOT_STARTED_TIMEOUT_S, client);
Assert.fail("DC not started, domain.cached-remote.xml does not exist but "
+ "slave host controller was started ");
} catch (IllegalStateException ise) {
// as HC should not be started IllegalStateException is expected
}
}
/**
* DC is down, HC waits for DC to be started when <code>--backup</code> parameter is used
*/
@Test
public void hcWaitsForDCBeingStarted_BackupDCParamIsSet() throws Exception {
domainConfig.getSlaveConfiguration()
.setCachedDC(false)
.setBackupDC(true);
test_hcWaitsForDcBeingStarted(domainConfig);
}
/**
* DC is up, HC is started with <code>--cached-dc</code> then domain configuration is passed from DC to HC
* (cached configuration is created for HC)
* a configuration change is done on DC then such change is propagated to HC cached configuration
*/
@Test
public void dcConfigChangePropagated() throws Exception {
domainConfig.getSlaveConfiguration().setCachedDC(true);
domainManager = DomainTestSupport.create(domainConfig);
domainManager.start();
// adding logger to profile "other" connected to DC
domainManager.getDomainMasterLifecycleUtil()
.executeForResult(getCreateOperationTestLoggingCategory());
domainManager.stop();
domainManager.getDomainSlaveLifecycleUtil().startAsync();
try (final DomainClient client = getDomainClient(domainConfig.getSlaveConfiguration())) {
waitForHostControllerBeingStarted(TIMEOUT_S, client);
waitForServersBeingStarted(TIMEOUT_S, client);
checkTestLoggerFromSlaveHost(client);
}
}
/**
* DC is up, HC is started with <code>--cached-dc</code> then domain configuration is passed from DC to HC
* (cached configuration is created for HC).
* HC is stopped and configuration change is done at DC. DC is stopped.
* DC is down, HC is started with --cached-dc and as cached configuration file exists it's used.
* HC is started and configuration change should be propagated and applied to HC.
*/
@Test
public void dcConfigChangePropagatedAfterRestart() throws Exception {
domainConfig.getSlaveConfiguration().setCachedDC(true);
domainManager = DomainTestSupport.create(domainConfig);
domainManager.start();
stopSlaveAndWaitForUnregistration();
assertEquals(false, domainManager.getDomainSlaveLifecycleUtil().isHostControllerStarted());
domainManager.getDomainMasterLifecycleUtil()
.executeForResult(getCreateOperationTestLoggingCategory());
domainManager.stop();
// starting domain once again - reusing already changed config files
domainConfig.getMasterConfiguration().setRewriteConfigFiles(false);
domainConfig.getSlaveConfiguration().setRewriteConfigFiles(false);
// HC started with old domain.cached-remote.xml
domainManager.getDomainSlaveLifecycleUtil().startAsync();
try (final DomainClient clientSlave = getDomainClient(domainConfig.getSlaveConfiguration())) {
waitForHostControllerBeingStarted(TIMEOUT_S, clientSlave);
waitForServersBeingStarted(TIMEOUT_S, clientSlave);
}
// DC started where domain config contains a configuration change (a new logger was created)
domainManager.getDomainMasterLifecycleUtil().startAsync();
try (final DomainClient clientMaster = getDomainClient(domainConfig.getSlaveConfiguration())) {
waitForHostControllerBeingStarted(TIMEOUT_S, clientMaster);
waitForServersBeingStarted(TIMEOUT_S, clientMaster);
}
// timeout waits to get changes from DC propagated to HC
// by WFCORE-2331 the host controller log file should advert need of configuration change
runWithTimeout(TIMEOUT_S, () -> checkHostControllerLogFile(domainConfig.getSlaveConfiguration(), "WFLYHC0202"));
}
/**
* <p>
* If configuration change (new configuration coming from DC) requires reload then reload needs
* to be advertised at HC’s domain model.
* <p>
* DC is up, HC is up. HC is started <b>without any special flag</b>.
* When DC provides change in settings the HC should show info that reload is needed.
*/
@Test
public void reloadAdvertisedAfterDcModelChange() throws Exception {
domainManager = DomainTestSupport.create(domainConfig);
domainManager.start();
final boolean isAddLoggingApiDependencies = setLoggingApiDependencies(domainManager.getDomainMasterLifecycleUtil().getDomainClient());
// property was changed - checking if change is visible at profile level
ModelNode profileRead = readLoggingApiDependencies(domainManager.getDomainSlaveLifecycleUtil().getDomainClient());
assertEquals("Expecting value of attribute 'add-logging-api-dependencies' was changed" + profileRead,
isAddLoggingApiDependencies, profileRead.get("result").asBoolean());
// property was changed - checking if change is visible at HC
ModelNode hostRead = readLoggingApiDependenciesAtServerOtherTwo(domainManager.getDomainSlaveLifecycleUtil().getDomainClient());
assertEquals("Read operation should suceed", SUCCESS, hostRead.get(OUTCOME).asString());
assertEquals("Expecting value of attribute 'add-logging-api-dependencies' was changed" + hostRead,
isAddLoggingApiDependencies, hostRead.get("result").asBoolean());
assertEquals("Expecting change of attribute 'add-logging-api-dependencies' requests a reload: " + hostRead,
"reload-required", hostRead.get("response-headers").get("process-state").asString());
}
/**
* <p>
* If configuration change (new configuration coming from DC) requires reload then reload needs
* to be advertised at HC’s domain model.
* <p>
* <ol>
* <li>DC is up, HC is started with <code>--backup</code> to get created a <code>domain.cached-remote.xml</code>.</li>
* <li>HC is stopped and configuration change which requires reload is done at DC and DC is stopped.</li>
* <li>HC is started with <code>--cached-dc</code> and boot-up with config from <code>domain.cached-remote.xml</code>.</li>
* <li>DC is started and configuration change should be propagated to HC with announcement that reload is needed</li>
* </ol>
*/
@Test
public void reloadAdvertisedAfterDcModelChangeWithShutdown() throws Exception {
// slave is started with backup parameter but not with cached dc
domainConfig.getSlaveConfiguration().setBackupDC(true).setCachedDC(false);
domainManager = DomainTestSupport.create(domainConfig);
domainManager.start();
// domain.cached-remote.xml was created now stop slave HC
stopSlaveAndWaitForUnregistration();
// changing parameter which needs reload
final DomainClient client = domainManager.getDomainMasterLifecycleUtil().getDomainClient();
final boolean isAddLoggingApiDependencies = setLoggingApiDependencies(client);
final ModelNode profileRead = readLoggingApiDependencies(client);
assertEquals("Expecting value of attribute 'add-logging-api-dependencies' was changed" + profileRead,
isAddLoggingApiDependencies, profileRead.get("result").asBoolean());
domainManager.stop();
// starting domain once again - reusing already changed config files
// slave will be started with cached dc parameter but not with backup parameter
domainConfig.getMasterConfiguration().setRewriteConfigFiles(false);
domainConfig.getSlaveConfiguration()
.setRewriteConfigFiles(false).setBackupDC(false).setCachedDC(true);
// starting HC with old domain.cached-remote.xml
domainManager.getDomainSlaveLifecycleUtil().startAsync();
try (final DomainClient clientSlave = getDomainClient(domainConfig.getSlaveConfiguration())) {
waitForHostControllerBeingStarted(TIMEOUT_S, clientSlave);
waitForServersBeingStarted(TIMEOUT_S, clientSlave);
}
// starting DC where domain config contains a configuration change
domainManager.getDomainMasterLifecycleUtil().startAsync();
try (final DomainClient clientMaster = getDomainClient(domainConfig.getSlaveConfiguration())) {
waitForHostControllerBeingStarted(TIMEOUT_S, clientMaster);
waitForServersBeingStarted(TIMEOUT_S, clientMaster);
}
try (final DomainClient clientSlave = getDomainClient(domainConfig.getSlaveConfiguration())) {
runWithTimeout(TIMEOUT_S, () -> {
ModelNode hostRead = readLoggingApiDependenciesAtServerOtherTwo(clientSlave);
assertEquals("Read operation should suceed", SUCCESS, hostRead.get(OUTCOME).asString());
assertEquals("Expecting change of attribute 'add-logging-api-dependencies' requests a reload: " + hostRead,
"reload-required", hostRead.get("response-headers").get("process-state").asString());
});
}
try (final DomainClient clientMaster = getDomainClient(domainConfig.getMasterConfiguration())) {
reloadServers(clientMaster);
}
try (final DomainClient clientMaster = getDomainClient(domainConfig.getMasterConfiguration())) {
runWithTimeout(TIMEOUT_S, () -> {
ModelNode hostRead = readLoggingApiDependenciesAtServerOtherTwo(clientMaster);
assertEquals("Expecting value of attribute 'add-logging-api-dependencies' changed: " + hostRead,
isAddLoggingApiDependencies, hostRead.get("result").asBoolean());
});
}
// by WFCORE-2331 the host controller log file should advert need of configuration change
runWithTimeout(TIMEOUT_S, () -> checkHostControllerLogFile(domainConfig.getSlaveConfiguration(), "WFLYHC0202"));
}
private void test_hcStartsWhenCachedConfigAvailable(DomainTestSupport.Configuration domainConfig) throws Exception {
domainManager = DomainTestSupport.create(domainConfig);
domainManager.start();
DomainLifecycleUtil masterHost = domainManager.getDomainMasterLifecycleUtil();
DomainLifecycleUtil slaveHost = domainManager.getDomainSlaveLifecycleUtil();
assertTrue("Master should be started", masterHost.areServersStarted());
assertTrue("Slave should be started", slaveHost.areServersStarted());
domainManager.stop();
domainConfig.getSlaveConfiguration().setCachedDC(true);
slaveHost.startAsync();
// check that HC and servers were started
try (final DomainClient client = getDomainClient(domainConfig.getSlaveConfiguration())) {
waitForHostControllerBeingStarted(TIMEOUT_S, client);
waitForServersBeingStarted(TIMEOUT_S, client);
}
}
/**
* Checking that HC waits for DC being started when HC is started first.
*/
private void test_hcWaitsForDcBeingStarted(DomainTestSupport.Configuration domainConfig) throws Exception {
domainManager = DomainTestSupport.create(domainConfig);
domainManager.getDomainSlaveLifecycleUtil().startAsync();
try (final DomainClient client = getDomainClient(domainConfig.getSlaveConfiguration())) {
// getting statuses of servers from slave HC as waiting for HC being ready
runWithTimeout(TimeoutUtil.adjust(5), () -> client.getServerStatuses());
Assert.fail("DC started with no param, it's waiting for DC but it's not possible to connect to it");
} catch (IllegalStateException ise) {
// as HC should not be started IllegalStateException is expected
}
// after starting DC, HC is ready to use with all its servers
domainManager.getDomainMasterLifecycleUtil().start();
try (final DomainClient client = getDomainClient(domainConfig.getSlaveConfiguration())) {
waitForHostControllerBeingStarted(TIMEOUT_S, client);
waitForServersBeingStarted(TIMEOUT_S, client);
}
}
private DomainClient getDomainClient(WildFlyManagedConfiguration config) throws UnknownHostException {
final InetAddress address = InetAddress.getByName(config.getHostControllerManagementAddress());
final int port = config.getHostControllerManagementPort();
final String protocol = config.getHostControllerManagementProtocol();
return new DomainClientImpl(protocol, address, port);
}
private void waitForHostControllerBeingStarted(long timeoutSeconds, DomainClient client) {
runWithTimeout(timeoutSeconds, () -> client.getServerStatuses());
}
private void waitForServersBeingStarted(long timeoutSeconds, DomainClient client) {
// checking that all serves are started
runWithTimeout(timeoutSeconds, () -> {
client.getServerStatuses().entrySet().forEach(entry -> {
switch(entry.getValue()) {
case DISABLED:
log.tracef("Server '%s' status check skipped as status is %s", entry.getKey(), entry.getValue());
break;
case STARTED:
log.tracef("Server '%s' is started", entry.getKey());
break;
default:
log.tracef("Assert fail: server '%s' with status '%s'", entry.getKey(), entry.getValue());
Assert.fail(String.format("Server '%s' is not started, is in status '%s'",
entry.getKey(), entry.getValue()));
}
});
return null;
});
}
private void runWithTimeout(long timeoutSeconds, Runnable voidFunctionInterface) {
runWithTimeout(timeoutSeconds, () -> {
voidFunctionInterface.run();
return null;
});
}
private <T> T runWithTimeout(long timeoutSeconds, Supplier<T> function) {
final long timeoutTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(timeoutSeconds);
while(true) {
try {
return function.get();
} catch (Throwable t) {
if(timeoutTime < System.currentTimeMillis()) {
throw new IllegalStateException("Function '" + function
+ "' failed to process in " + timeoutSeconds + " s, caused: " + t.getMessage() , t);
}
try {
Thread.sleep(TIMEOUT_SLEEP_MILLIS);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
}
}
private File getDomainCachedRemoteXmlFile(WildFlyManagedConfiguration appConfiguration) {
final File rootDir = new File(appConfiguration.getDomainDirectory());
return new File(rootDir, "configuration" + File.separator + DOMAIN_CACHED_REMOTE_XML_FILE_NAME);
}
private void checkHostControllerLogFile(WildFlyManagedConfiguration appConfiguration, String containString) {
final File logFile = new File(appConfiguration.getDomainDirectory(), "log" + File.separator + "host-controller.log");
assertTrue("Log file '" + logFile + "' does not exist", logFile.exists());
try {
final String content = com.google.common.io.Files.toString(logFile, Charset.forName("UTF-8"));
assertTrue("Expecting log file '" + logFile + " contains string '" + containString + "'",
content.contains(containString));
} catch (IOException ioe) {
throw new RuntimeException("Can't read content of file " + logFile, ioe);
}
}
private ModelNode getProfileDefaultLoggingAddr() {
return new ModelNode()
.add(PROFILE, "default")
.add(SUBSYSTEM, "logging");
}
private ModelNode getCreateOperationTestLoggingCategory() {
final ModelNode addrLogger = getProfileDefaultLoggingAddr();
addrLogger.add(LOGGER, TEST_LOGGER_NAME);
final ModelNode createOp = Operations.createAddOperation(addrLogger);
createOp.get("level").set("TRACE");
createOp.get("category").set(TEST_LOGGER_NAME);
return createOp;
}
private ModelNode readResourceTestLoggerFromSlaveHost(DomainClient client) throws IOException {
final ModelNode hostLoggerAddress = new ModelNode()
.add(HOST, "slave")
.add(SERVER, "other-two")
.add(SUBSYSTEM, "logging")
.add(LOGGER, TEST_LOGGER_NAME);
final ModelNode readResourceOp = Operations.createReadResourceOperation(hostLoggerAddress);
final ModelNode result = client.execute(readResourceOp);
assertEquals(SUCCESS, result.get(OUTCOME).asString());
return result;
}
/**
* ls /host=slave/server=other-two/subsystem=logging/logger
*/
private void checkTestLoggerFromSlaveHost(DomainClient client) throws IOException {
final ModelNode result = readResourceTestLoggerFromSlaveHost(client);
assertEquals("Reading logger '" + TEST_LOGGER_NAME + "' resource does not finish with success: " + result,
SUCCESS, result.get(OUTCOME).asString());
}
private ModelNode readLoggingApiDependenciesAtServerOtherTwo(DomainClient client) {
final ModelNode hostLoggingAddress = new ModelNode()
.add(HOST, "slave")
.add(SERVER, "other-two")
.add(SUBSYSTEM, "logging");
final ModelNode readAttributeOp = Operations
.createReadAttributeOperation(hostLoggingAddress, "add-logging-api-dependencies");
try {
final ModelNode result = client.execute(readAttributeOp);
assertEquals(SUCCESS, result.get(OUTCOME).asString());
return result;
} catch (IOException ioe) {
throw new RuntimeException("Can't read attribute 'add-logging-api-dependencies' from address "
+ hostLoggingAddress, ioe);
}
}
private ModelNode readLoggingApiDependencies(DomainClient client) throws IOException {
final ModelNode readAttributeOp = Operations
.createReadAttributeOperation(getProfileDefaultLoggingAddr(), "add-logging-api-dependencies");
final ModelNode result = client.execute(readAttributeOp);
assertEquals(SUCCESS, result.get(OUTCOME).asString());
return result;
}
private boolean setLoggingApiDependencies(DomainClient client) throws IOException {
boolean isAddLoggingApiDependencies = readLoggingApiDependencies(client).get("result").asBoolean();
final ModelNode writeAttributeOp = Operations
.createWriteAttributeOperation(getProfileDefaultLoggingAddr(), "add-logging-api-dependencies", !isAddLoggingApiDependencies);
final ModelNode result = client.execute(writeAttributeOp);
assertEquals(SUCCESS, result.get(OUTCOME).asString());
return !isAddLoggingApiDependencies;
}
private void reloadServers(DomainClient clientMaster) throws IOException {
final ModelNode op = Operations.createOperation("reload-servers");
op.get("blocking").set("true");
final ModelNode result = clientMaster.execute(op);
assertEquals(SUCCESS, result.get(OUTCOME).asString());
}
private void stopSlaveAndWaitForUnregistration() throws InterruptedException, IOException {
domainManager.getDomainSlaveLifecycleUtil().stop();
// WFCORE-2836
// this is a bit flaky in CI. It seems that that operation (example adding a logger)
// occasionally executre before the slave host unregisters completely, triggering rollback
// when the slave shuts down.
final long deadline = System.currentTimeMillis() + 1000;
while (true) {
if (! isHostPresentInModel(domainManager.getDomainSlaveConfiguration().getHostName(), null)) {
break;
}
if (System.currentTimeMillis() > deadline) {
break;
}
Thread.sleep(TIMEOUT_SLEEP_MILLIS);
}
}
/**
* @param hostname the hostname to query
* @param requiredState the {@link ControlledProcessState.State} expected, or null for any state}
* @return true if the host is present in the queried hosts's model (in the requiredState, if present), false otherwise.
*/
private boolean isHostPresentInModel(final String hostname, final ControlledProcessState.State requiredState) throws IOException {
final ModelNode operation = new ModelNode();
operation.get(OP).set(READ_ATTRIBUTE_OPERATION);
operation.get(OP_ADDR).add(HOST, hostname);
operation.get(NAME).set(HOST_STATE);
ModelNode result;
try (DomainClient client = getDomainClient(domainConfig.getMasterConfiguration())) {
result = client.execute(operation);
if (result.get(ModelDescriptionConstants.OUTCOME).asString().equals(ModelDescriptionConstants.SUCCESS)) {
final ModelNode model = result.require(RESULT);
if (requiredState == null) {
return true;
}
return model.asString().equalsIgnoreCase(requiredState.toString());
} else if (result.get(ModelDescriptionConstants.OUTCOME).asString().equals(FAILED)) {
// make sure we get WFLYCTL0030: No resource definition is registered for address so we don't mistakenly hide other problems.
if (result.require(FAILURE_DESCRIPTION).asString().contains("WFLYCTL0030")) {
return false;
}
// otherwise we got a failure, but the host is present (perhaps still shutting down?), so return true
return true;
}
// otherwise, something bad happened
throw new RuntimeException(result != null ? result.toJSONString(false) : "Unknown error in determining host state.");
}
}
}
| testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/cacheddc/CachedDcDomainTestCase.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2017, Red Hat, Inc., and individual contributors as indicated
* by the @authors tag.
*
* 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.jboss.as.test.integration.domain.cacheddc;
import static org.jboss.as.controller.client.helpers.ClientConstants.OUTCOME;
import static org.jboss.as.controller.client.helpers.ClientConstants.SUCCESS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.LOGGER;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROFILE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import org.jboss.as.controller.client.helpers.Operations;
import org.jboss.as.controller.client.helpers.domain.DomainClient;
import org.jboss.as.controller.client.helpers.domain.impl.DomainClientImpl;
import org.jboss.as.test.integration.domain.management.util.DomainLifecycleUtil;
import org.jboss.as.test.integration.domain.management.util.DomainTestSupport;
import org.jboss.as.test.integration.domain.management.util.WildFlyManagedConfiguration;
import org.jboss.as.test.shared.TimeoutUtil;
import org.jboss.dmr.ModelNode;
import org.jboss.logging.Logger;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Testing <code>--cached-dc</code> configuration option.<br>
* Tests shows that <code>domain.cached-remote.xml</code> is created on slave HC
* and that slave HC is capable to start when that file exists even DC is down.
*
* @author <a href="[email protected]">Ondra Chaloupka</a>
*/
public class CachedDcDomainTestCase {
private static Logger log = Logger.getLogger(CachedDcDomainTestCase.class);
private static final long TIMEOUT_S = TimeoutUtil.adjust(30);
private static final long NOT_STARTED_TIMEOUT_S = TimeoutUtil.adjust(7);
private static final int TIMEOUT_SLEEP_MILLIS = 50;
private static final String TEST_LOGGER_NAME = "org.jboss.test";
private static final String DOMAIN_CACHED_REMOTE_XML_FILE_NAME = "domain.cached-remote.xml";
private DomainTestSupport.Configuration domainConfig;
private DomainTestSupport domainManager;
@Before
public void specifyDomainConfig() throws Exception {
domainConfig = DomainTestSupport.Configuration.create(CachedDcDomainTestCase.class.getSimpleName(),
"domain-configs/domain-minimal.xml", "host-configs/host-master-cacheddc.xml", "host-configs/host-slave-cacheddc.xml");
// removing domain.cached-remote.xml if exists
getDomainCachedRemoteXmlFile(domainConfig.getSlaveConfiguration()).delete();
}
@After
public void stopDomain() {
if(domainManager != null) {
domainManager.stop();
}
}
/**
* DC is down, HC successfully starts if parameter <code>--cached-dc</code> is used
* and cached configuration is available
*/
@Test
public void hcStartsWhenCachedConfigAvailable_CachedDCParamIsSet() throws Exception {
domainConfig.getSlaveConfiguration()
.setCachedDC(true)
.setBackupDC(false);
test_hcStartsWhenCachedConfigAvailable(domainConfig);
}
/**
* DC is down, HC successfully starts if parameters <code>--backup --cached-dc</code> is used together
* and cached configuration is available (see WFCORE-317)
*/
@Test
public void hcStartsWhenCachedConfigAvailable_CachedAndBackupDCParamIsSet() throws Exception {
domainConfig.getSlaveConfiguration()
.setCachedDC(true)
.setBackupDC(true);
test_hcStartsWhenCachedConfigAvailable(domainConfig);
}
/**
* DC is up, HC successfully starts if parameter --backup, both HC and DC is put down
* and when HC is subsequently started with --cached-dc it uses cached file created during start-up
* with --backup param and HC is succesfully started
*/
@Test
public void hcStartsWhenCachedConfigAvailable_BackupDCParamIsSet() throws Exception {
domainConfig.getSlaveConfiguration()
.setCachedDC(false)
.setBackupDC(true);
test_hcStartsWhenCachedConfigAvailable(domainConfig);
}
/**
* DC is down, HC fails to start if parameter <code>--cached-dc</code> is used but
* no cached configuration is available
*/
@Test
public void hcNotStartsWhenCachedConfigNotAvailable_CachedDCParamIsSet() throws Exception {
domainConfig.getSlaveConfiguration()
.setCachedDC(true)
.setBackupDC(false);
domainManager = DomainTestSupport.create(domainConfig);
domainManager.getDomainSlaveLifecycleUtil().startAsync();
// expecting that HC is not started
try (final DomainClient client = getDomainClient(domainConfig.getSlaveConfiguration())) {
waitForHostControllerBeingStarted(NOT_STARTED_TIMEOUT_S, client);
Assert.fail("DC not started, domain.cached-remote.xml does not exist but "
+ "slave host controller was started ");
} catch (IllegalStateException ise) {
// as HC should not be started IllegalStateException is expected
}
}
/**
* DC is down, HC waits for DC to be started when <code>--backup</code> parameter is used
*/
@Test
public void hcWaitsForDCBeingStarted_BackupDCParamIsSet() throws Exception {
domainConfig.getSlaveConfiguration()
.setCachedDC(false)
.setBackupDC(true);
test_hcWaitsForDcBeingStarted(domainConfig);
}
/**
* DC is up, HC is started with <code>--cached-dc</code> then domain configuration is passed from DC to HC
* (cached configuration is created for HC)
* a configuration change is done on DC then such change is propagated to HC cached configuration
*/
@Test
public void dcConfigChangePropagated() throws Exception {
domainConfig.getSlaveConfiguration().setCachedDC(true);
domainManager = DomainTestSupport.create(domainConfig);
domainManager.start();
// adding logger to profile "other" connected to DC
domainManager.getDomainMasterLifecycleUtil()
.executeForResult(getCreateOperationTestLoggingCategory());
domainManager.stop();
domainManager.getDomainSlaveLifecycleUtil().startAsync();
try (final DomainClient client = getDomainClient(domainConfig.getSlaveConfiguration())) {
waitForHostControllerBeingStarted(TIMEOUT_S, client);
waitForServersBeingStarted(TIMEOUT_S, client);
checkTestLoggerFromSlaveHost(client);
}
}
/**
* DC is up, HC is started with <code>--cached-dc</code> then domain configuration is passed from DC to HC
* (cached configuration is created for HC).
* HC is stopped and configuration change is done at DC. DC is stopped.
* DC is down, HC is started with --cached-dc and as cached configuration file exists it's used.
* HC is started and configuration change should be propagated and applied to HC.
*/
@Test
public void dcConfigChangePropagatedAfterRestart() throws Exception {
domainConfig.getSlaveConfiguration().setCachedDC(true);
domainManager = DomainTestSupport.create(domainConfig);
domainManager.start();
stopSlaveAndWaitForUnregistration();
assertEquals(false, domainManager.getDomainSlaveLifecycleUtil().isHostControllerStarted());
domainManager.getDomainMasterLifecycleUtil()
.executeForResult(getCreateOperationTestLoggingCategory());
domainManager.stop();
// starting domain once again - reusing already changed config files
domainConfig.getMasterConfiguration().setRewriteConfigFiles(false);
domainConfig.getSlaveConfiguration().setRewriteConfigFiles(false);
// HC started with old domain.cached-remote.xml
domainManager.getDomainSlaveLifecycleUtil().startAsync();
try (final DomainClient clientSlave = getDomainClient(domainConfig.getSlaveConfiguration())) {
waitForHostControllerBeingStarted(TIMEOUT_S, clientSlave);
waitForServersBeingStarted(TIMEOUT_S, clientSlave);
}
// DC started where domain config contains a configuration change (a new logger was created)
domainManager.getDomainMasterLifecycleUtil().startAsync();
try (final DomainClient clientMaster = getDomainClient(domainConfig.getSlaveConfiguration())) {
waitForHostControllerBeingStarted(TIMEOUT_S, clientMaster);
waitForServersBeingStarted(TIMEOUT_S, clientMaster);
}
// timeout waits to get changes from DC propagated to HC
// by WFCORE-2331 the host controller log file should advert need of configuration change
runWithTimeout(TIMEOUT_S, () -> checkHostControllerLogFile(domainConfig.getSlaveConfiguration(), "WFLYHC0202"));
}
/**
* <p>
* If configuration change (new configuration coming from DC) requires reload then reload needs
* to be advertised at HC’s domain model.
* <p>
* DC is up, HC is up. HC is started <b>without any special flag</b>.
* When DC provides change in settings the HC should show info that reload is needed.
*/
@Test
public void reloadAdvertisedAfterDcModelChange() throws Exception {
domainManager = DomainTestSupport.create(domainConfig);
domainManager.start();
final boolean isAddLoggingApiDependencies = setLoggingApiDependencies(domainManager.getDomainMasterLifecycleUtil().getDomainClient());
// property was changed - checking if change is visible at profile level
ModelNode profileRead = readLoggingApiDependencies(domainManager.getDomainSlaveLifecycleUtil().getDomainClient());
assertEquals("Expecting value of attribute 'add-logging-api-dependencies' was changed" + profileRead,
isAddLoggingApiDependencies, profileRead.get("result").asBoolean());
// property was changed - checking if change is visible at HC
ModelNode hostRead = readLoggingApiDependenciesAtServerOtherTwo(domainManager.getDomainSlaveLifecycleUtil().getDomainClient());
assertEquals("Read operation should suceed", SUCCESS, hostRead.get(OUTCOME).asString());
assertEquals("Expecting value of attribute 'add-logging-api-dependencies' was changed" + hostRead,
isAddLoggingApiDependencies, hostRead.get("result").asBoolean());
assertEquals("Expecting change of attribute 'add-logging-api-dependencies' requests a reload: " + hostRead,
"reload-required", hostRead.get("response-headers").get("process-state").asString());
}
/**
* <p>
* If configuration change (new configuration coming from DC) requires reload then reload needs
* to be advertised at HC’s domain model.
* <p>
* <ol>
* <li>DC is up, HC is started with <code>--backup</code> to get created a <code>domain.cached-remote.xml</code>.</li>
* <li>HC is stopped and configuration change which requires reload is done at DC and DC is stopped.</li>
* <li>HC is started with <code>--cached-dc</code> and boot-up with config from <code>domain.cached-remote.xml</code>.</li>
* <li>DC is started and configuration change should be propagated to HC with announcement that reload is needed</li>
* </ol>
*/
@Test
public void reloadAdvertisedAfterDcModelChangeWithShutdown() throws Exception {
// slave is started with backup parameter but not with cached dc
domainConfig.getSlaveConfiguration().setBackupDC(true).setCachedDC(false);
domainManager = DomainTestSupport.create(domainConfig);
domainManager.start();
// domain.cached-remote.xml was created now stop slave HC
stopSlaveAndWaitForUnregistration();
// changing parameter which needs reload
final DomainClient client = domainManager.getDomainMasterLifecycleUtil().getDomainClient();
final boolean isAddLoggingApiDependencies = setLoggingApiDependencies(client);
final ModelNode profileRead = readLoggingApiDependencies(client);
assertEquals("Expecting value of attribute 'add-logging-api-dependencies' was changed" + profileRead,
isAddLoggingApiDependencies, profileRead.get("result").asBoolean());
domainManager.stop();
// starting domain once again - reusing already changed config files
// slave will be started with cached dc parameter but not with backup parameter
domainConfig.getMasterConfiguration().setRewriteConfigFiles(false);
domainConfig.getSlaveConfiguration()
.setRewriteConfigFiles(false).setBackupDC(false).setCachedDC(true);
// starting HC with old domain.cached-remote.xml
domainManager.getDomainSlaveLifecycleUtil().startAsync();
try (final DomainClient clientSlave = getDomainClient(domainConfig.getSlaveConfiguration())) {
waitForHostControllerBeingStarted(TIMEOUT_S, clientSlave);
waitForServersBeingStarted(TIMEOUT_S, clientSlave);
}
// starting DC where domain config contains a configuration change
domainManager.getDomainMasterLifecycleUtil().startAsync();
try (final DomainClient clientMaster = getDomainClient(domainConfig.getSlaveConfiguration())) {
waitForHostControllerBeingStarted(TIMEOUT_S, clientMaster);
waitForServersBeingStarted(TIMEOUT_S, clientMaster);
}
try (final DomainClient clientSlave = getDomainClient(domainConfig.getSlaveConfiguration())) {
runWithTimeout(TIMEOUT_S, () -> {
ModelNode hostRead = readLoggingApiDependenciesAtServerOtherTwo(clientSlave);
assertEquals("Read operation should suceed", SUCCESS, hostRead.get(OUTCOME).asString());
assertEquals("Expecting change of attribute 'add-logging-api-dependencies' requests a reload: " + hostRead,
"reload-required", hostRead.get("response-headers").get("process-state").asString());
});
}
try (final DomainClient clientMaster = getDomainClient(domainConfig.getMasterConfiguration())) {
reloadServers(clientMaster);
}
try (final DomainClient clientMaster = getDomainClient(domainConfig.getMasterConfiguration())) {
runWithTimeout(TIMEOUT_S, () -> {
ModelNode hostRead = readLoggingApiDependenciesAtServerOtherTwo(clientMaster);
assertEquals("Expecting value of attribute 'add-logging-api-dependencies' changed: " + hostRead,
isAddLoggingApiDependencies, hostRead.get("result").asBoolean());
});
}
// by WFCORE-2331 the host controller log file should advert need of configuration change
runWithTimeout(TIMEOUT_S, () -> checkHostControllerLogFile(domainConfig.getSlaveConfiguration(), "WFLYHC0202"));
}
private void test_hcStartsWhenCachedConfigAvailable(DomainTestSupport.Configuration domainConfig) throws Exception {
domainManager = DomainTestSupport.create(domainConfig);
domainManager.start();
DomainLifecycleUtil masterHost = domainManager.getDomainMasterLifecycleUtil();
DomainLifecycleUtil slaveHost = domainManager.getDomainSlaveLifecycleUtil();
Assert.assertTrue("Master should be started", masterHost.areServersStarted());
Assert.assertTrue("Slave should be started", slaveHost.areServersStarted());
domainManager.stop();
domainConfig.getSlaveConfiguration().setCachedDC(true);
slaveHost.startAsync();
// check that HC and servers were started
try (final DomainClient client = getDomainClient(domainConfig.getSlaveConfiguration())) {
waitForHostControllerBeingStarted(TIMEOUT_S, client);
waitForServersBeingStarted(TIMEOUT_S, client);
}
}
/**
* Checking that HC waits for DC being started when HC is started first.
*/
private void test_hcWaitsForDcBeingStarted(DomainTestSupport.Configuration domainConfig) throws Exception {
domainManager = DomainTestSupport.create(domainConfig);
domainManager.getDomainSlaveLifecycleUtil().startAsync();
try (final DomainClient client = getDomainClient(domainConfig.getSlaveConfiguration())) {
// getting statuses of servers from slave HC as waiting for HC being ready
runWithTimeout(TimeoutUtil.adjust(5), () -> client.getServerStatuses());
Assert.fail("DC started with no param, it's waiting for DC but it's not possible to connect to it");
} catch (IllegalStateException ise) {
// as HC should not be started IllegalStateException is expected
}
// after starting DC, HC is ready to use with all its servers
domainManager.getDomainMasterLifecycleUtil().start();
try (final DomainClient client = getDomainClient(domainConfig.getSlaveConfiguration())) {
waitForHostControllerBeingStarted(TIMEOUT_S, client);
waitForServersBeingStarted(TIMEOUT_S, client);
}
}
private DomainClient getDomainClient(WildFlyManagedConfiguration config) throws UnknownHostException {
final InetAddress address = InetAddress.getByName(config.getHostControllerManagementAddress());
final int port = config.getHostControllerManagementPort();
final String protocol = config.getHostControllerManagementProtocol();
return new DomainClientImpl(protocol, address, port);
}
private void waitForHostControllerBeingStarted(long timeoutSeconds, DomainClient client) {
runWithTimeout(timeoutSeconds, () -> client.getServerStatuses());
}
private void waitForServersBeingStarted(long timeoutSeconds, DomainClient client) {
// checking that all serves are started
runWithTimeout(timeoutSeconds, () -> {
client.getServerStatuses().entrySet().forEach(entry -> {
switch(entry.getValue()) {
case DISABLED:
log.tracef("Server '%s' status check skipped as status is %s", entry.getKey(), entry.getValue());
break;
case STARTED:
log.tracef("Server '%s' is started", entry.getKey());
break;
default:
log.tracef("Assert fail: server '%s' with status '%s'", entry.getKey(), entry.getValue());
Assert.fail(String.format("Server '%s' is not started, is in status '%s'",
entry.getKey(), entry.getValue()));
}
});
return null;
});
}
private void runWithTimeout(long timeoutSeconds, Runnable voidFunctionInterface) {
runWithTimeout(timeoutSeconds, () -> {
voidFunctionInterface.run();
return null;
});
}
private <T> T runWithTimeout(long timeoutSeconds, Supplier<T> function) {
final long timeoutTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(timeoutSeconds);
while(true) {
try {
return function.get();
} catch (Throwable t) {
if(timeoutTime < System.currentTimeMillis()) {
throw new IllegalStateException("Function '" + function
+ "' failed to process in " + timeoutSeconds + " s, caused: " + t.getMessage() , t);
}
try {
Thread.sleep(TIMEOUT_SLEEP_MILLIS);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
}
}
private File getDomainCachedRemoteXmlFile(WildFlyManagedConfiguration appConfiguration) {
final File rootDir = new File(appConfiguration.getDomainDirectory());
return new File(rootDir, "configuration" + File.separator + DOMAIN_CACHED_REMOTE_XML_FILE_NAME);
}
private void checkHostControllerLogFile(WildFlyManagedConfiguration appConfiguration, String containString) {
final File logFile = new File(appConfiguration.getDomainDirectory(), "log" + File.separator + "host-controller.log");
Assert.assertTrue("Log file '" + logFile + "' does not exist", logFile.exists());
try {
final String content = com.google.common.io.Files.toString(logFile, Charset.forName("UTF-8"));
Assert.assertTrue("Expecting log file '" + logFile + " contains string '" + containString + "'",
content.contains(containString));
} catch (IOException ioe) {
throw new RuntimeException("Can't read content of file " + logFile, ioe);
}
}
private ModelNode getProfileDefaultLoggingAddr() {
return new ModelNode()
.add(PROFILE, "default")
.add(SUBSYSTEM, "logging");
}
private ModelNode getCreateOperationTestLoggingCategory() {
final ModelNode addrLogger = getProfileDefaultLoggingAddr();
addrLogger.add(LOGGER, TEST_LOGGER_NAME);
final ModelNode createOp = Operations.createAddOperation(addrLogger);
createOp.get("level").set("TRACE");
createOp.get("category").set(TEST_LOGGER_NAME);
return createOp;
}
private ModelNode readResourceTestLoggerFromSlaveHost(DomainClient client) throws IOException {
final ModelNode hostLoggerAddress = new ModelNode()
.add(HOST, "slave")
.add(SERVER, "other-two")
.add(SUBSYSTEM, "logging")
.add(LOGGER, TEST_LOGGER_NAME);
final ModelNode readResourceOp = Operations.createReadResourceOperation(hostLoggerAddress);
final ModelNode result = client.execute(readResourceOp);
assertEquals(SUCCESS, result.get(OUTCOME).asString());
return result;
}
/**
* ls /host=slave/server=other-two/subsystem=logging/logger
*/
private void checkTestLoggerFromSlaveHost(DomainClient client) throws IOException {
final ModelNode result = readResourceTestLoggerFromSlaveHost(client);
assertEquals("Reading logger '" + TEST_LOGGER_NAME + "' resource does not finish with success: " + result,
SUCCESS, result.get(OUTCOME).asString());
}
private ModelNode readLoggingApiDependenciesAtServerOtherTwo(DomainClient client) {
final ModelNode hostLoggingAddress = new ModelNode()
.add(HOST, "slave")
.add(SERVER, "other-two")
.add(SUBSYSTEM, "logging");
final ModelNode readAttributeOp = Operations
.createReadAttributeOperation(hostLoggingAddress, "add-logging-api-dependencies");
try {
final ModelNode result = client.execute(readAttributeOp);
assertEquals(SUCCESS, result.get(OUTCOME).asString());
return result;
} catch (IOException ioe) {
throw new RuntimeException("Can't read attribute 'add-logging-api-dependencies' from address "
+ hostLoggingAddress, ioe);
}
}
private ModelNode readLoggingApiDependencies(DomainClient client) throws IOException {
final ModelNode readAttributeOp = Operations
.createReadAttributeOperation(getProfileDefaultLoggingAddr(), "add-logging-api-dependencies");
final ModelNode result = client.execute(readAttributeOp);
assertEquals(SUCCESS, result.get(OUTCOME).asString());
return result;
}
private boolean setLoggingApiDependencies(DomainClient client) throws IOException {
boolean isAddLoggingApiDependencies = readLoggingApiDependencies(client).get("result").asBoolean();
final ModelNode writeAttributeOp = Operations
.createWriteAttributeOperation(getProfileDefaultLoggingAddr(), "add-logging-api-dependencies", !isAddLoggingApiDependencies);
final ModelNode result = client.execute(writeAttributeOp);
assertEquals(SUCCESS, result.get(OUTCOME).asString());
return !isAddLoggingApiDependencies;
}
private void reloadServers(DomainClient clientMaster) throws IOException {
final ModelNode op = Operations.createOperation("reload-servers");
op.get("blocking").set("true");
final ModelNode result = clientMaster.execute(op);
assertEquals(SUCCESS, result.get(OUTCOME).asString());
}
private void stopSlaveAndWaitForUnregistration() throws InterruptedException {
domainManager.getDomainSlaveLifecycleUtil().stop();
// WFCORE-2836
// this is a bit flaky in CI. It seems that the logger add below begins
// occasionally before the slave host unregisters completely, then when the
// slave unregisters the op is rolled back.
final long deadline = System.currentTimeMillis() + 1000;
while (true) {
if (!domainManager.getDomainSlaveLifecycleUtil().isHostControllerStarted()) {
break;
}
if (System.currentTimeMillis() > deadline) {
break;
}
Thread.sleep(TIMEOUT_SLEEP_MILLIS);
}
}
}
| WFCORE-2836 - better version of verifying the slave has actually deregistered before continuing tests
| testsuite/domain/src/test/java/org/jboss/as/test/integration/domain/cacheddc/CachedDcDomainTestCase.java | WFCORE-2836 - better version of verifying the slave has actually deregistered before continuing tests |
|
Java | apache-2.0 | 35791224ab954e3a271df0862ba6fbc2d6fb3e3c | 0 | sibok666/flowable-engine,flowable/flowable-engine,motorina0/flowable-engine,Activiti/Activiti,yvoswillens/flowable-engine,zwets/flowable-engine,sibok666/flowable-engine,paulstapleton/flowable-engine,marcus-nl/flowable-engine,gro-mar/flowable-engine,roberthafner/flowable-engine,lsmall/flowable-engine,stephraleigh/flowable-engine,motorina0/flowable-engine,stefan-ziel/Activiti,martin-grofcik/flowable-engine,robsoncardosoti/flowable-engine,stefan-ziel/Activiti,yvoswillens/flowable-engine,flowable/flowable-engine,paulstapleton/flowable-engine,marcus-nl/flowable-engine,motorina0/flowable-engine,dbmalkovsky/flowable-engine,paulstapleton/flowable-engine,gro-mar/flowable-engine,Activiti/Activiti,dbmalkovsky/flowable-engine,marcus-nl/flowable-engine,paulstapleton/flowable-engine,martin-grofcik/flowable-engine,yvoswillens/flowable-engine,stefan-ziel/Activiti,sibok666/flowable-engine,lsmall/flowable-engine,roberthafner/flowable-engine,gro-mar/flowable-engine,zwets/flowable-engine,zwets/flowable-engine,lsmall/flowable-engine,dbmalkovsky/flowable-engine,robsoncardosoti/flowable-engine,robsoncardosoti/flowable-engine,martin-grofcik/flowable-engine,zwets/flowable-engine,flowable/flowable-engine,stefan-ziel/Activiti,gro-mar/flowable-engine,roberthafner/flowable-engine,martin-grofcik/flowable-engine,roberthafner/flowable-engine,marcus-nl/flowable-engine,yvoswillens/flowable-engine,stephraleigh/flowable-engine,sibok666/flowable-engine,robsoncardosoti/flowable-engine,stephraleigh/flowable-engine,lsmall/flowable-engine,motorina0/flowable-engine,stephraleigh/flowable-engine,flowable/flowable-engine,dbmalkovsky/flowable-engine | /* 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.activiti.bpmn.converter;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import org.activiti.bpmn.converter.util.BpmnXMLUtil;
import org.activiti.bpmn.model.BaseElement;
import org.activiti.bpmn.model.ManualTask;
import org.activiti.bpmn.model.Task;
/**
* @author Tijs Rademakers
*/
public class TaskXMLConverter extends BaseBpmnXMLConverter {
public static String getXMLType() {
return ELEMENT_TASK;
}
public static Class<? extends BaseElement> getBpmnElementType() {
return Task.class;
}
@Override
protected String getXMLElementName() {
return ELEMENT_TASK;
}
@Override
protected BaseElement convertXMLToElement(XMLStreamReader xtr) throws Exception {
ManualTask manualTask = new ManualTask();
BpmnXMLUtil.addXMLLocation(manualTask, xtr);
parseChildElements(getXMLElementName(), manualTask, xtr);
return manualTask;
}
@Override
protected void writeAdditionalAttributes(BaseElement element, XMLStreamWriter xtw) throws Exception {
}
@Override
protected void writeExtensionChildElements(BaseElement element, XMLStreamWriter xtw) throws Exception {
}
@Override
protected void writeAdditionalChildElements(BaseElement element, XMLStreamWriter xtw) throws Exception {
}
}
| modules/activiti-bpmn-converter/src/main/java/org/activiti/bpmn/converter/TaskXMLConverter.java | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.bpmn.converter;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import org.activiti.bpmn.converter.util.BpmnXMLUtil;
import org.activiti.bpmn.model.BaseElement;
import org.activiti.bpmn.model.ManualTask;
/**
* @author Tijs Rademakers
*/
public class TaskXMLConverter extends BaseBpmnXMLConverter {
public static String getXMLType() {
return ELEMENT_TASK;
}
public static Class<? extends BaseElement> getBpmnElementType() {
return ManualTask.class;
}
@Override
protected String getXMLElementName() {
return ELEMENT_TASK;
}
@Override
protected BaseElement convertXMLToElement(XMLStreamReader xtr) throws Exception {
ManualTask manualTask = new ManualTask();
BpmnXMLUtil.addXMLLocation(manualTask, xtr);
parseChildElements(getXMLElementName(), manualTask, xtr);
return manualTask;
}
@Override
protected void writeAdditionalAttributes(BaseElement element, XMLStreamWriter xtw) throws Exception {
}
@Override
protected void writeExtensionChildElements(BaseElement element, XMLStreamWriter xtw) throws Exception {
}
@Override
protected void writeAdditionalChildElements(BaseElement element, XMLStreamWriter xtw) throws Exception {
}
}
| Fixed Task parsing issue
| modules/activiti-bpmn-converter/src/main/java/org/activiti/bpmn/converter/TaskXMLConverter.java | Fixed Task parsing issue |
|
Java | apache-2.0 | 7aa87503651027c8b3db34c6b6d7ed441497bda5 | 0 | rfoltyns/log4j2-elasticsearch | package org.appenders.log4j2.elasticsearch;
/*-
* #%L
* log4j2-elasticsearch
* %%
* Copyright (C) 2018 Rafal Foltynski
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import org.apache.logging.log4j.core.config.ConfigurationException;
import org.apache.logging.log4j.core.config.Node;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginBuilderAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory;
import org.apache.logging.log4j.core.config.plugins.PluginElement;
import org.apache.logging.log4j.core.config.plugins.validation.constraints.Required;
import org.appenders.core.logging.InternalLogging;
import org.appenders.core.logging.Logger;
import org.appenders.log4j2.elasticsearch.failover.FailoverListener;
import org.appenders.log4j2.elasticsearch.failover.RetryListener;
import org.appenders.log4j2.elasticsearch.spi.BatchEmitterServiceProvider;
/**
* Uses {@link BatchEmitterFactory} SPI to get a {@link BatchEmitter} instance that will hold given items until interval
* or size conditions are met.
*/
@Plugin(name = "AsyncBatchDelivery", category = Node.CATEGORY, elementType = BatchDelivery.ELEMENT_TYPE, printObject = true)
public class AsyncBatchDelivery implements BatchDelivery<String> {
private static final Logger LOG = InternalLogging.getLogger();
private volatile State state = State.STOPPED;
private final BatchOperations batchOperations;
private final BatchEmitter batchEmitter;
private final IndexTemplate indexTemplate;
private final ClientObjectFactory<Object, Object> objectFactory;
private final FailoverPolicy failoverPolicy;
private final long delayShutdownInMillis;
/**
* @param builder {@link Builder} instance
*/
protected AsyncBatchDelivery(Builder builder) {
this.batchOperations = builder.clientObjectFactory.createBatchOperations();
this.batchEmitter = createBatchEmitterServiceProvider()
.createInstance(
builder.batchSize,
builder.deliveryInterval,
builder.clientObjectFactory,
builder.failoverPolicy);
this.indexTemplate = builder.indexTemplate;
this.objectFactory = builder.clientObjectFactory;
this.failoverPolicy = builder.failoverPolicy;
this.delayShutdownInMillis = builder.shutdownDelayMillis;
}
/**
* Transforms given items to client-specific model and adds them to provided {@link BatchEmitter}
*
* @param log batch item source
*/
@Override
public void add(String indexName, String log) {
this.batchEmitter.add(batchOperations.createBatchItem(indexName, log));
}
@Override
public void add(String indexName, ItemSource source) {
this.batchEmitter.add(batchOperations.createBatchItem(indexName, source));
}
protected BatchEmitterServiceProvider createBatchEmitterServiceProvider() {
return new BatchEmitterServiceProvider();
}
protected FailoverListener failoverListener() {
// TODO: consider inverting the hierarchy as it may not be appropriate in this case
return (RetryListener) event -> {
this.add(event.getInfo().getTargetName(), event);
return true;
};
}
@PluginBuilderFactory
public static Builder newBuilder() {
return new Builder();
}
public static class Builder implements org.apache.logging.log4j.core.util.Builder<AsyncBatchDelivery> {
/**
* Default: 1000
*/
public static final int DEFAULT_BATCH_SIZE = 1000;
/**
* Default: 1000 ms
*/
public static final int DEFAULT_DELIVERY_INTERVAL = 1000;
/**
* Default: {@link NoopFailoverPolicy}
*/
public static final FailoverPolicy DEFAULT_FAILOVER_POLICY = new NoopFailoverPolicy();
/**
* Default: 5000 ms
*/
public static final long DEFAULT_SHUTDOWN_DELAY = 5000L;
@PluginElement("elasticsearchClientFactory")
@Required(message = "No Elasticsearch client factory [HCHttp|JestHttp|ElasticsearchBulkProcessor] provided for AsyncBatchDelivery")
private ClientObjectFactory clientObjectFactory;
@PluginBuilderAttribute
private int deliveryInterval = DEFAULT_BATCH_SIZE;
@PluginBuilderAttribute
private int batchSize = DEFAULT_DELIVERY_INTERVAL;
@PluginElement("failoverPolicy")
private FailoverPolicy failoverPolicy = DEFAULT_FAILOVER_POLICY;
@PluginElement("indexTemplate")
private IndexTemplate indexTemplate;
@PluginBuilderAttribute("shutdownDelayMillis")
public long shutdownDelayMillis = DEFAULT_SHUTDOWN_DELAY;
@Override
public AsyncBatchDelivery build() {
if (clientObjectFactory == null) {
throw new ConfigurationException("No Elasticsearch client factory [HCHttp|JestHttp|ElasticsearchBulkProcessor] provided for AsyncBatchDelivery");
}
return new AsyncBatchDelivery(this);
}
public Builder withClientObjectFactory(ClientObjectFactory clientObjectFactory) {
this.clientObjectFactory = clientObjectFactory;
return this;
}
public Builder withDeliveryInterval(int deliveryInterval) {
this.deliveryInterval = deliveryInterval;
return this;
}
public Builder withBatchSize(int batchSize) {
this.batchSize = batchSize;
return this;
}
public Builder withFailoverPolicy(FailoverPolicy failoverPolicy) {
this.failoverPolicy = failoverPolicy;
return this;
}
public Builder withIndexTemplate(IndexTemplate indexTemplate) {
this.indexTemplate = indexTemplate;
return this;
}
public Builder withShutdownDelayMillis(long shutdownDelayMillis) {
this.shutdownDelayMillis = shutdownDelayMillis;
return this;
}
}
// ==========
// LIFECYCLE
// ==========
@Override
public void start() {
if (!objectFactory.isStarted()) {
objectFactory.start();
}
if (indexTemplate != null) {
objectFactory.addOperation(() -> objectFactory.execute(indexTemplate));
}
batchEmitter.start();
if (!LifeCycle.of(failoverPolicy).isStarted()) {
failoverPolicy.addListener(failoverListener());
LifeCycle.of(failoverPolicy).start();
}
state = State.STARTED;
}
@Override
public void stop() {
LOG.debug("Stopping {}", getClass().getSimpleName());
if (!LifeCycle.of(failoverPolicy).isStopped()) {
// Shutdown MUST happen in background to allow the execution to continue
// and allow last items flushed by emitter to fail (in case of outage downstream)
// and get handled properly
LifeCycle.of(failoverPolicy).stop(delayShutdownInMillis, true);
}
if (!batchEmitter.isStopped()) {
batchEmitter.stop(delayShutdownInMillis, false);
}
if (!objectFactory.isStopped()) {
objectFactory.stop();
}
state = State.STOPPED;
LOG.debug("{} stopped", getClass().getSimpleName());
}
@Override
public boolean isStarted() {
return state == State.STARTED;
}
@Override
public boolean isStopped() {
return state == State.STOPPED;
}
}
| log4j2-elasticsearch-core/src/main/java/org/appenders/log4j2/elasticsearch/AsyncBatchDelivery.java | package org.appenders.log4j2.elasticsearch;
/*-
* #%L
* log4j2-elasticsearch
* %%
* Copyright (C) 2018 Rafal Foltynski
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import org.apache.logging.log4j.core.config.ConfigurationException;
import org.apache.logging.log4j.core.config.Node;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginBuilderAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory;
import org.apache.logging.log4j.core.config.plugins.PluginElement;
import org.apache.logging.log4j.core.config.plugins.validation.constraints.Required;
import org.appenders.core.logging.InternalLogging;
import org.appenders.core.logging.Logger;
import org.appenders.log4j2.elasticsearch.failover.FailoverListener;
import org.appenders.log4j2.elasticsearch.failover.RetryListener;
import org.appenders.log4j2.elasticsearch.spi.BatchEmitterServiceProvider;
/**
* Uses {@link BatchEmitterFactory} SPI to get a {@link BatchEmitter} instance that will hold given items until interval
* or size conditions are met.
*/
@Plugin(name = "AsyncBatchDelivery", category = Node.CATEGORY, elementType = BatchDelivery.ELEMENT_TYPE, printObject = true)
public class AsyncBatchDelivery implements BatchDelivery<String> {
private static final Logger LOG = InternalLogging.getLogger();
private volatile State state = State.STOPPED;
private final BatchOperations batchOperations;
private final BatchEmitter batchEmitter;
private final IndexTemplate indexTemplate;
private final ClientObjectFactory<Object, Object> objectFactory;
private final FailoverPolicy failoverPolicy;
private final long delayShutdownInMillis;
/**
* @param builder {@link Builder} instance
*/
protected AsyncBatchDelivery(Builder builder) {
this.batchOperations = builder.clientObjectFactory.createBatchOperations();
this.batchEmitter = createBatchEmitterServiceProvider()
.createInstance(
builder.batchSize,
builder.deliveryInterval,
builder.clientObjectFactory,
builder.failoverPolicy);
this.indexTemplate = builder.indexTemplate;
this.objectFactory = builder.clientObjectFactory;
this.failoverPolicy = builder.failoverPolicy;
this.delayShutdownInMillis = builder.shutdownDelayMillis;
}
/**
* Transforms given items to client-specific model and adds them to provided {@link BatchEmitter}
*
* @param log batch item source
*/
@Override
public void add(String indexName, String log) {
this.batchEmitter.add(batchOperations.createBatchItem(indexName, log));
}
@Override
public void add(String indexName, ItemSource source) {
this.batchEmitter.add(batchOperations.createBatchItem(indexName, source));
}
protected BatchEmitterServiceProvider createBatchEmitterServiceProvider() {
return new BatchEmitterServiceProvider();
}
protected FailoverListener failoverListener() {
// TODO: consider inverting the hierarchy as it may not be appropriate in this case
return (RetryListener) event -> {
this.add(event.getInfo().getTargetName(), event);
return true;
};
}
@PluginBuilderFactory
public static Builder newBuilder() {
return new Builder();
}
public static class Builder implements org.apache.logging.log4j.core.util.Builder<AsyncBatchDelivery> {
/**
* Default: 1000
*/
public static final int DEFAULT_BATCH_SIZE = 1000;
/**
* Default: 1000 ms
*/
public static final int DEFAULT_DELIVERY_INTERVAL = 1000;
/**
* Default: {@link NoopFailoverPolicy}
*/
public static final FailoverPolicy DEFAULT_FAILOVER_POLICY = new NoopFailoverPolicy();
/**
* Default: 5000 ms
*/
public static final long DEFAULT_SHUTDOWN_DELAY = 5000L;
@PluginElement("elasticsearchClientFactory")
@Required(message = "No Elasticsearch client factory [JestHttp|ElasticsearchBulkProcessor] provided for AsyncBatchDelivery")
private ClientObjectFactory clientObjectFactory;
@PluginBuilderAttribute
private int deliveryInterval = DEFAULT_BATCH_SIZE;
@PluginBuilderAttribute
private int batchSize = DEFAULT_DELIVERY_INTERVAL;
@PluginElement("failoverPolicy")
private FailoverPolicy failoverPolicy = DEFAULT_FAILOVER_POLICY;
@PluginElement("indexTemplate")
private IndexTemplate indexTemplate;
@PluginBuilderAttribute("shutdownDelayMillis")
public long shutdownDelayMillis = DEFAULT_SHUTDOWN_DELAY;
@Override
public AsyncBatchDelivery build() {
if (clientObjectFactory == null) {
throw new ConfigurationException("No Elasticsearch client factory [JestHttp|ElasticsearchBulkProcessor] provided for AsyncBatchDelivery");
}
return new AsyncBatchDelivery(this);
}
public Builder withClientObjectFactory(ClientObjectFactory clientObjectFactory) {
this.clientObjectFactory = clientObjectFactory;
return this;
}
public Builder withDeliveryInterval(int deliveryInterval) {
this.deliveryInterval = deliveryInterval;
return this;
}
public Builder withBatchSize(int batchSize) {
this.batchSize = batchSize;
return this;
}
public Builder withFailoverPolicy(FailoverPolicy failoverPolicy) {
this.failoverPolicy = failoverPolicy;
return this;
}
public Builder withIndexTemplate(IndexTemplate indexTemplate) {
this.indexTemplate = indexTemplate;
return this;
}
public Builder withShutdownDelayMillis(long shutdownDelayMillis) {
this.shutdownDelayMillis = shutdownDelayMillis;
return this;
}
}
// ==========
// LIFECYCLE
// ==========
@Override
public void start() {
if (!objectFactory.isStarted()) {
objectFactory.start();
}
if (indexTemplate != null) {
objectFactory.addOperation(() -> objectFactory.execute(indexTemplate));
}
batchEmitter.start();
if (!LifeCycle.of(failoverPolicy).isStarted()) {
failoverPolicy.addListener(failoverListener());
LifeCycle.of(failoverPolicy).start();
}
state = State.STARTED;
}
@Override
public void stop() {
LOG.debug("Stopping {}", getClass().getSimpleName());
if (!LifeCycle.of(failoverPolicy).isStopped()) {
// Shutdown MUST happen in background to allow the execution to continue
// and allow last items flushed by emitter to fail (in case of outage downstream)
// and get handled properly
LifeCycle.of(failoverPolicy).stop(delayShutdownInMillis, true);
}
if (!batchEmitter.isStopped()) {
batchEmitter.stop(delayShutdownInMillis, false);
}
if (!objectFactory.isStopped()) {
objectFactory.stop();
}
state = State.STOPPED;
LOG.debug("{} stopped", getClass().getSimpleName());
}
@Override
public boolean isStarted() {
return state == State.STARTED;
}
@Override
public boolean isStopped() {
return state == State.STOPPED;
}
}
| Configuration error messages updated
| log4j2-elasticsearch-core/src/main/java/org/appenders/log4j2/elasticsearch/AsyncBatchDelivery.java | Configuration error messages updated |
|
Java | apache-2.0 | 8e7691a1337d4d838815780a33e208862be755ad | 0 | nssales/OG-Platform,DevStreet/FinanceAnalytics,nssales/OG-Platform,ChinaQuants/OG-Platform,jerome79/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling,jeorme/OG-Platform,jerome79/OG-Platform,jeorme/OG-Platform,jerome79/OG-Platform,jerome79/OG-Platform,codeaudit/OG-Platform,codeaudit/OG-Platform,nssales/OG-Platform,codeaudit/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,ChinaQuants/OG-Platform,codeaudit/OG-Platform,jeorme/OG-Platform,McLeodMoores/starling,McLeodMoores/starling,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,nssales/OG-Platform,McLeodMoores/starling,jeorme/OG-Platform | /**
* Copyright (C) 2009 - 2010 by OpenGamma Inc.
*
* Please see distribution for license.
*/
package com.opengamma.engine.historicaldata;
import java.io.Serializable;
import javax.time.calendar.LocalDate;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.event.RegisteredEventListeners;
import net.sf.ehcache.store.MemoryStoreEvictionPolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.opengamma.id.IdentifierBundle;
import com.opengamma.id.UniqueIdentifier;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.ehcache.EHCacheUtils;
import com.opengamma.util.timeseries.localdate.LocalDateDoubleTimeSeries;
import com.opengamma.util.tuple.ObjectsPair;
import com.opengamma.util.tuple.Pair;
/**
*
*/
public class EHCachingHistoricalDataProvider implements HistoricalDataSource {
private static final Logger s_logger = LoggerFactory.getLogger(EHCachingHistoricalDataProvider.class);
private static final boolean INCLUDE_LAST_DAY = true;
private static final String CACHE_NAME = "HistoricalDataCache";
private final HistoricalDataSource _underlying;
private final CacheManager _manager;
private final Cache _cache;
public EHCachingHistoricalDataProvider(HistoricalDataSource underlying, CacheManager cacheManager, int maxElementsInMemory, MemoryStoreEvictionPolicy memoryStoreEvictionPolicy,
boolean overflowToDisk, String diskStorePath, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds, boolean diskPersistent, long diskExpiryThreadIntervalSeconds,
RegisteredEventListeners registeredEventListeners) {
ArgumentChecker.notNull(underlying, "Underlying Historical Data Provider");
ArgumentChecker.notNull(cacheManager, "cacheManager");
_underlying = underlying;
_manager = cacheManager;
EHCacheUtils.addCache(_manager, CACHE_NAME, maxElementsInMemory, memoryStoreEvictionPolicy, overflowToDisk, diskStorePath, eternal, timeToLiveSeconds, timeToIdleSeconds, diskPersistent,
diskExpiryThreadIntervalSeconds, registeredEventListeners);
_cache = EHCacheUtils.getCacheFromManager(_manager, CACHE_NAME);
}
public EHCachingHistoricalDataProvider(HistoricalDataSource underlying, CacheManager manager) {
ArgumentChecker.notNull(underlying, "Underlying Historical Data Provider");
ArgumentChecker.notNull(manager, "Cache Manager");
_underlying = underlying;
EHCacheUtils.addCache(manager, CACHE_NAME);
_cache = EHCacheUtils.getCacheFromManager(manager, CACHE_NAME);
_manager = manager;
}
/**
* @return the underlying
*/
public HistoricalDataSource getUnderlying() {
return _underlying;
}
/**
* @return the CacheManager
*/
public CacheManager getCacheManager() {
return _manager;
}
@Override
public Pair<UniqueIdentifier, LocalDateDoubleTimeSeries> getHistoricalData(IdentifierBundle identifiers, String dataSource, String dataProvider, String field) {
MetaDataKey key = new MetaDataKey(identifiers, dataSource, dataProvider, field);
Element element = _cache.get(key);
if (element != null) {
Serializable value = element.getValue();
if (value instanceof UniqueIdentifier) {
UniqueIdentifier uid = (UniqueIdentifier) value;
s_logger.debug("retrieved UID: {} from cache", uid);
LocalDateDoubleTimeSeries timeSeries = getHistoricalData(uid);
return new ObjectsPair<UniqueIdentifier, LocalDateDoubleTimeSeries>(uid, timeSeries);
} else {
s_logger.warn("returned object {} from cache, not a UniqueIdentifier", value);
return null;
}
} else {
Pair<UniqueIdentifier, LocalDateDoubleTimeSeries> tsPair = _underlying.getHistoricalData(identifiers, dataSource, dataProvider, field);
_cache.put(new Element(key, tsPair.getFirst()));
_cache.put(new Element(tsPair.getFirst(), tsPair.getSecond()));
return tsPair;
}
}
@Override
public Pair<UniqueIdentifier, LocalDateDoubleTimeSeries> getHistoricalData(IdentifierBundle dsids, String dataSource, String dataProvider, String field, LocalDate start, LocalDate end) {
Pair<UniqueIdentifier, LocalDateDoubleTimeSeries> tsPair = getHistoricalData(dsids, dataSource, dataProvider, field);
if (tsPair != null) {
LocalDateDoubleTimeSeries timeSeries = (LocalDateDoubleTimeSeries) tsPair.getSecond().subSeries(start, true, end, INCLUDE_LAST_DAY);
return Pair.of(tsPair.getKey(), timeSeries);
} else {
return null;
}
}
@Override
public LocalDateDoubleTimeSeries getHistoricalData(UniqueIdentifier uid) {
Element element = _cache.get(uid);
if (element != null) {
Serializable value = element.getValue();
if (value instanceof LocalDateDoubleTimeSeries) {
LocalDateDoubleTimeSeries ts = (LocalDateDoubleTimeSeries) value;
s_logger.debug("retrieved time series: {} from cache", ts);
return ts;
} else {
s_logger.error("returned object {} from cache, not a LocalDateDoubleTimeSeries", value);
return null;
}
} else {
LocalDateDoubleTimeSeries ts = _underlying.getHistoricalData(uid);
_cache.put(new Element(uid, ts));
return ts;
}
}
@Override
public LocalDateDoubleTimeSeries getHistoricalData(UniqueIdentifier uid, LocalDate start, LocalDate end) {
LocalDateDoubleTimeSeries ts = getHistoricalData(uid);
if (ts != null) {
return (LocalDateDoubleTimeSeries) ts.subSeries(start, true, end, INCLUDE_LAST_DAY);
} else {
return null;
}
}
private static class MetaDataKey implements Serializable {
private final IdentifierBundle _dsids;
private final String _dataSource;
private final String _dataProvider;
private final String _field;
public MetaDataKey(IdentifierBundle dsids, String dataSource, String dataProvider, String field) {
_dsids = dsids;
_dataSource = dataSource;
_dataProvider = dataProvider;
_field = field;
}
@Override
public int hashCode() {
final int shift = 17;
int hc = _dsids.hashCode();
hc *= shift;
if (_dataSource != null) {
hc += _dataSource.hashCode();
}
hc *= shift;
if (_dataProvider != null) {
hc += _dataProvider.hashCode();
}
hc *= shift;
if (_field != null) {
hc += _field.hashCode();
}
return hc;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof MetaDataKey)) {
return false;
}
MetaDataKey other = (MetaDataKey) obj;
if (_field == null) {
if (other._field != null) {
return false;
}
} else if (!_field.equals(other._field)) {
return false;
}
if (_dsids == null) {
if (other._dsids != null) {
return false;
}
} else if (!_dsids.equals(other._dsids)) {
return false;
}
if (_dataProvider == null) {
if (other._dataProvider != null) {
return false;
}
} else if (!_dataProvider.equals(other._dataProvider)) {
return false;
}
if (_dataSource == null) {
if (other._dataSource != null) {
return false;
}
} else if (!_dataSource.equals(other._dataSource)) {
return false;
}
return true;
}
}
@Override
public Pair<UniqueIdentifier, LocalDateDoubleTimeSeries> getHistoricalData(IdentifierBundle identifiers) {
MetaDataKey key = new MetaDataKey(identifiers, null, null, null);
Element element = _cache.get(key);
if (element != null) {
Serializable value = element.getValue();
if (value instanceof UniqueIdentifier) {
UniqueIdentifier uid = (UniqueIdentifier) value;
s_logger.debug("retrieved UID: {} from cache", uid);
LocalDateDoubleTimeSeries timeSeries = getHistoricalData(uid);
return new ObjectsPair<UniqueIdentifier, LocalDateDoubleTimeSeries>(uid, timeSeries);
} else {
s_logger.warn("returned object {} from cache, not a UniqueIdentifier", value);
return null;
}
} else {
Pair<UniqueIdentifier, LocalDateDoubleTimeSeries> tsPair = _underlying.getHistoricalData(identifiers);
_cache.put(new Element(key, tsPair.getFirst()));
_cache.put(new Element(tsPair.getFirst(), tsPair.getSecond()));
return tsPair;
}
}
@Override
public Pair<UniqueIdentifier, LocalDateDoubleTimeSeries> getHistoricalData(IdentifierBundle identifiers, LocalDate start, LocalDate end) {
Pair<UniqueIdentifier, LocalDateDoubleTimeSeries> tsPair = getHistoricalData(identifiers);
if (tsPair != null) {
LocalDateDoubleTimeSeries timeSeries = (LocalDateDoubleTimeSeries) tsPair.getSecond().subSeries(start, true, end, INCLUDE_LAST_DAY);
return Pair.of(tsPair.getKey(), timeSeries);
} else {
return null;
}
}
@Override
public Pair<UniqueIdentifier, LocalDateDoubleTimeSeries> getHistoricalData(IdentifierBundle identifiers, LocalDate start, boolean inclusiveStart, LocalDate end, boolean exclusiveEnd) {
Pair<UniqueIdentifier, LocalDateDoubleTimeSeries> tsPair = getHistoricalData(identifiers);
if (tsPair != null && tsPair.getValue() != null) {
LocalDateDoubleTimeSeries timeSeries = (LocalDateDoubleTimeSeries) tsPair.getSecond().subSeries(start, inclusiveStart, end, !exclusiveEnd);
return Pair.of(tsPair.getKey(), timeSeries);
} else {
return null;
}
}
@Override
public Pair<UniqueIdentifier, LocalDateDoubleTimeSeries> getHistoricalData(IdentifierBundle identifiers, String dataSource, String dataProvider, String field, LocalDate start,
boolean inclusiveStart, LocalDate end, boolean exclusiveEnd) {
Pair<UniqueIdentifier, LocalDateDoubleTimeSeries> tsPair = getHistoricalData(identifiers, dataSource, dataProvider, field);
if (tsPair != null && tsPair.getValue() != null) {
LocalDateDoubleTimeSeries timeSeries = (LocalDateDoubleTimeSeries) tsPair.getSecond().subSeries(start, inclusiveStart, end, !exclusiveEnd);
return Pair.of(tsPair.getKey(), timeSeries);
} else {
return null;
}
}
@Override
public LocalDateDoubleTimeSeries getHistoricalData(UniqueIdentifier uid, LocalDate start, boolean inclusiveStart, LocalDate end, boolean exclusiveEnd) {
LocalDateDoubleTimeSeries timeseries = getHistoricalData(uid);
if (timeseries != null) {
return (LocalDateDoubleTimeSeries) timeseries.subSeries(start, inclusiveStart, end, !exclusiveEnd);
} else {
return null;
}
}
}
| projects/OG-Engine/src/com/opengamma/engine/historicaldata/EHCachingHistoricalDataProvider.java | /**
* Copyright (C) 2009 - 2010 by OpenGamma Inc.
*
* Please see distribution for license.
*/
package com.opengamma.engine.historicaldata;
import java.io.Serializable;
import javax.time.calendar.LocalDate;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.event.RegisteredEventListeners;
import net.sf.ehcache.store.MemoryStoreEvictionPolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.opengamma.id.IdentifierBundle;
import com.opengamma.id.UniqueIdentifier;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.ehcache.EHCacheUtils;
import com.opengamma.util.timeseries.localdate.LocalDateDoubleTimeSeries;
import com.opengamma.util.tuple.ObjectsPair;
import com.opengamma.util.tuple.Pair;
/**
*
*/
public class EHCachingHistoricalDataProvider implements HistoricalDataSource {
private static final Logger s_logger = LoggerFactory.getLogger(EHCachingHistoricalDataProvider.class);
private static final boolean INCLUDE_LAST_DAY = true;
private static final String CACHE_NAME = "HistoricalDataCache";
private final HistoricalDataSource _underlying;
private final CacheManager _manager;
private final Cache _cache;
public EHCachingHistoricalDataProvider(HistoricalDataSource underlying, CacheManager cacheManager, int maxElementsInMemory, MemoryStoreEvictionPolicy memoryStoreEvictionPolicy,
boolean overflowToDisk, String diskStorePath, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds, boolean diskPersistent, long diskExpiryThreadIntervalSeconds,
RegisteredEventListeners registeredEventListeners) {
ArgumentChecker.notNull(underlying, "Underlying Historical Data Provider");
ArgumentChecker.notNull(cacheManager, "cacheManager");
_underlying = underlying;
_manager = cacheManager;
EHCacheUtils.addCache(_manager, CACHE_NAME, maxElementsInMemory, memoryStoreEvictionPolicy, overflowToDisk, diskStorePath, eternal, timeToLiveSeconds, timeToIdleSeconds, diskPersistent,
diskExpiryThreadIntervalSeconds, registeredEventListeners);
_cache = EHCacheUtils.getCacheFromManager(_manager, CACHE_NAME);
}
public EHCachingHistoricalDataProvider(HistoricalDataSource underlying, CacheManager manager) {
ArgumentChecker.notNull(underlying, "Underlying Historical Data Provider");
ArgumentChecker.notNull(manager, "Cache Manager");
_underlying = underlying;
EHCacheUtils.addCache(manager, CACHE_NAME);
_cache = EHCacheUtils.getCacheFromManager(manager, CACHE_NAME);
_manager = manager;
}
/**
* @return the underlying
*/
public HistoricalDataSource getUnderlying() {
return _underlying;
}
/**
* @return the CacheManager
*/
public CacheManager getCacheManager() {
return _manager;
}
@Override
public Pair<UniqueIdentifier, LocalDateDoubleTimeSeries> getHistoricalData(IdentifierBundle identifiers, String dataSource, String dataProvider, String field) {
MetaDataKey key = new MetaDataKey(identifiers, dataSource, dataProvider, field);
Element element = _cache.get(key);
if (element != null) {
Serializable value = element.getValue();
if (value instanceof UniqueIdentifier) {
UniqueIdentifier uid = (UniqueIdentifier) value;
s_logger.debug("retrieved UID: {} from cache", uid);
LocalDateDoubleTimeSeries timeSeries = getHistoricalData(uid);
return new ObjectsPair<UniqueIdentifier, LocalDateDoubleTimeSeries>(uid, timeSeries);
} else {
s_logger.warn("returned object {} from cache, not a UniqueIdentifier", value);
return null;
}
} else {
Pair<UniqueIdentifier, LocalDateDoubleTimeSeries> tsPair = _underlying.getHistoricalData(identifiers, dataSource, dataProvider, field);
_cache.put(new Element(key, tsPair.getFirst()));
_cache.put(new Element(tsPair.getFirst(), tsPair.getSecond()));
return tsPair;
}
}
@Override
public Pair<UniqueIdentifier, LocalDateDoubleTimeSeries> getHistoricalData(IdentifierBundle dsids, String dataSource, String dataProvider, String field, LocalDate start, LocalDate end) {
Pair<UniqueIdentifier, LocalDateDoubleTimeSeries> tsPair = getHistoricalData(dsids, dataSource, dataProvider, field);
if (tsPair != null) {
LocalDateDoubleTimeSeries timeSeries = (LocalDateDoubleTimeSeries) tsPair.getSecond().subSeries(start, true, end, INCLUDE_LAST_DAY);
return Pair.of(tsPair.getKey(), timeSeries);
} else {
return null;
}
}
@Override
public LocalDateDoubleTimeSeries getHistoricalData(UniqueIdentifier uid) {
Element element = _cache.get(uid);
if (element != null) {
Serializable value = element.getValue();
if (value instanceof LocalDateDoubleTimeSeries) {
LocalDateDoubleTimeSeries ts = (LocalDateDoubleTimeSeries) value;
s_logger.debug("retrieved time series: {} from cache", ts);
return ts;
} else {
s_logger.error("returned object {} from cache, not a LocalDateDoubleTimeSeries", value);
return null;
}
} else {
LocalDateDoubleTimeSeries ts = _underlying.getHistoricalData(uid);
_cache.put(new Element(uid, ts));
return ts;
}
}
@Override
public LocalDateDoubleTimeSeries getHistoricalData(UniqueIdentifier uid, LocalDate start, LocalDate end) {
LocalDateDoubleTimeSeries ts = getHistoricalData(uid);
if (ts != null) {
return (LocalDateDoubleTimeSeries) ts.subSeries(start, true, end, INCLUDE_LAST_DAY);
} else {
return null;
}
}
private static class MetaDataKey implements Serializable {
private final IdentifierBundle _dsids;
private final String _dataSource;
private final String _dataProvider;
private final String _field;
public MetaDataKey(IdentifierBundle dsids, String dataSource, String dataProvider, String field) {
_dsids = dsids;
_dataSource = dataSource;
_dataProvider = dataProvider;
_field = field;
}
@Override
public int hashCode() {
return _dsids.hashCode() ^ _field.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof MetaDataKey)) {
return false;
}
MetaDataKey other = (MetaDataKey) obj;
if (_field == null) {
if (other._field != null) {
return false;
}
} else if (!_field.equals(other._field)) {
return false;
}
if (_dsids == null) {
if (other._dsids != null) {
return false;
}
} else if (!_dsids.equals(other._dsids)) {
return false;
}
if (_dataProvider == null) {
if (other._dataProvider != null) {
return false;
}
} else if (!_dataProvider.equals(other._dataProvider)) {
return false;
}
if (_dataSource == null) {
if (other._dataSource != null) {
return false;
}
} else if (!_dataSource.equals(other._dataSource)) {
return false;
}
return true;
}
}
@Override
public Pair<UniqueIdentifier, LocalDateDoubleTimeSeries> getHistoricalData(IdentifierBundle identifiers) {
return getHistoricalData(identifiers, null, null, null);
}
@Override
public Pair<UniqueIdentifier, LocalDateDoubleTimeSeries> getHistoricalData(IdentifierBundle identifiers, LocalDate start, LocalDate end) {
Pair<UniqueIdentifier, LocalDateDoubleTimeSeries> tsPair = getHistoricalData(identifiers);
if (tsPair != null) {
LocalDateDoubleTimeSeries timeSeries = (LocalDateDoubleTimeSeries) tsPair.getSecond().subSeries(start, true, end, INCLUDE_LAST_DAY);
return Pair.of(tsPair.getKey(), timeSeries);
} else {
return null;
}
}
@Override
public Pair<UniqueIdentifier, LocalDateDoubleTimeSeries> getHistoricalData(IdentifierBundle identifiers, LocalDate start, boolean inclusiveStart, LocalDate end, boolean exclusiveEnd) {
Pair<UniqueIdentifier, LocalDateDoubleTimeSeries> tsPair = getHistoricalData(identifiers);
if (tsPair != null && tsPair.getValue() != null) {
LocalDateDoubleTimeSeries timeSeries = (LocalDateDoubleTimeSeries) tsPair.getSecond().subSeries(start, inclusiveStart, end, !exclusiveEnd);
return Pair.of(tsPair.getKey(), timeSeries);
} else {
return null;
}
}
@Override
public Pair<UniqueIdentifier, LocalDateDoubleTimeSeries> getHistoricalData(IdentifierBundle identifiers, String dataSource, String dataProvider, String field, LocalDate start,
boolean inclusiveStart, LocalDate end, boolean exclusiveEnd) {
Pair<UniqueIdentifier, LocalDateDoubleTimeSeries> tsPair = getHistoricalData(identifiers, dataSource, dataProvider, field);
if (tsPair != null && tsPair.getValue() != null) {
LocalDateDoubleTimeSeries timeSeries = (LocalDateDoubleTimeSeries) tsPair.getSecond().subSeries(start, inclusiveStart, end, !exclusiveEnd);
return Pair.of(tsPair.getKey(), timeSeries);
} else {
return null;
}
}
@Override
public LocalDateDoubleTimeSeries getHistoricalData(UniqueIdentifier uid, LocalDate start, boolean inclusiveStart, LocalDate end, boolean exclusiveEnd) {
LocalDateDoubleTimeSeries timeseries = getHistoricalData(uid);
if (timeseries != null) {
return (LocalDateDoubleTimeSeries) timeseries.subSeries(start, inclusiveStart, end, !exclusiveEnd);
} else {
return null;
}
}
}
| Fix null pointer exception errors when requesting the default data provider.
| projects/OG-Engine/src/com/opengamma/engine/historicaldata/EHCachingHistoricalDataProvider.java | Fix null pointer exception errors when requesting the default data provider. |
|
Java | apache-2.0 | e5ae35ab71fca4e1602692f9ac4013d2891ac68a | 0 | spring-projects/spring-security,spring-projects/spring-security,spring-projects/spring-security,spring-projects/spring-security,spring-projects/spring-security,spring-projects/spring-security,spring-projects/spring-security | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.builders;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.SecurityBuilder;
import org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry;
import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AuthorizationManagerWebInvocationPrivilegeEvaluator;
import org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator;
import org.springframework.security.web.access.RequestMatcherDelegatingWebInvocationPrivilegeEvaluator;
import org.springframework.security.web.access.WebInvocationPrivilegeEvaluator;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
import org.springframework.security.web.access.intercept.AuthorizationFilter;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.debug.DebugFilter;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.firewall.RequestRejectedHandler;
import org.springframework.security.web.firewall.StrictHttpFirewall;
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcherEntry;
import org.springframework.util.Assert;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.filter.DelegatingFilterProxy;
/**
* <p>
* The {@link WebSecurity} is created by {@link WebSecurityConfiguration} to create the
* {@link FilterChainProxy} known as the Spring Security Filter Chain
* (springSecurityFilterChain). The springSecurityFilterChain is the {@link Filter} that
* the {@link DelegatingFilterProxy} delegates to.
* </p>
*
* <p>
* Customizations to the {@link WebSecurity} can be made by creating a
* {@link WebSecurityConfigurer}, overriding {@link WebSecurityConfigurerAdapter} or
* exposing a {@link WebSecurityCustomizer} bean.
* </p>
*
* @author Rob Winch
* @author Evgeniy Cheban
* @since 3.2
* @see EnableWebSecurity
* @see WebSecurityConfiguration
*/
public final class WebSecurity extends AbstractConfiguredSecurityBuilder<Filter, WebSecurity>
implements SecurityBuilder<Filter>, ApplicationContextAware, ServletContextAware {
private final Log logger = LogFactory.getLog(getClass());
private final List<RequestMatcher> ignoredRequests = new ArrayList<>();
private final List<SecurityBuilder<? extends SecurityFilterChain>> securityFilterChainBuilders = new ArrayList<>();
private IgnoredRequestConfigurer ignoredRequestRegistry;
private FilterSecurityInterceptor filterSecurityInterceptor;
private HttpFirewall httpFirewall;
private RequestRejectedHandler requestRejectedHandler;
private boolean debugEnabled;
private WebInvocationPrivilegeEvaluator privilegeEvaluator;
private DefaultWebSecurityExpressionHandler defaultWebSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler();
private SecurityExpressionHandler<FilterInvocation> expressionHandler = this.defaultWebSecurityExpressionHandler;
private Runnable postBuildAction = () -> {
};
private ServletContext servletContext;
/**
* Creates a new instance
* @param objectPostProcessor the {@link ObjectPostProcessor} to use
* @see WebSecurityConfiguration
*/
public WebSecurity(ObjectPostProcessor<Object> objectPostProcessor) {
super(objectPostProcessor);
}
/**
* <p>
* Allows adding {@link RequestMatcher} instances that Spring Security should ignore.
* Web Security provided by Spring Security (including the {@link SecurityContext})
* will not be available on {@link HttpServletRequest} that match. Typically the
* requests that are registered should be that of only static resources. For requests
* that are dynamic, consider mapping the request to allow all users instead.
* </p>
*
* Example Usage:
*
* <pre>
* webSecurityBuilder.ignoring()
* // ignore all URLs that start with /resources/ or /static/
* .antMatchers("/resources/**", "/static/**");
* </pre>
*
* Alternatively this will accomplish the same result:
*
* <pre>
* webSecurityBuilder.ignoring()
* // ignore all URLs that start with /resources/ or /static/
* .antMatchers("/resources/**").antMatchers("/static/**");
* </pre>
*
* Multiple invocations of ignoring() are also additive, so the following is also
* equivalent to the previous two examples:
*
* <pre>
* webSecurityBuilder.ignoring()
* // ignore all URLs that start with /resources/
* .antMatchers("/resources/**");
* webSecurityBuilder.ignoring()
* // ignore all URLs that start with /static/
* .antMatchers("/static/**");
* // now both URLs that start with /resources/ and /static/ will be ignored
* </pre>
* @return the {@link IgnoredRequestConfigurer} to use for registering request that
* should be ignored
*/
public IgnoredRequestConfigurer ignoring() {
return this.ignoredRequestRegistry;
}
/**
* Allows customizing the {@link HttpFirewall}. The default is
* {@link StrictHttpFirewall}.
* @param httpFirewall the custom {@link HttpFirewall}
* @return the {@link WebSecurity} for further customizations
*/
public WebSecurity httpFirewall(HttpFirewall httpFirewall) {
this.httpFirewall = httpFirewall;
return this;
}
/**
* Controls debugging support for Spring Security.
* @param debugEnabled if true, enables debug support with Spring Security. Default is
* false.
* @return the {@link WebSecurity} for further customization.
* @see EnableWebSecurity#debug()
*/
public WebSecurity debug(boolean debugEnabled) {
this.debugEnabled = debugEnabled;
return this;
}
/**
* <p>
* Adds builders to create {@link SecurityFilterChain} instances.
* </p>
*
* <p>
* Typically this method is invoked automatically within the framework from
* {@link WebSecurityConfigurerAdapter#init(WebSecurity)}
* </p>
* @param securityFilterChainBuilder the builder to use to create the
* {@link SecurityFilterChain} instances
* @return the {@link WebSecurity} for further customizations
*/
public WebSecurity addSecurityFilterChainBuilder(
SecurityBuilder<? extends SecurityFilterChain> securityFilterChainBuilder) {
this.securityFilterChainBuilders.add(securityFilterChainBuilder);
return this;
}
/**
* Set the {@link WebInvocationPrivilegeEvaluator} to be used. If this is not
* specified, then a {@link DefaultWebInvocationPrivilegeEvaluator} will be created
* when {@link #securityInterceptor(FilterSecurityInterceptor)} is non null.
* @param privilegeEvaluator the {@link WebInvocationPrivilegeEvaluator} to use
* @return the {@link WebSecurity} for further customizations
*/
public WebSecurity privilegeEvaluator(WebInvocationPrivilegeEvaluator privilegeEvaluator) {
this.privilegeEvaluator = privilegeEvaluator;
return this;
}
/**
* Set the {@link SecurityExpressionHandler} to be used. If this is not specified,
* then a {@link DefaultWebSecurityExpressionHandler} will be used.
* @param expressionHandler the {@link SecurityExpressionHandler} to use
* @return the {@link WebSecurity} for further customizations
*/
public WebSecurity expressionHandler(SecurityExpressionHandler<FilterInvocation> expressionHandler) {
Assert.notNull(expressionHandler, "expressionHandler cannot be null");
this.expressionHandler = expressionHandler;
return this;
}
/**
* Gets the {@link SecurityExpressionHandler} to be used.
* @return the {@link SecurityExpressionHandler} for further customizations
*/
public SecurityExpressionHandler<FilterInvocation> getExpressionHandler() {
return this.expressionHandler;
}
/**
* Gets the {@link WebInvocationPrivilegeEvaluator} to be used.
* @return the {@link WebInvocationPrivilegeEvaluator} for further customizations
*/
public WebInvocationPrivilegeEvaluator getPrivilegeEvaluator() {
if (this.privilegeEvaluator != null) {
return this.privilegeEvaluator;
}
return (this.filterSecurityInterceptor != null)
? new DefaultWebInvocationPrivilegeEvaluator(this.filterSecurityInterceptor) : null;
}
/**
* Sets the {@link FilterSecurityInterceptor}. This is typically invoked by
* {@link WebSecurityConfigurerAdapter}.
* @param securityInterceptor the {@link FilterSecurityInterceptor} to use
* @return the {@link WebSecurity} for further customizations
* @deprecated Use {@link #privilegeEvaluator(WebInvocationPrivilegeEvaluator)}
* instead
*/
@Deprecated
public WebSecurity securityInterceptor(FilterSecurityInterceptor securityInterceptor) {
this.filterSecurityInterceptor = securityInterceptor;
return this;
}
/**
* Executes the Runnable immediately after the build takes place
* @param postBuildAction
* @return the {@link WebSecurity} for further customizations
*/
public WebSecurity postBuildAction(Runnable postBuildAction) {
this.postBuildAction = postBuildAction;
return this;
}
/**
* Sets the handler to handle
* {@link org.springframework.security.web.firewall.RequestRejectedException}
* @param requestRejectedHandler
* @return the {@link WebSecurity} for further customizations
* @since 5.7
*/
public WebSecurity requestRejectedHandler(RequestRejectedHandler requestRejectedHandler) {
Assert.notNull(requestRejectedHandler, "requestRejectedHandler cannot be null");
this.requestRejectedHandler = requestRejectedHandler;
return this;
}
@Override
protected Filter performBuild() throws Exception {
Assert.state(!this.securityFilterChainBuilders.isEmpty(),
() -> "At least one SecurityBuilder<? extends SecurityFilterChain> needs to be specified. "
+ "Typically this is done by exposing a SecurityFilterChain bean "
+ "or by adding a @Configuration that extends WebSecurityConfigurerAdapter. "
+ "More advanced users can invoke " + WebSecurity.class.getSimpleName()
+ ".addSecurityFilterChainBuilder directly");
int chainSize = this.ignoredRequests.size() + this.securityFilterChainBuilders.size();
List<SecurityFilterChain> securityFilterChains = new ArrayList<>(chainSize);
List<RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>>> requestMatcherPrivilegeEvaluatorsEntries = new ArrayList<>();
for (RequestMatcher ignoredRequest : this.ignoredRequests) {
WebSecurity.this.logger.warn("You are asking Spring Security to ignore " + ignoredRequest
+ ". This is not recommended -- please use permitAll via HttpSecurity#authorizeHttpRequests instead.");
SecurityFilterChain securityFilterChain = new DefaultSecurityFilterChain(ignoredRequest);
securityFilterChains.add(securityFilterChain);
requestMatcherPrivilegeEvaluatorsEntries
.add(getRequestMatcherPrivilegeEvaluatorsEntry(securityFilterChain));
}
for (SecurityBuilder<? extends SecurityFilterChain> securityFilterChainBuilder : this.securityFilterChainBuilders) {
SecurityFilterChain securityFilterChain = securityFilterChainBuilder.build();
securityFilterChains.add(securityFilterChain);
requestMatcherPrivilegeEvaluatorsEntries
.add(getRequestMatcherPrivilegeEvaluatorsEntry(securityFilterChain));
}
if (this.privilegeEvaluator == null) {
this.privilegeEvaluator = new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator(
requestMatcherPrivilegeEvaluatorsEntries);
}
FilterChainProxy filterChainProxy = new FilterChainProxy(securityFilterChains);
if (this.httpFirewall != null) {
filterChainProxy.setFirewall(this.httpFirewall);
}
if (this.requestRejectedHandler != null) {
filterChainProxy.setRequestRejectedHandler(this.requestRejectedHandler);
}
filterChainProxy.afterPropertiesSet();
Filter result = filterChainProxy;
if (this.debugEnabled) {
this.logger.warn("\n\n" + "********************************************************************\n"
+ "********** Security debugging is enabled. *************\n"
+ "********** This may include sensitive information. *************\n"
+ "********** Do not use in a production system! *************\n"
+ "********************************************************************\n\n");
result = new DebugFilter(filterChainProxy);
}
this.postBuildAction.run();
return result;
}
private RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>> getRequestMatcherPrivilegeEvaluatorsEntry(
SecurityFilterChain securityFilterChain) {
List<WebInvocationPrivilegeEvaluator> privilegeEvaluators = new ArrayList<>();
for (Filter filter : securityFilterChain.getFilters()) {
if (filter instanceof FilterSecurityInterceptor) {
DefaultWebInvocationPrivilegeEvaluator defaultWebInvocationPrivilegeEvaluator = new DefaultWebInvocationPrivilegeEvaluator(
(FilterSecurityInterceptor) filter);
defaultWebInvocationPrivilegeEvaluator.setServletContext(this.servletContext);
privilegeEvaluators.add(defaultWebInvocationPrivilegeEvaluator);
continue;
}
if (filter instanceof AuthorizationFilter) {
AuthorizationManager<HttpServletRequest> authorizationManager = ((AuthorizationFilter) filter)
.getAuthorizationManager();
AuthorizationManagerWebInvocationPrivilegeEvaluator evaluator = new AuthorizationManagerWebInvocationPrivilegeEvaluator(
authorizationManager);
evaluator.setServletContext(this.servletContext);
privilegeEvaluators.add(evaluator);
}
}
return new RequestMatcherEntry<>(securityFilterChain::matches, privilegeEvaluators);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.defaultWebSecurityExpressionHandler.setApplicationContext(applicationContext);
try {
this.defaultWebSecurityExpressionHandler.setRoleHierarchy(applicationContext.getBean(RoleHierarchy.class));
}
catch (NoSuchBeanDefinitionException ex) {
}
try {
this.defaultWebSecurityExpressionHandler
.setPermissionEvaluator(applicationContext.getBean(PermissionEvaluator.class));
}
catch (NoSuchBeanDefinitionException ex) {
}
this.ignoredRequestRegistry = new IgnoredRequestConfigurer(applicationContext);
try {
this.httpFirewall = applicationContext.getBean(HttpFirewall.class);
}
catch (NoSuchBeanDefinitionException ex) {
}
try {
this.requestRejectedHandler = applicationContext.getBean(RequestRejectedHandler.class);
}
catch (NoSuchBeanDefinitionException ex) {
}
}
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
/**
* An {@link IgnoredRequestConfigurer} that allows optionally configuring the
* {@link MvcRequestMatcher#setMethod(HttpMethod)}
*
* @author Rob Winch
*/
public final class MvcMatchersIgnoredRequestConfigurer extends IgnoredRequestConfigurer {
private final List<MvcRequestMatcher> mvcMatchers;
private MvcMatchersIgnoredRequestConfigurer(ApplicationContext context, List<MvcRequestMatcher> mvcMatchers) {
super(context);
this.mvcMatchers = mvcMatchers;
}
public IgnoredRequestConfigurer servletPath(String servletPath) {
for (MvcRequestMatcher matcher : this.mvcMatchers) {
matcher.setServletPath(servletPath);
}
return this;
}
}
/**
* Allows registering {@link RequestMatcher} instances that should be ignored by
* Spring Security.
*
* @author Rob Winch
* @since 3.2
*/
public class IgnoredRequestConfigurer extends AbstractRequestMatcherRegistry<IgnoredRequestConfigurer> {
IgnoredRequestConfigurer(ApplicationContext context) {
setApplicationContext(context);
}
@Override
public MvcMatchersIgnoredRequestConfigurer mvcMatchers(HttpMethod method, String... mvcPatterns) {
List<MvcRequestMatcher> mvcMatchers = createMvcMatchers(method, mvcPatterns);
WebSecurity.this.ignoredRequests.addAll(mvcMatchers);
return new MvcMatchersIgnoredRequestConfigurer(getApplicationContext(), mvcMatchers);
}
@Override
public MvcMatchersIgnoredRequestConfigurer mvcMatchers(String... mvcPatterns) {
return mvcMatchers(null, mvcPatterns);
}
@Override
protected IgnoredRequestConfigurer chainRequestMatchers(List<RequestMatcher> requestMatchers) {
WebSecurity.this.ignoredRequests.addAll(requestMatchers);
return this;
}
/**
* Returns the {@link WebSecurity} to be returned for chaining.
*/
public WebSecurity and() {
return WebSecurity.this;
}
}
}
| config/src/main/java/org/springframework/security/config/annotation/web/builders/WebSecurity.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.builders;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.SecurityBuilder;
import org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry;
import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AuthorizationManagerWebInvocationPrivilegeEvaluator;
import org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator;
import org.springframework.security.web.access.RequestMatcherDelegatingWebInvocationPrivilegeEvaluator;
import org.springframework.security.web.access.WebInvocationPrivilegeEvaluator;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
import org.springframework.security.web.access.intercept.AuthorizationFilter;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.debug.DebugFilter;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.firewall.RequestRejectedHandler;
import org.springframework.security.web.firewall.StrictHttpFirewall;
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcherEntry;
import org.springframework.util.Assert;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.filter.DelegatingFilterProxy;
/**
* <p>
* The {@link WebSecurity} is created by {@link WebSecurityConfiguration} to create the
* {@link FilterChainProxy} known as the Spring Security Filter Chain
* (springSecurityFilterChain). The springSecurityFilterChain is the {@link Filter} that
* the {@link DelegatingFilterProxy} delegates to.
* </p>
*
* <p>
* Customizations to the {@link WebSecurity} can be made by creating a
* {@link WebSecurityConfigurer}, overriding {@link WebSecurityConfigurerAdapter} or
* exposing a {@link WebSecurityCustomizer} bean.
* </p>
*
* @author Rob Winch
* @author Evgeniy Cheban
* @since 3.2
* @see EnableWebSecurity
* @see WebSecurityConfiguration
*/
public final class WebSecurity extends AbstractConfiguredSecurityBuilder<Filter, WebSecurity>
implements SecurityBuilder<Filter>, ApplicationContextAware, ServletContextAware {
private final Log logger = LogFactory.getLog(getClass());
private final List<RequestMatcher> ignoredRequests = new ArrayList<>();
private final List<SecurityBuilder<? extends SecurityFilterChain>> securityFilterChainBuilders = new ArrayList<>();
private IgnoredRequestConfigurer ignoredRequestRegistry;
private FilterSecurityInterceptor filterSecurityInterceptor;
private HttpFirewall httpFirewall;
private RequestRejectedHandler requestRejectedHandler;
private boolean debugEnabled;
private WebInvocationPrivilegeEvaluator privilegeEvaluator;
private DefaultWebSecurityExpressionHandler defaultWebSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler();
private SecurityExpressionHandler<FilterInvocation> expressionHandler = this.defaultWebSecurityExpressionHandler;
private Runnable postBuildAction = () -> {
};
private ServletContext servletContext;
/**
* Creates a new instance
* @param objectPostProcessor the {@link ObjectPostProcessor} to use
* @see WebSecurityConfiguration
*/
public WebSecurity(ObjectPostProcessor<Object> objectPostProcessor) {
super(objectPostProcessor);
}
/**
* <p>
* Allows adding {@link RequestMatcher} instances that Spring Security should ignore.
* Web Security provided by Spring Security (including the {@link SecurityContext})
* will not be available on {@link HttpServletRequest} that match. Typically the
* requests that are registered should be that of only static resources. For requests
* that are dynamic, consider mapping the request to allow all users instead.
* </p>
*
* Example Usage:
*
* <pre>
* webSecurityBuilder.ignoring()
* // ignore all URLs that start with /resources/ or /static/
* .antMatchers("/resources/**", "/static/**");
* </pre>
*
* Alternatively this will accomplish the same result:
*
* <pre>
* webSecurityBuilder.ignoring()
* // ignore all URLs that start with /resources/ or /static/
* .antMatchers("/resources/**").antMatchers("/static/**");
* </pre>
*
* Multiple invocations of ignoring() are also additive, so the following is also
* equivalent to the previous two examples:
*
* <pre>
* webSecurityBuilder.ignoring()
* // ignore all URLs that start with /resources/
* .antMatchers("/resources/**");
* webSecurityBuilder.ignoring()
* // ignore all URLs that start with /static/
* .antMatchers("/static/**");
* // now both URLs that start with /resources/ and /static/ will be ignored
* </pre>
* @return the {@link IgnoredRequestConfigurer} to use for registering request that
* should be ignored
*/
public IgnoredRequestConfigurer ignoring() {
return this.ignoredRequestRegistry;
}
/**
* Allows customizing the {@link HttpFirewall}. The default is
* {@link StrictHttpFirewall}.
* @param httpFirewall the custom {@link HttpFirewall}
* @return the {@link WebSecurity} for further customizations
*/
public WebSecurity httpFirewall(HttpFirewall httpFirewall) {
this.httpFirewall = httpFirewall;
return this;
}
/**
* Controls debugging support for Spring Security.
* @param debugEnabled if true, enables debug support with Spring Security. Default is
* false.
* @return the {@link WebSecurity} for further customization.
* @see EnableWebSecurity#debug()
*/
public WebSecurity debug(boolean debugEnabled) {
this.debugEnabled = debugEnabled;
return this;
}
/**
* <p>
* Adds builders to create {@link SecurityFilterChain} instances.
* </p>
*
* <p>
* Typically this method is invoked automatically within the framework from
* {@link WebSecurityConfigurerAdapter#init(WebSecurity)}
* </p>
* @param securityFilterChainBuilder the builder to use to create the
* {@link SecurityFilterChain} instances
* @return the {@link WebSecurity} for further customizations
*/
public WebSecurity addSecurityFilterChainBuilder(
SecurityBuilder<? extends SecurityFilterChain> securityFilterChainBuilder) {
this.securityFilterChainBuilders.add(securityFilterChainBuilder);
return this;
}
/**
* Set the {@link WebInvocationPrivilegeEvaluator} to be used. If this is not
* specified, then a {@link DefaultWebInvocationPrivilegeEvaluator} will be created
* when {@link #securityInterceptor(FilterSecurityInterceptor)} is non null.
* @param privilegeEvaluator the {@link WebInvocationPrivilegeEvaluator} to use
* @return the {@link WebSecurity} for further customizations
*/
public WebSecurity privilegeEvaluator(WebInvocationPrivilegeEvaluator privilegeEvaluator) {
this.privilegeEvaluator = privilegeEvaluator;
return this;
}
/**
* Set the {@link SecurityExpressionHandler} to be used. If this is not specified,
* then a {@link DefaultWebSecurityExpressionHandler} will be used.
* @param expressionHandler the {@link SecurityExpressionHandler} to use
* @return the {@link WebSecurity} for further customizations
*/
public WebSecurity expressionHandler(SecurityExpressionHandler<FilterInvocation> expressionHandler) {
Assert.notNull(expressionHandler, "expressionHandler cannot be null");
this.expressionHandler = expressionHandler;
return this;
}
/**
* Gets the {@link SecurityExpressionHandler} to be used.
* @return the {@link SecurityExpressionHandler} for further customizations
*/
public SecurityExpressionHandler<FilterInvocation> getExpressionHandler() {
return this.expressionHandler;
}
/**
* Gets the {@link WebInvocationPrivilegeEvaluator} to be used.
* @return the {@link WebInvocationPrivilegeEvaluator} for further customizations
*/
public WebInvocationPrivilegeEvaluator getPrivilegeEvaluator() {
if (this.privilegeEvaluator != null) {
return this.privilegeEvaluator;
}
return (this.filterSecurityInterceptor != null)
? new DefaultWebInvocationPrivilegeEvaluator(this.filterSecurityInterceptor) : null;
}
/**
* Sets the {@link FilterSecurityInterceptor}. This is typically invoked by
* {@link WebSecurityConfigurerAdapter}.
* @param securityInterceptor the {@link FilterSecurityInterceptor} to use
* @return the {@link WebSecurity} for further customizations
* @deprecated Use {@link #privilegeEvaluator(WebInvocationPrivilegeEvaluator)}
* instead
*/
public WebSecurity securityInterceptor(FilterSecurityInterceptor securityInterceptor) {
this.filterSecurityInterceptor = securityInterceptor;
return this;
}
/**
* Executes the Runnable immediately after the build takes place
* @param postBuildAction
* @return the {@link WebSecurity} for further customizations
*/
public WebSecurity postBuildAction(Runnable postBuildAction) {
this.postBuildAction = postBuildAction;
return this;
}
/**
* Sets the handler to handle
* {@link org.springframework.security.web.firewall.RequestRejectedException}
* @param requestRejectedHandler
* @return the {@link WebSecurity} for further customizations
* @since 5.7
*/
public WebSecurity requestRejectedHandler(RequestRejectedHandler requestRejectedHandler) {
Assert.notNull(requestRejectedHandler, "requestRejectedHandler cannot be null");
this.requestRejectedHandler = requestRejectedHandler;
return this;
}
@Override
protected Filter performBuild() throws Exception {
Assert.state(!this.securityFilterChainBuilders.isEmpty(),
() -> "At least one SecurityBuilder<? extends SecurityFilterChain> needs to be specified. "
+ "Typically this is done by exposing a SecurityFilterChain bean "
+ "or by adding a @Configuration that extends WebSecurityConfigurerAdapter. "
+ "More advanced users can invoke " + WebSecurity.class.getSimpleName()
+ ".addSecurityFilterChainBuilder directly");
int chainSize = this.ignoredRequests.size() + this.securityFilterChainBuilders.size();
List<SecurityFilterChain> securityFilterChains = new ArrayList<>(chainSize);
List<RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>>> requestMatcherPrivilegeEvaluatorsEntries = new ArrayList<>();
for (RequestMatcher ignoredRequest : this.ignoredRequests) {
WebSecurity.this.logger.warn("You are asking Spring Security to ignore " + ignoredRequest
+ ". This is not recommended -- please use permitAll via HttpSecurity#authorizeHttpRequests instead.");
SecurityFilterChain securityFilterChain = new DefaultSecurityFilterChain(ignoredRequest);
securityFilterChains.add(securityFilterChain);
requestMatcherPrivilegeEvaluatorsEntries
.add(getRequestMatcherPrivilegeEvaluatorsEntry(securityFilterChain));
}
for (SecurityBuilder<? extends SecurityFilterChain> securityFilterChainBuilder : this.securityFilterChainBuilders) {
SecurityFilterChain securityFilterChain = securityFilterChainBuilder.build();
securityFilterChains.add(securityFilterChain);
requestMatcherPrivilegeEvaluatorsEntries
.add(getRequestMatcherPrivilegeEvaluatorsEntry(securityFilterChain));
}
if (this.privilegeEvaluator == null) {
this.privilegeEvaluator = new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator(
requestMatcherPrivilegeEvaluatorsEntries);
}
FilterChainProxy filterChainProxy = new FilterChainProxy(securityFilterChains);
if (this.httpFirewall != null) {
filterChainProxy.setFirewall(this.httpFirewall);
}
if (this.requestRejectedHandler != null) {
filterChainProxy.setRequestRejectedHandler(this.requestRejectedHandler);
}
filterChainProxy.afterPropertiesSet();
Filter result = filterChainProxy;
if (this.debugEnabled) {
this.logger.warn("\n\n" + "********************************************************************\n"
+ "********** Security debugging is enabled. *************\n"
+ "********** This may include sensitive information. *************\n"
+ "********** Do not use in a production system! *************\n"
+ "********************************************************************\n\n");
result = new DebugFilter(filterChainProxy);
}
this.postBuildAction.run();
return result;
}
private RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>> getRequestMatcherPrivilegeEvaluatorsEntry(
SecurityFilterChain securityFilterChain) {
List<WebInvocationPrivilegeEvaluator> privilegeEvaluators = new ArrayList<>();
for (Filter filter : securityFilterChain.getFilters()) {
if (filter instanceof FilterSecurityInterceptor) {
DefaultWebInvocationPrivilegeEvaluator defaultWebInvocationPrivilegeEvaluator = new DefaultWebInvocationPrivilegeEvaluator(
(FilterSecurityInterceptor) filter);
defaultWebInvocationPrivilegeEvaluator.setServletContext(this.servletContext);
privilegeEvaluators.add(defaultWebInvocationPrivilegeEvaluator);
continue;
}
if (filter instanceof AuthorizationFilter) {
AuthorizationManager<HttpServletRequest> authorizationManager = ((AuthorizationFilter) filter)
.getAuthorizationManager();
AuthorizationManagerWebInvocationPrivilegeEvaluator evaluator = new AuthorizationManagerWebInvocationPrivilegeEvaluator(
authorizationManager);
evaluator.setServletContext(this.servletContext);
privilegeEvaluators.add(evaluator);
}
}
return new RequestMatcherEntry<>(securityFilterChain::matches, privilegeEvaluators);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.defaultWebSecurityExpressionHandler.setApplicationContext(applicationContext);
try {
this.defaultWebSecurityExpressionHandler.setRoleHierarchy(applicationContext.getBean(RoleHierarchy.class));
}
catch (NoSuchBeanDefinitionException ex) {
}
try {
this.defaultWebSecurityExpressionHandler
.setPermissionEvaluator(applicationContext.getBean(PermissionEvaluator.class));
}
catch (NoSuchBeanDefinitionException ex) {
}
this.ignoredRequestRegistry = new IgnoredRequestConfigurer(applicationContext);
try {
this.httpFirewall = applicationContext.getBean(HttpFirewall.class);
}
catch (NoSuchBeanDefinitionException ex) {
}
try {
this.requestRejectedHandler = applicationContext.getBean(RequestRejectedHandler.class);
}
catch (NoSuchBeanDefinitionException ex) {
}
}
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
/**
* An {@link IgnoredRequestConfigurer} that allows optionally configuring the
* {@link MvcRequestMatcher#setMethod(HttpMethod)}
*
* @author Rob Winch
*/
public final class MvcMatchersIgnoredRequestConfigurer extends IgnoredRequestConfigurer {
private final List<MvcRequestMatcher> mvcMatchers;
private MvcMatchersIgnoredRequestConfigurer(ApplicationContext context, List<MvcRequestMatcher> mvcMatchers) {
super(context);
this.mvcMatchers = mvcMatchers;
}
public IgnoredRequestConfigurer servletPath(String servletPath) {
for (MvcRequestMatcher matcher : this.mvcMatchers) {
matcher.setServletPath(servletPath);
}
return this;
}
}
/**
* Allows registering {@link RequestMatcher} instances that should be ignored by
* Spring Security.
*
* @author Rob Winch
* @since 3.2
*/
public class IgnoredRequestConfigurer extends AbstractRequestMatcherRegistry<IgnoredRequestConfigurer> {
IgnoredRequestConfigurer(ApplicationContext context) {
setApplicationContext(context);
}
@Override
public MvcMatchersIgnoredRequestConfigurer mvcMatchers(HttpMethod method, String... mvcPatterns) {
List<MvcRequestMatcher> mvcMatchers = createMvcMatchers(method, mvcPatterns);
WebSecurity.this.ignoredRequests.addAll(mvcMatchers);
return new MvcMatchersIgnoredRequestConfigurer(getApplicationContext(), mvcMatchers);
}
@Override
public MvcMatchersIgnoredRequestConfigurer mvcMatchers(String... mvcPatterns) {
return mvcMatchers(null, mvcPatterns);
}
@Override
protected IgnoredRequestConfigurer chainRequestMatchers(List<RequestMatcher> requestMatchers) {
WebSecurity.this.ignoredRequests.addAll(requestMatchers);
return this;
}
/**
* Returns the {@link WebSecurity} to be returned for chaining.
*/
public WebSecurity and() {
return WebSecurity.this;
}
}
}
| Add Deprecated annotation to WebSecurity#securityInterceptor
Closes gh-11634
| config/src/main/java/org/springframework/security/config/annotation/web/builders/WebSecurity.java | Add Deprecated annotation to WebSecurity#securityInterceptor |
|
Java | apache-2.0 | 32b21def343bb50f487cb894535145574ca34d7d | 0 | crate/crate,crate/crate,EvilMcJerkface/crate,crate/crate,EvilMcJerkface/crate,EvilMcJerkface/crate | /*
* Licensed to Crate under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership. Crate 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.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial
* agreement.
*/
package io.crate.execution.jobs;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
public abstract class AbstractTask implements Task {
protected final int id;
private final AtomicBoolean firstClose = new AtomicBoolean(false);
private final CompletionState completionState = new CompletionState();
private final CompletableFuture<CompletionState> future = new CompletableFuture<>();
protected AbstractTask(int id) {
this.id = id;
}
public int id() {
return id;
}
protected void innerStart() {
}
protected void innerPrepare() throws Exception {
}
@Override
public final void prepare() throws Exception {
try {
innerPrepare();
} catch (Exception e) {
close(e);
throw e;
}
}
@Override
public final void start() {
if (!firstClose.get()) {
try {
innerStart();
} catch (Throwable t) {
close(t);
}
}
}
protected void innerClose(@Nullable Throwable t) {
}
protected void close(@Nullable Throwable t) {
if (firstClose.compareAndSet(false, true)) {
try {
innerClose(t);
} catch (Throwable t2) {
if (t == null) {
t = t2;
}
}
completeFuture(t);
}
}
private void completeFuture(@Nullable Throwable t) {
if (t == null) {
future.complete(completionState);
} else {
future.completeExceptionally(t);
}
}
protected void innerKill(@Nonnull Throwable t) {
}
@Override
public final void kill(@Nonnull Throwable t) {
if (firstClose.compareAndSet(false, true)) {
try {
innerKill(t);
} finally {
future.completeExceptionally(t);
}
}
}
@Override
public CompletableFuture<CompletionState> completionFuture() {
return future;
}
protected void setBytesUsed(long bytesUsed) {
completionState.bytesUsed(bytesUsed);
}
protected synchronized boolean isClosed() {
return firstClose.get() || future.isDone();
}
}
| sql/src/main/java/io/crate/execution/jobs/AbstractTask.java | /*
* Licensed to Crate under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership. Crate 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.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial
* agreement.
*/
package io.crate.execution.jobs;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
public abstract class AbstractTask implements Task {
protected final int id;
private final AtomicBoolean firstClose = new AtomicBoolean(false);
private final CompletionState completionState = new CompletionState();
private final CompletableFuture<CompletionState> future = new CompletableFuture<>();
protected AbstractTask(int id) {
this.id = id;
}
public int id() {
return id;
}
protected void innerStart() {
}
protected void innerPrepare() throws Exception {
}
@Override
public final void prepare() throws Exception {
try {
innerPrepare();
} catch (Exception e) {
close(e);
throw e;
}
}
@Override
public final void start() {
if (!firstClose.get()) {
try {
innerStart();
} catch (Throwable t) {
close(t);
}
}
}
protected void innerClose(@Nullable Throwable t) {
}
protected boolean close(@Nullable Throwable t) {
if (firstClose.compareAndSet(false, true)) {
try {
innerClose(t);
} catch (Throwable t2) {
if (t == null) {
t = t2;
}
}
completeFuture(t);
return true;
}
return false;
}
private void completeFuture(@Nullable Throwable t) {
if (t == null) {
future.complete(completionState);
} else {
future.completeExceptionally(t);
}
}
protected void innerKill(@Nonnull Throwable t) {
}
@Override
public final void kill(@Nonnull Throwable t) {
if (firstClose.compareAndSet(false, true)) {
try {
innerKill(t);
} finally {
future.completeExceptionally(t);
}
}
}
@Override
public CompletableFuture<CompletionState> completionFuture() {
return future;
}
protected void setBytesUsed(long bytesUsed) {
completionState.bytesUsed(bytesUsed);
}
protected synchronized boolean isClosed() {
return firstClose.get() || future.isDone();
}
}
| Remove unused return value from AbstractTask.close
| sql/src/main/java/io/crate/execution/jobs/AbstractTask.java | Remove unused return value from AbstractTask.close |
|
Java | apache-2.0 | 3f8d8e8ace88246316413ecfbae3e68465d9e967 | 0 | aschaetzle/Sempala | package de.uni_freiburg.informatik.dbis.sempala.translator.spark;
import java.util.Properties;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.sql.DataFrame;
import org.apache.spark.sql.hive.HiveContext;
import de.uni_freiburg.informatik.dbis.sempala.translator.Tags;
/**
* Wrapper of Spark connection. This class contains the initialization of needed
* Spark objects. It wraps the functionality for execution of Spark SQL queries.
*
* @author Polina Koleva
*
*/
public class Spark {
private SparkConf sparkConfiguration;
private JavaSparkContext javaContext;
private HiveContext hiveContext;
private int dfPartitions;
/**
* Initializes a Spark connection. Use it afterwards for execution of Spark
* SQL queries.
*
* @param appName the name of the app that will be used with this Spark
* connection
* @param database name of the database that will be used with this Spark
* connection
* @param master the master URI
*/
public Spark(String appName, String database) {
// TODO check what will happen if there is already in use the same app
// name
this.sparkConfiguration = new SparkConf().setAppName(appName).set("spark.io.compression.codec", "snappy");
this.javaContext = new JavaSparkContext(sparkConfiguration);
this.hiveContext = new HiveContext(javaContext);
// use the created database
this.hiveContext.sql((String.format("USE %s", database)));
configureSparkContext();
cacheTable();
}
/**
* Add specific configuration for Spark SQL execution.
*/
public void configureSparkContext(){
Properties properties = new Properties();
properties.setProperty("spark.sql.parquet.filterPushdown", "true");
properties.setProperty("spark.sql.inMemoryColumnarStorage.batchSize", "20000");
if(dfPartitions != 0){
properties.setProperty("spark.sql.shuffle.partitions", Integer.toString(dfPartitions));
}
hiveContext.setConf(properties);
}
/**
* Cache complex_property_table.
*/
public void cacheTable() {
DataFrame result = hiveContext.sql(String.format("SELECT * FROM %s",
Tags.COMPLEX_PROPERTYTABLE_TABLENAME));
// add partitioning if enables
if (dfPartitions != 0) {
result.repartition(dfPartitions);
}
result.registerTempTable(Tags.CACHED_COMPLEX_PROPERTYTABLE_TABLENAME);
hiveContext.cacheTable(Tags.CACHED_COMPLEX_PROPERTYTABLE_TABLENAME);
// force caching
result.count();
}
public void unpersistCachedTables(){
hiveContext.uncacheTable(Tags.CACHED_COMPLEX_PROPERTYTABLE_TABLENAME);
}
/**
* Get Hive context.
*
* @return {@link HiveContext}
*/
public HiveContext getHiveContext() {
return hiveContext;
}
/**
* Execute a query and return its result.
*/
public DataFrame sql(String sqlQuqery) {
return this.hiveContext.sql(sqlQuqery);
}
public int getDfPartitions() {
return dfPartitions;
}
public void setDfPartitions(int dfPartitions) {
this.dfPartitions = dfPartitions;
}
}
| sempala-translator/src/main/java/de/uni_freiburg/informatik/dbis/sempala/translator/spark/Spark.java | package de.uni_freiburg.informatik.dbis.sempala.translator.spark;
import java.util.Properties;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.sql.DataFrame;
import org.apache.spark.sql.hive.HiveContext;
import de.uni_freiburg.informatik.dbis.sempala.translator.Tags;
/**
* Wrapper of Spark connection. This class contains the initialization of needed
* Spark objects. It wraps the functionality for execution of Spark SQL queries.
*
* @author Polina Koleva
*
*/
public class Spark {
private SparkConf sparkConfiguration;
private JavaSparkContext javaContext;
private HiveContext hiveContext;
private int dfPartitions;
/**
* Initializes a Spark connection. Use it afterwards for execution of Spark
* SQL queries.
*
* @param appName the name of the app that will be used with this Spark
* connection
* @param database name of the database that will be used with this Spark
* connection
* @param master the master URI
*/
public Spark(String appName, String database) {
// TODO check what will happen if there is already in use the same app
// name
this.sparkConfiguration = new SparkConf().setAppName(appName).set("spark.io.compression.codec", "snappy");
this.javaContext = new JavaSparkContext(sparkConfiguration);
this.hiveContext = new HiveContext(javaContext);
// use the created database
this.hiveContext.sql((String.format("USE %s", database)));
configureSparkContext();
cacheTable();
}
/**
* Add specific configuration for Spark SQL execution.
*/
public void configureSparkContext(){
Properties properties = new Properties();
properties.setProperty("spark.sql.parquet.filterPushdown", "true");
properties.setProperty("spark.sql.inMemoryColumnarStorage.batchSize", "20000");
properties.setProperty("spark.sql.shuffle.partitions", "100");
hiveContext.setConf(properties);
}
/**
* Cache complex_property_table.
*/
public void cacheTable() {
DataFrame result = hiveContext.sql(String.format("SELECT * FROM %s",
Tags.COMPLEX_PROPERTYTABLE_TABLENAME));
// add partitioning if enables
if (dfPartitions != 0) {
result.repartition(dfPartitions);
}
result.registerTempTable(Tags.CACHED_COMPLEX_PROPERTYTABLE_TABLENAME);
hiveContext.cacheTable(Tags.CACHED_COMPLEX_PROPERTYTABLE_TABLENAME);
// force caching
result.count();
}
public void unpersistCachedTables(){
hiveContext.uncacheTable(Tags.CACHED_COMPLEX_PROPERTYTABLE_TABLENAME);
}
/**
* Get Hive context.
*
* @return {@link HiveContext}
*/
public HiveContext getHiveContext() {
return hiveContext;
}
/**
* Execute a query and return its result.
*/
public DataFrame sql(String sqlQuqery) {
return this.hiveContext.sql(sqlQuqery);
}
public int getDfPartitions() {
return dfPartitions;
}
public void setDfPartitions(int dfPartitions) {
this.dfPartitions = dfPartitions;
}
}
| Add shuffle partitions.
| sempala-translator/src/main/java/de/uni_freiburg/informatik/dbis/sempala/translator/spark/Spark.java | Add shuffle partitions. |
|
Java | apache-2.0 | 3398b44be6759f275fe4b552c25fec6faa0fe1a6 | 0 | codehaus-plexus/plexus-utils,codehaus-plexus/plexus-utils,codehaus-plexus/plexus-utils | package org.codehaus.plexus.util.cli.shell;
/*
* Copyright 2001-2006 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.
*/
import org.codehaus.plexus.util.cli.CommandLineException;
import org.codehaus.plexus.util.cli.Commandline;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* <p>
* Class that abstracts the Shell functionality,
* with subclases for shells that behave particularly, like
* <ul>
* <li><code>command.com</code></li>
* <li><code>cmd.exe</code></li>
* </ul>
* </p>
*
* @author <a href="mailto:[email protected]">Carlos Sanchez</a>
* @since 1.2
*/
public class Shell
{
private String shellCommand;
private List shellArgs = new ArrayList();
private boolean quotedArgumentsEnabled = true;
/**
* Set the command to execute the shell (eg. COMMAND.COM, /bin/bash,...)
*
* @param shellCommand
*/
public void setShellCommand( String shellCommand )
{
this.shellCommand = shellCommand;
}
/**
* Get the command to execute the shell
*
* @return
*/
public String getShellCommand()
{
return shellCommand;
}
/**
* Set the shell arguments when calling a command line (not the executable arguments)
* (eg. /X /C for CMD.EXE)
*
* @param shellArgs
*/
public void setShellArgs( String[] shellArgs )
{
this.shellArgs.clear();
this.shellArgs.addAll( Arrays.asList( shellArgs ) );
}
/**
* Get the shell arguments
*
* @return
*/
public String[] getShellArgs()
{
if ( shellArgs == null || shellArgs.isEmpty() )
{
return null;
}
else
{
return (String[]) shellArgs.toArray( new String[shellArgs.size()] );
}
}
/**
* Get the command line for the provided executable and arguments in this shell
*
* @param executable executable that the shell has to call
* @param arguments arguments for the executable, not the shell
* @return List with one String object with executable and arguments quoted as needed
*/
public List getCommandLine( String executable, String[] arguments )
{
List commandLine = new ArrayList();
try
{
StringBuffer sb = new StringBuffer();
if ( executable != null )
{
if ( quotedArgumentsEnabled )
{
sb.append( Commandline.quoteArgument( executable ) );
}
else
{
sb.append( executable );
}
}
for ( int i = 0; i < arguments.length; i++ )
{
sb.append( " " );
if ( quotedArgumentsEnabled )
{
sb.append( Commandline.quoteArgument( arguments[i] ) );
}
else
{
sb.append( arguments[i] );
}
}
commandLine.add( sb.toString() );
}
catch ( CommandLineException e )
{
throw new RuntimeException( e );
}
return commandLine;
}
/**
* Get the full command line to execute, including shell command, shell arguments,
* executable and executable arguments
*
* @param executable executable that the shell has to call
* @param arguments arguments for the executable, not the shell
* @return List of String objects, whose array version is suitable to be used as argument
* of Runtime.getRuntime().exec()
*/
public List getShellCommandLine( String executable, String[] arguments )
{
List commandLine = new ArrayList();
if ( getShellCommand() != null )
{
commandLine.add( getShellCommand() );
}
if ( getShellArgs() != null )
{
commandLine.addAll( getShellArgsList() );
}
commandLine.addAll( getCommandLine( executable, arguments ) );
return commandLine;
}
public List getShellArgsList()
{
return shellArgs;
}
public void addShellArg( String arg )
{
this.shellArgs.add( arg );
}
public void setQuotedArgumentsEnabled( boolean quotedArgumentsEnabled )
{
this.quotedArgumentsEnabled = quotedArgumentsEnabled;
}
public boolean isQuotedArgumentsEnabled()
{
return quotedArgumentsEnabled;
}
}
| src/main/java/org/codehaus/plexus/util/cli/shell/Shell.java | package org.codehaus.plexus.util.cli.shell;
/*
* Copyright 2001-2006 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.
*/
import org.codehaus.plexus.util.cli.CommandLineException;
import org.codehaus.plexus.util.cli.Commandline;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* <p>
* Class that abstracts the Shell functionality,
* with subclases for shells that behave particularly, like
* <ul>
* <li><code>command.com</code></li>
* <li><code>cmd.exe</code></li>
* </ul>
* </p>
*
* @author <a href="mailto:[email protected]">Carlos Sanchez</a>
* @since 1.2
*/
public class Shell
{
private String shellCommand;
private List shellArgs = new ArrayList();
/**
* Set the command to execute the shell (eg. COMMAND.COM, /bin/bash,...)
*
* @param shellCommand
*/
public void setShellCommand( String shellCommand )
{
this.shellCommand = shellCommand;
}
/**
* Get the command to execute the shell
*
* @return
*/
public String getShellCommand()
{
return shellCommand;
}
/**
* Set the shell arguments when calling a command line (not the executable arguments)
* (eg. /X /C for CMD.EXE)
*
* @param shellArgs
*/
public void setShellArgs( String[] shellArgs )
{
this.shellArgs.clear();
this.shellArgs.addAll( Arrays.asList( shellArgs ) );
}
/**
* Get the shell arguments
*
* @return
*/
public String[] getShellArgs()
{
if ( shellArgs == null || shellArgs.isEmpty() )
{
return null;
}
else
{
return (String[]) shellArgs.toArray( new String[shellArgs.size()] );
}
}
/**
* Get the command line for the provided executable and arguments in this shell
*
* @param executable executable that the shell has to call
* @param arguments arguments for the executable, not the shell
* @return List with one String object with executable and arguments quoted as needed
*/
public List getCommandLine( String executable, String[] arguments )
{
List commandLine = new ArrayList();
try
{
StringBuffer sb = new StringBuffer();
if ( executable != null )
{
sb.append( Commandline.quoteArgument( executable ) );
}
for ( int i = 0; i < arguments.length; i++ )
{
sb.append( " " );
sb.append( Commandline.quoteArgument( arguments[i] ) );
}
commandLine.add( sb.toString() );
}
catch ( CommandLineException e )
{
throw new RuntimeException( e );
}
return commandLine;
}
/**
* Get the full command line to execute, including shell command, shell arguments,
* executable and executable arguments
*
* @param executable executable that the shell has to call
* @param arguments arguments for the executable, not the shell
* @return List of String objects, whose array version is suitable to be used as argument
* of Runtime.getRuntime().exec()
*/
public List getShellCommandLine( String executable, String[] arguments )
{
List commandLine = new ArrayList();
if ( getShellCommand() != null )
{
commandLine.add( getShellCommand() );
}
if ( getShellArgs() != null )
{
commandLine.addAll( getShellArgsList() );
}
commandLine.addAll( getCommandLine( executable, arguments ) );
return commandLine;
}
public List getShellArgsList()
{
return shellArgs;
}
public void addShellArg( String arg )
{
this.shellArgs.add( arg );
}
}
| Adding ability to disable argument-quoting in shells.
| src/main/java/org/codehaus/plexus/util/cli/shell/Shell.java | Adding ability to disable argument-quoting in shells. |
|
Java | apache-2.0 | a3e5fb5d0b2aa732d616da64a643037f16363807 | 0 | ledoyen/spring-automocker | package com.github.ledoyen.automocker.extension.sql;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import com.google.common.base.Joiner;
public class DatasourceLocator implements InitializingBean {
@Autowired
private Map<String, DataSource> datasourcesByName;
public DataSource getDataSource() {
if (datasourcesByName.size() == 1) {
return datasourcesByName.values()
.iterator()
.next();
} else {
throw new IllegalArgumentException("Multiple datasources available: " + Joiner.on(", ")
.join(datasourcesByName.keySet()));
}
}
public DataSource getDataSource(String dsName) {
if (!datasourcesByName.containsKey(dsName)) {
throw new IllegalArgumentException(
"No datasource names [" + dsName + "] (availables: " + Joiner.on(", ")
.join(datasourcesByName.keySet()) + ")");
}
return datasourcesByName.get(dsName);
}
public String getName() {
if (datasourcesByName.size() == 1) {
return datasourcesByName.keySet()
.iterator()
.next();
} else {
throw new IllegalArgumentException("Multiple datasources available: " + Joiner.on(", ")
.join(datasourcesByName.keySet()));
}
}
@Override
public void afterPropertiesSet() throws Exception {
if (datasourcesByName.size() == 1) {
}
}
}
| spring-automocker/src/main/java/com/github/ledoyen/automocker/extension/sql/DatasourceLocator.java | package com.github.ledoyen.automocker.extension.sql;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import com.google.common.base.Joiner;
public class DatasourceLocator implements InitializingBean {
@Autowired
private Map<String, DataSource> datasourcesByName;
public DataSource getDataSource() {
if (datasourcesByName.size() == 1) {
return datasourcesByName.values()
.iterator()
.next();
} else {
throw new IllegalArgumentException("Multiple datasources available: " + Joiner.on(", ")
.join(datasourcesByName.keySet()));
}
}
@Override
public void afterPropertiesSet() throws Exception {
if (datasourcesByName.size() == 1) {
}
}
}
| add Datasource locator utilities | spring-automocker/src/main/java/com/github/ledoyen/automocker/extension/sql/DatasourceLocator.java | add Datasource locator utilities |
|
Java | apache-2.0 | 226403ecd7e63ed0b9f81c68288ca1a7c8a1c935 | 0 | dinithis/stratos,gayangunarathne/stratos,asankasanjaya/stratos,gayangunarathne/stratos,agentmilindu/stratos,dinithis/stratos,dinithis/stratos,pkdevbox/stratos,lasinducharith/stratos,Thanu/stratos,Thanu/stratos,dinithis/stratos,gayangunarathne/stratos,pubudu538/stratos,apache/stratos,Thanu/stratos,asankasanjaya/stratos,lasinducharith/stratos,Thanu/stratos,pkdevbox/stratos,pkdevbox/stratos,pubudu538/stratos,pubudu538/stratos,ravihansa3000/stratos,lasinducharith/stratos,pkdevbox/stratos,pubudu538/stratos,anuruddhal/stratos,lasinducharith/stratos,gayangunarathne/stratos,anuruddhal/stratos,agentmilindu/stratos,asankasanjaya/stratos,asankasanjaya/stratos,Thanu/stratos,ravihansa3000/stratos,ravihansa3000/stratos,Thanu/stratos,apache/stratos,hsbhathiya/stratos,dinithis/stratos,ravihansa3000/stratos,apache/stratos,anuruddhal/stratos,dinithis/stratos,gayangunarathne/stratos,ravihansa3000/stratos,anuruddhal/stratos,hsbhathiya/stratos,gayangunarathne/stratos,hsbhathiya/stratos,asankasanjaya/stratos,pubudu538/stratos,dinithis/stratos,agentmilindu/stratos,agentmilindu/stratos,pubudu538/stratos,hsbhathiya/stratos,agentmilindu/stratos,hsbhathiya/stratos,anuruddhal/stratos,anuruddhal/stratos,lasinducharith/stratos,pkdevbox/stratos,pkdevbox/stratos,agentmilindu/stratos,ravihansa3000/stratos,apache/stratos,apache/stratos,apache/stratos,asankasanjaya/stratos,Thanu/stratos,hsbhathiya/stratos,asankasanjaya/stratos,pubudu538/stratos,pkdevbox/stratos,lasinducharith/stratos,agentmilindu/stratos,anuruddhal/stratos,gayangunarathne/stratos,ravihansa3000/stratos,apache/stratos,hsbhathiya/stratos,lasinducharith/stratos | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.stratos.autoscaler.deployment.policy;
import org.apache.stratos.autoscaler.partition.PartitionGroup;
import org.apache.stratos.cloud.controller.stub.deployment.partition.Partition;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
/**
* The model class for Deployment-Policy definition.
*/
public class DeploymentPolicy implements Serializable{
private static final long serialVersionUID = 5675507196284400099L;
private String id;
private String description;
private boolean isPublic;
private PartitionGroup[] partitionGroups;
private int tenantId;
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the description property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDescription(String value) {
this.description = value;
}
/**
* Gets the value of the isPublic property.
*
* @return
* possible object is boolean
*
*/
public boolean getIsPublic() {
return isPublic;
}
/**
* Sets the value of the isPublic property.
*
* @param isPublic
* allowed object is boolean
*
*/
public void setIsPublic(boolean isPublic) {
this.isPublic = isPublic;
}
/**
* Gets the value of the tenantId property.
*
*
*/
public int getTenantId() {
return tenantId;
}
/**
* Sets the value of the tenantId property.
*
*
*/
public void setTenantId(int tenantId) {
this.tenantId = tenantId;
}
public void setPartitionGroups(PartitionGroup[] partitionGroups) {
if(partitionGroups == null) {
this.partitionGroups = new PartitionGroup[0];
} else {
this.partitionGroups = Arrays.copyOf(partitionGroups, partitionGroups.length);
}
}
public Partition[] getAllPartitions() {
ArrayList<Partition> partitionsList = new ArrayList<Partition>();
for (PartitionGroup partitionGroup : this.getPartitionGroups()) {
Partition[] partitions = partitionGroup.getPartitions();
if(partitions != null) {
partitionsList.addAll(Arrays.asList(partitions));
}
}
return partitionsList.toArray(new Partition[partitionsList.size()]);
}
public Partition getPartitionById(String id){
for(Partition p : this.getAllPartitions()){
if(p.getId().equalsIgnoreCase(id))
return p;
}
return null;
}
/**
* Gets the value of the partition-groups.
*/
public PartitionGroup[] getPartitionGroups() {
return this.partitionGroups;
}
public PartitionGroup getPartitionGroup(String partitionGrpId){
for(PartitionGroup parGrp : this.getPartitionGroups()){
if(parGrp.getId().equals(partitionGrpId))
return parGrp;
}
return null;
}
public String toString() {
return "Deployment Policy [id]" + this.id + " Description " + this.description
+ " isPublic " + this.isPublic
+" [partitions] " + Arrays.toString(this.getAllPartitions());
}
}
| components/org.apache.stratos.autoscaler/src/main/java/org/apache/stratos/autoscaler/deployment/policy/DeploymentPolicy.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.stratos.autoscaler.deployment.policy;
import org.apache.stratos.autoscaler.partition.PartitionGroup;
import org.apache.stratos.cloud.controller.stub.deployment.partition.Partition;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
/**
* The model class for Deployment-Policy definition.
*/
public class DeploymentPolicy implements Serializable{
private static final long serialVersionUID = 5675507196284400099L;
private String id;
private String description;
private boolean isPublic;
private PartitionGroup[] partitionGroups;
private int tenantId;
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the description property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDescription(String value) {
this.description = value;
}
/**
* Gets the value of the isPublic property.
*
* @return
* possible object is boolean
*
*/
public boolean getIsPublic() {
return isPublic;
}
/**
* Sets the value of the isPublic property.
*
* @param isPublic
* allowed object is boolean
*
*/
public void setIsPublic(boolean isPublic) {
this.isPublic = isPublic;
}
/**
* Gets the value of the tenantId property.
*
*
*/
public int getTenantId() {
return tenantId;
}
/**
* Sets the value of the tenantId property.
*
*
*/
public void setTenantId(int tenantId) {
this.tenantId = tenantId;
}
public void setPartitionGroups(PartitionGroup[] partitionGroups) {
if(partitionGroups == null) {
this.partitionGroups = new PartitionGroup[0];
} else {
this.partitionGroups = Arrays.copyOf(partitionGroups, partitionGroups.length);
}
}
public Partition[] getAllPartitions() {
ArrayList<Partition> partitionslist = new ArrayList<Partition>();
for (PartitionGroup partitionGroup : this.getPartitionGroups()) {
Partition[] partitions = partitionGroup.getPartitions();
if(partitions != null) {
partitionslist.addAll(Arrays.asList(partitions));
}
}
return partitionslist.toArray(new Partition[0]);
}
public Partition getPartitionById(String id){
for(Partition p : this.getAllPartitions()){
if(p.getId().equalsIgnoreCase(id))
return p;
}
return null;
}
/**
* Gets the value of the partition-groups.
*/
public PartitionGroup[] getPartitionGroups() {
return this.partitionGroups;
}
public PartitionGroup getPartitionGroup(String partitionGrpId){
for(PartitionGroup parGrp : this.getPartitionGroups()){
if(parGrp.getId().equals(partitionGrpId))
return parGrp;
}
return null;
}
public String toString() {
return "Deployment Policy [id]" + this.id + " Description " + this.description
+ " isPublic " + this.isPublic
+" [partitions] " + Arrays.toString(this.getAllPartitions());
}
}
| Fxing a typo
| components/org.apache.stratos.autoscaler/src/main/java/org/apache/stratos/autoscaler/deployment/policy/DeploymentPolicy.java | Fxing a typo |
|
Java | apache-2.0 | 2c2705aa6b06982e246f0660f31c8fc106b7301e | 0 | amzn/exoplayer-amazon-port,androidx/media,google/ExoPlayer,amzn/exoplayer-amazon-port,google/ExoPlayer,google/ExoPlayer,androidx/media,amzn/exoplayer-amazon-port,androidx/media | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.transformer;
import static com.google.android.exoplayer2.DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS;
import static com.google.android.exoplayer2.DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_MS;
import static com.google.android.exoplayer2.DefaultLoadControl.DEFAULT_MAX_BUFFER_MS;
import static com.google.android.exoplayer2.DefaultLoadControl.DEFAULT_MIN_BUFFER_MS;
import static com.google.android.exoplayer2.util.Assertions.checkNotNull;
import static com.google.android.exoplayer2.util.Assertions.checkState;
import static com.google.android.exoplayer2.util.Assertions.checkStateNotNull;
import static java.lang.Math.min;
import android.content.Context;
import android.media.MediaFormat;
import android.media.MediaMuxer;
import android.os.Handler;
import android.os.Looper;
import android.os.ParcelFileDescriptor;
import androidx.annotation.IntDef;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.VisibleForTesting;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.PlaybackException;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.Renderer;
import com.google.android.exoplayer2.RenderersFactory;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.TracksInfo;
import com.google.android.exoplayer2.audio.AudioRendererEventListener;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.extractor.mp4.Mp4Extractor;
import com.google.android.exoplayer2.metadata.MetadataOutput;
import com.google.android.exoplayer2.source.DefaultMediaSourceFactory;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.MediaSourceFactory;
import com.google.android.exoplayer2.text.TextOutput;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.util.Clock;
import com.google.android.exoplayer2.util.Log;
import com.google.android.exoplayer2.util.MimeTypes;
import com.google.android.exoplayer2.util.Util;
import com.google.android.exoplayer2.video.VideoRendererEventListener;
import java.io.IOException;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
/**
* A transcoding transformer to transform media inputs.
*
* <p>Temporary copy of the {@link Transformer} class, which transforms by transcoding rather than
* by muxing. This class is intended to replace the Transformer class.
*
* <p>TODO(http://b/202131097): Replace the Transformer class with TranscodingTransformer, and
* rename this class to Transformer.
*
* <p>The same TranscodingTransformer instance can be used to transform multiple inputs
* (sequentially, not concurrently).
*
* <p>TranscodingTransformer instances must be accessed from a single application thread. For the
* vast majority of cases this should be the application's main thread. The thread on which a
* TranscodingTransformer instance must be accessed can be explicitly specified by passing a {@link
* Looper} when creating the transcoding transformer. If no Looper is specified, then the Looper of
* the thread that the {@link TranscodingTransformer.Builder} is created on is used, or if that
* thread does not have a Looper, the Looper of the application's main thread is used. In all cases
* the Looper of the thread from which the transcoding transformer must be accessed can be queried
* using {@link #getApplicationLooper()}.
*/
@RequiresApi(18)
public final class TranscodingTransformer {
/** A builder for {@link TranscodingTransformer} instances. */
public static final class Builder {
// Mandatory field.
private @MonotonicNonNull Context context;
// Optional fields.
private @MonotonicNonNull MediaSourceFactory mediaSourceFactory;
private Muxer.Factory muxerFactory;
private boolean removeAudio;
private boolean removeVideo;
private boolean flattenForSlowMotion;
private int outputHeight;
private String outputMimeType;
@Nullable private String audioMimeType;
@Nullable private String videoMimeType;
private TranscodingTransformer.Listener listener;
private Looper looper;
private Clock clock;
/** Creates a builder with default values. */
public Builder() {
muxerFactory = new FrameworkMuxer.Factory();
outputMimeType = MimeTypes.VIDEO_MP4;
listener = new Listener() {};
looper = Util.getCurrentOrMainLooper();
clock = Clock.DEFAULT;
}
/** Creates a builder with the values of the provided {@link TranscodingTransformer}. */
private Builder(TranscodingTransformer transcodingTransformer) {
this.context = transcodingTransformer.context;
this.mediaSourceFactory = transcodingTransformer.mediaSourceFactory;
this.muxerFactory = transcodingTransformer.muxerFactory;
this.removeAudio = transcodingTransformer.transformation.removeAudio;
this.removeVideo = transcodingTransformer.transformation.removeVideo;
this.flattenForSlowMotion = transcodingTransformer.transformation.flattenForSlowMotion;
this.outputHeight = transcodingTransformer.transformation.outputHeight;
this.outputMimeType = transcodingTransformer.transformation.outputMimeType;
this.audioMimeType = transcodingTransformer.transformation.audioMimeType;
this.videoMimeType = transcodingTransformer.transformation.videoMimeType;
this.listener = transcodingTransformer.listener;
this.looper = transcodingTransformer.looper;
this.clock = transcodingTransformer.clock;
}
/**
* Sets the {@link Context}.
*
* <p>This parameter is mandatory.
*
* @param context The {@link Context}.
* @return This builder.
*/
public Builder setContext(Context context) {
this.context = context.getApplicationContext();
return this;
}
/**
* Sets the {@link MediaSourceFactory} to be used to retrieve the inputs to transform. The
* default value is a {@link DefaultMediaSourceFactory} built with the context provided in
* {@link #setContext(Context)}.
*
* @param mediaSourceFactory A {@link MediaSourceFactory}.
* @return This builder.
*/
public Builder setMediaSourceFactory(MediaSourceFactory mediaSourceFactory) {
this.mediaSourceFactory = mediaSourceFactory;
return this;
}
/**
* Sets whether to remove the audio from the output. The default value is {@code false}.
*
* <p>The audio and video cannot both be removed because the output would not contain any
* samples.
*
* @param removeAudio Whether to remove the audio.
* @return This builder.
*/
public Builder setRemoveAudio(boolean removeAudio) {
this.removeAudio = removeAudio;
return this;
}
/**
* Sets whether to remove the video from the output. The default value is {@code false}.
*
* <p>The audio and video cannot both be removed because the output would not contain any
* samples.
*
* @param removeVideo Whether to remove the video.
* @return This builder.
*/
public Builder setRemoveVideo(boolean removeVideo) {
this.removeVideo = removeVideo;
return this;
}
/**
* Sets whether the input should be flattened for media containing slow motion markers. The
* transformed output is obtained by removing the slow motion metadata and by actually slowing
* down the parts of the video and audio streams defined in this metadata. The default value for
* {@code flattenForSlowMotion} is {@code false}.
*
* <p>Only Samsung Extension Format (SEF) slow motion metadata type is supported. The
* transformation has no effect if the input does not contain this metadata type.
*
* <p>For SEF slow motion media, the following assumptions are made on the input:
*
* <ul>
* <li>The input container format is (unfragmented) MP4.
* <li>The input contains an AVC video elementary stream with temporal SVC.
* <li>The recording frame rate of the video is 120 or 240 fps.
* </ul>
*
* <p>If specifying a {@link MediaSourceFactory} using {@link
* #setMediaSourceFactory(MediaSourceFactory)}, make sure that {@link
* Mp4Extractor#FLAG_READ_SEF_DATA} is set on the {@link Mp4Extractor} used. Otherwise, the slow
* motion metadata will be ignored and the input won't be flattened.
*
* @param flattenForSlowMotion Whether to flatten for slow motion.
* @return This builder.
*/
public Builder setFlattenForSlowMotion(boolean flattenForSlowMotion) {
this.flattenForSlowMotion = flattenForSlowMotion;
return this;
}
/**
* Sets the output resolution for the video, using the output height. The default value is to
* use the same height as the input. Output width will scale to preserve the input video's
* aspect ratio.
*
* <p>For example, a 1920x1440 video can be scaled to 640x480 by calling setResolution(480).
*
* @param outputHeight The output height for the video, in pixels.
* @return This builder.
*/
public Builder setResolution(int outputHeight) {
this.outputHeight = outputHeight;
return this;
}
/**
* Sets the MIME type of the output. The default value is {@link MimeTypes#VIDEO_MP4}. Supported
* values are:
*
* <ul>
* <li>{@link MimeTypes#VIDEO_MP4}
* <li>{@link MimeTypes#VIDEO_WEBM} from API level 21
* </ul>
*
* @param outputMimeType The MIME type of the output.
* @return This builder.
*/
public Builder setOutputMimeType(String outputMimeType) {
this.outputMimeType = outputMimeType;
return this;
}
/**
* Sets the video MIME type of the output. The default value is to use the same MIME type as the
* input. Supported values are:
*
* <ul>
* <li>when the container MIME type is {@link MimeTypes#VIDEO_MP4}:
* <ul>
* <li>{@link MimeTypes#VIDEO_H263}
* <li>{@link MimeTypes#VIDEO_H264}
* <li>{@link MimeTypes#VIDEO_H265} from API level 24
* <li>{@link MimeTypes#VIDEO_MP4V}
* </ul>
* <li>when the container MIME type is {@link MimeTypes#VIDEO_WEBM}:
* <ul>
* <li>{@link MimeTypes#VIDEO_VP8}
* <li>{@link MimeTypes#VIDEO_VP9} from API level 24
* </ul>
* </ul>
*
* @param videoMimeType The MIME type of the video samples in the output.
* @return This builder.
*/
public Builder setVideoMimeType(String videoMimeType) {
this.videoMimeType = videoMimeType;
return this;
}
/**
* Sets the audio MIME type of the output. The default value is to use the same MIME type as the
* input. Supported values are:
*
* <ul>
* <li>when the container MIME type is {@link MimeTypes#VIDEO_MP4}:
* <ul>
* <li>{@link MimeTypes#AUDIO_AAC}
* <li>{@link MimeTypes#AUDIO_AMR_NB}
* <li>{@link MimeTypes#AUDIO_AMR_WB}
* </ul>
* <li>when the container MIME type is {@link MimeTypes#VIDEO_WEBM}:
* <ul>
* <li>{@link MimeTypes#AUDIO_VORBIS}
* </ul>
* </ul>
*
* @param audioMimeType The MIME type of the audio samples in the output.
* @return This builder.
*/
public Builder setAudioMimeType(String audioMimeType) {
this.audioMimeType = audioMimeType;
return this;
}
/**
* Sets the {@link TranscodingTransformer.Listener} to listen to the transformation events.
*
* <p>This is equivalent to {@link TranscodingTransformer#setListener(Listener)}.
*
* @param listener A {@link TranscodingTransformer.Listener}.
* @return This builder.
*/
public Builder setListener(TranscodingTransformer.Listener listener) {
this.listener = listener;
return this;
}
/**
* Sets the {@link Looper} that must be used for all calls to the transcoding transformer and
* that is used to call listeners on. The default value is the Looper of the thread that this
* builder was created on, or if that thread does not have a Looper, the Looper of the
* application's main thread.
*
* @param looper A {@link Looper}.
* @return This builder.
*/
public Builder setLooper(Looper looper) {
this.looper = looper;
return this;
}
/**
* Sets the {@link Clock} that will be used by the transcoding transformer. The default value is
* {@link Clock#DEFAULT}.
*
* @param clock The {@link Clock} instance.
* @return This builder.
*/
@VisibleForTesting
/* package */ Builder setClock(Clock clock) {
this.clock = clock;
return this;
}
/**
* Sets the factory for muxers that write the media container. The default value is a {@link
* FrameworkMuxer.Factory}.
*
* @param muxerFactory A {@link Muxer.Factory}.
* @return This builder.
*/
@VisibleForTesting
/* package */ Builder setMuxerFactory(Muxer.Factory muxerFactory) {
this.muxerFactory = muxerFactory;
return this;
}
/**
* Builds a {@link TranscodingTransformer} instance.
*
* @throws IllegalStateException If the {@link Context} has not been provided.
* @throws IllegalStateException If both audio and video have been removed (otherwise the output
* would not contain any samples).
* @throws IllegalStateException If the muxer doesn't support the requested output MIME type.
* @throws IllegalStateException If the muxer doesn't support the requested audio MIME type.
*/
public TranscodingTransformer build() {
checkStateNotNull(context);
if (mediaSourceFactory == null) {
DefaultExtractorsFactory defaultExtractorsFactory = new DefaultExtractorsFactory();
if (flattenForSlowMotion) {
defaultExtractorsFactory.setMp4ExtractorFlags(Mp4Extractor.FLAG_READ_SEF_DATA);
}
mediaSourceFactory = new DefaultMediaSourceFactory(context, defaultExtractorsFactory);
}
checkState(
muxerFactory.supportsOutputMimeType(outputMimeType),
"Unsupported output MIME type: " + outputMimeType);
// TODO(ME): Test with values of 10, 100, 1000).
Log.e("TranscodingTransformer", "outputHeight = " + outputHeight);
if (outputHeight == 0) {
// TODO(ME): get output height from input video.
outputHeight = 480;
}
if (audioMimeType != null) {
checkSampleMimeType(audioMimeType);
}
if (videoMimeType != null) {
checkSampleMimeType(videoMimeType);
}
Transformation transformation =
new Transformation(
removeAudio,
removeVideo,
flattenForSlowMotion,
outputHeight,
outputMimeType,
audioMimeType,
videoMimeType);
return new TranscodingTransformer(
context, mediaSourceFactory, muxerFactory, transformation, listener, looper, clock);
}
private void checkSampleMimeType(String sampleMimeType) {
checkState(
muxerFactory.supportsSampleMimeType(sampleMimeType, outputMimeType),
"Unsupported sample MIME type "
+ sampleMimeType
+ " for container MIME type "
+ outputMimeType);
}
}
/** A listener for the transformation events. */
public interface Listener {
/**
* Called when the transformation is completed.
*
* @param inputMediaItem The {@link MediaItem} for which the transformation is completed.
*/
default void onTransformationCompleted(MediaItem inputMediaItem) {}
/**
* Called if an error occurs during the transformation.
*
* @param inputMediaItem The {@link MediaItem} for which the error occurs.
* @param exception The exception describing the error.
*/
default void onTransformationError(MediaItem inputMediaItem, Exception exception) {}
}
/**
* Progress state. One of {@link #PROGRESS_STATE_WAITING_FOR_AVAILABILITY}, {@link
* #PROGRESS_STATE_AVAILABLE}, {@link #PROGRESS_STATE_UNAVAILABLE}, {@link
* #PROGRESS_STATE_NO_TRANSFORMATION}
*/
@Documented
@Retention(RetentionPolicy.SOURCE)
@IntDef({
PROGRESS_STATE_WAITING_FOR_AVAILABILITY,
PROGRESS_STATE_AVAILABLE,
PROGRESS_STATE_UNAVAILABLE,
PROGRESS_STATE_NO_TRANSFORMATION
})
public @interface ProgressState {}
/**
* Indicates that the progress is unavailable for the current transformation, but might become
* available.
*/
public static final int PROGRESS_STATE_WAITING_FOR_AVAILABILITY = 0;
/** Indicates that the progress is available. */
public static final int PROGRESS_STATE_AVAILABLE = 1;
/** Indicates that the progress is permanently unavailable for the current transformation. */
public static final int PROGRESS_STATE_UNAVAILABLE = 2;
/** Indicates that there is no current transformation. */
public static final int PROGRESS_STATE_NO_TRANSFORMATION = 4;
private final Context context;
private final MediaSourceFactory mediaSourceFactory;
private final Muxer.Factory muxerFactory;
private final Transformation transformation;
private final Looper looper;
private final Clock clock;
private TranscodingTransformer.Listener listener;
@Nullable private MuxerWrapper muxerWrapper;
@Nullable private ExoPlayer player;
@ProgressState private int progressState;
private TranscodingTransformer(
Context context,
MediaSourceFactory mediaSourceFactory,
Muxer.Factory muxerFactory,
Transformation transformation,
TranscodingTransformer.Listener listener,
Looper looper,
Clock clock) {
checkState(
!transformation.removeAudio || !transformation.removeVideo,
"Audio and video cannot both be removed.");
this.context = context;
this.mediaSourceFactory = mediaSourceFactory;
this.muxerFactory = muxerFactory;
this.transformation = transformation;
this.listener = listener;
this.looper = looper;
this.clock = clock;
progressState = PROGRESS_STATE_NO_TRANSFORMATION;
}
/**
* Returns a {@link TranscodingTransformer.Builder} initialized with the values of this instance.
*/
public Builder buildUpon() {
return new Builder(this);
}
/**
* Sets the {@link TranscodingTransformer.Listener} to listen to the transformation events.
*
* @param listener A {@link TranscodingTransformer.Listener}.
* @throws IllegalStateException If this method is called from the wrong thread.
*/
public void setListener(TranscodingTransformer.Listener listener) {
verifyApplicationThread();
this.listener = listener;
}
/**
* Starts an asynchronous operation to transform the given {@link MediaItem}.
*
* <p>The transformation state is notified through the {@link Builder#setListener(Listener)
* listener}.
*
* <p>Concurrent transformations on the same TranscodingTransformer object are not allowed.
*
* <p>The output can contain at most one video track and one audio track. Other track types are
* ignored. For adaptive bitrate {@link MediaSource media sources}, the highest bitrate video and
* audio streams are selected.
*
* @param mediaItem The {@link MediaItem} to transform. The supported sample formats depend on the
* {@link Muxer} and on the output container format. For the {@link FrameworkMuxer}, they are
* described in {@link MediaMuxer#addTrack(MediaFormat)}.
* @param path The path to the output file.
* @throws IllegalArgumentException If the path is invalid.
* @throws IllegalStateException If this method is called from the wrong thread.
* @throws IllegalStateException If a transformation is already in progress.
* @throws IOException If an error occurs opening the output file for writing.
*/
public void startTransformation(MediaItem mediaItem, String path) throws IOException {
startTransformation(mediaItem, muxerFactory.create(path, transformation.outputMimeType));
}
/**
* Starts an asynchronous operation to transform the given {@link MediaItem}.
*
* <p>The transformation state is notified through the {@link Builder#setListener(Listener)
* listener}.
*
* <p>Concurrent transformations on the same TranscodingTransformer object are not allowed.
*
* <p>The output can contain at most one video track and one audio track. Other track types are
* ignored. For adaptive bitrate {@link MediaSource media sources}, the highest bitrate video and
* audio streams are selected.
*
* @param mediaItem The {@link MediaItem} to transform. The supported sample formats depend on the
* {@link Muxer} and on the output container format. For the {@link FrameworkMuxer}, they are
* described in {@link MediaMuxer#addTrack(MediaFormat)}.
* @param parcelFileDescriptor A readable and writable {@link ParcelFileDescriptor} of the output.
* The file referenced by this ParcelFileDescriptor should not be used before the
* transformation is completed. It is the responsibility of the caller to close the
* ParcelFileDescriptor. This can be done after this method returns.
* @throws IllegalArgumentException If the file descriptor is invalid.
* @throws IllegalStateException If this method is called from the wrong thread.
* @throws IllegalStateException If a transformation is already in progress.
* @throws IOException If an error occurs opening the output file for writing.
*/
@RequiresApi(26)
public void startTransformation(MediaItem mediaItem, ParcelFileDescriptor parcelFileDescriptor)
throws IOException {
startTransformation(
mediaItem, muxerFactory.create(parcelFileDescriptor, transformation.outputMimeType));
}
private void startTransformation(MediaItem mediaItem, Muxer muxer) {
verifyApplicationThread();
if (player != null) {
throw new IllegalStateException("There is already a transformation in progress.");
}
MuxerWrapper muxerWrapper =
new MuxerWrapper(muxer, muxerFactory, transformation.outputMimeType);
this.muxerWrapper = muxerWrapper;
DefaultTrackSelector trackSelector = new DefaultTrackSelector(context);
trackSelector.setParameters(
new DefaultTrackSelector.ParametersBuilder(context)
.setForceHighestSupportedBitrate(true)
.build());
// Arbitrarily decrease buffers for playback so that samples start being sent earlier to the
// muxer (rebuffers are less problematic for the transformation use case).
DefaultLoadControl loadControl =
new DefaultLoadControl.Builder()
.setBufferDurationsMs(
DEFAULT_MIN_BUFFER_MS,
DEFAULT_MAX_BUFFER_MS,
DEFAULT_BUFFER_FOR_PLAYBACK_MS / 10,
DEFAULT_BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS / 10)
.build();
player =
new ExoPlayer.Builder(
context,
new TranscodingTransformerRenderersFactory(context, muxerWrapper, transformation))
.setMediaSourceFactory(mediaSourceFactory)
.setTrackSelector(trackSelector)
.setLoadControl(loadControl)
.setLooper(looper)
.setClock(clock)
.build();
player.setMediaItem(mediaItem);
player.addListener(new TranscodingTransformerPlayerListener(mediaItem, muxerWrapper));
player.prepare();
progressState = PROGRESS_STATE_WAITING_FOR_AVAILABILITY;
}
/**
* Returns the {@link Looper} associated with the application thread that's used to access the
* transcoding transformer and on which transcoding transformer events are received.
*/
public Looper getApplicationLooper() {
return looper;
}
/**
* Returns the current {@link ProgressState} and updates {@code progressHolder} with the current
* progress if it is {@link #PROGRESS_STATE_AVAILABLE available}.
*
* <p>After a transformation {@link Listener#onTransformationCompleted(MediaItem) completes}, this
* method returns {@link #PROGRESS_STATE_NO_TRANSFORMATION}.
*
* @param progressHolder A {@link ProgressHolder}, updated to hold the percentage progress if
* {@link #PROGRESS_STATE_AVAILABLE available}.
* @return The {@link ProgressState}.
* @throws IllegalStateException If this method is called from the wrong thread.
*/
@ProgressState
public int getProgress(ProgressHolder progressHolder) {
verifyApplicationThread();
if (progressState == PROGRESS_STATE_AVAILABLE) {
Player player = checkNotNull(this.player);
long durationMs = player.getDuration();
long positionMs = player.getCurrentPosition();
progressHolder.progress = min((int) (positionMs * 100 / durationMs), 99);
}
return progressState;
}
/**
* Cancels the transformation that is currently in progress, if any.
*
* @throws IllegalStateException If this method is called from the wrong thread.
*/
public void cancel() {
releaseResources(/* forCancellation= */ true);
}
/**
* Releases the resources.
*
* @param forCancellation Whether the reason for releasing the resources is the transformation
* cancellation.
* @throws IllegalStateException If this method is called from the wrong thread.
* @throws IllegalStateException If the muxer is in the wrong state and {@code forCancellation} is
* false.
*/
private void releaseResources(boolean forCancellation) {
verifyApplicationThread();
if (player != null) {
player.release();
player = null;
}
if (muxerWrapper != null) {
muxerWrapper.release(forCancellation);
muxerWrapper = null;
}
progressState = PROGRESS_STATE_NO_TRANSFORMATION;
}
private void verifyApplicationThread() {
if (Looper.myLooper() != looper) {
throw new IllegalStateException("Transcoding Transformer is accessed on the wrong thread.");
}
}
private static final class TranscodingTransformerRenderersFactory implements RenderersFactory {
private final Context context;
private final MuxerWrapper muxerWrapper;
private final TransformerMediaClock mediaClock;
private final Transformation transformation;
public TranscodingTransformerRenderersFactory(
Context context, MuxerWrapper muxerWrapper, Transformation transformation) {
this.context = context;
this.muxerWrapper = muxerWrapper;
this.transformation = transformation;
mediaClock = new TransformerMediaClock();
}
@Override
public Renderer[] createRenderers(
Handler eventHandler,
VideoRendererEventListener videoRendererEventListener,
AudioRendererEventListener audioRendererEventListener,
TextOutput textRendererOutput,
MetadataOutput metadataRendererOutput) {
int rendererCount = transformation.removeAudio || transformation.removeVideo ? 1 : 2;
Renderer[] renderers = new Renderer[rendererCount];
int index = 0;
if (!transformation.removeAudio) {
renderers[index] = new TransformerAudioRenderer(muxerWrapper, mediaClock, transformation);
index++;
}
if (!transformation.removeVideo) {
renderers[index] =
new TransformerTranscodingVideoRenderer(
context, muxerWrapper, mediaClock, transformation);
index++;
}
return renderers;
}
}
private final class TranscodingTransformerPlayerListener implements Player.Listener {
private final MediaItem mediaItem;
private final MuxerWrapper muxerWrapper;
public TranscodingTransformerPlayerListener(MediaItem mediaItem, MuxerWrapper muxerWrapper) {
this.mediaItem = mediaItem;
this.muxerWrapper = muxerWrapper;
}
@Override
public void onPlaybackStateChanged(int state) {
if (state == Player.STATE_ENDED) {
handleTransformationEnded(/* exception= */ null);
}
}
@Override
public void onTimelineChanged(Timeline timeline, int reason) {
if (progressState != PROGRESS_STATE_WAITING_FOR_AVAILABILITY) {
return;
}
Timeline.Window window = new Timeline.Window();
timeline.getWindow(/* windowIndex= */ 0, window);
if (!window.isPlaceholder) {
long durationUs = window.durationUs;
// Make progress permanently unavailable if the duration is unknown, so that it doesn't jump
// to a high value at the end of the transformation if the duration is set once the media is
// entirely loaded.
progressState =
durationUs <= 0 || durationUs == C.TIME_UNSET
? PROGRESS_STATE_UNAVAILABLE
: PROGRESS_STATE_AVAILABLE;
checkNotNull(player).play();
}
}
@Override
public void onTracksInfoChanged(TracksInfo tracksInfo) {
if (muxerWrapper.getTrackCount() == 0) {
handleTransformationEnded(
new IllegalStateException(
"The output does not contain any tracks. Check that at least one of the input"
+ " sample formats is supported."));
}
}
@Override
public void onPlayerError(PlaybackException error) {
handleTransformationEnded(error);
}
private void handleTransformationEnded(@Nullable Exception exception) {
try {
releaseResources(/* forCancellation= */ false);
} catch (IllegalStateException e) {
if (exception == null) {
exception = e;
}
}
if (exception == null) {
listener.onTransformationCompleted(mediaItem);
} else {
listener.onTransformationError(mediaItem, exception);
}
}
}
}
| library/transformer/src/main/java/com/google/android/exoplayer2/transformer/TranscodingTransformer.java | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.transformer;
import static com.google.android.exoplayer2.DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS;
import static com.google.android.exoplayer2.DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_MS;
import static com.google.android.exoplayer2.DefaultLoadControl.DEFAULT_MAX_BUFFER_MS;
import static com.google.android.exoplayer2.DefaultLoadControl.DEFAULT_MIN_BUFFER_MS;
import static com.google.android.exoplayer2.util.Assertions.checkNotNull;
import static com.google.android.exoplayer2.util.Assertions.checkState;
import static com.google.android.exoplayer2.util.Assertions.checkStateNotNull;
import static java.lang.Math.min;
import android.content.Context;
import android.media.MediaFormat;
import android.media.MediaMuxer;
import android.os.Handler;
import android.os.Looper;
import android.os.ParcelFileDescriptor;
import androidx.annotation.IntDef;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.VisibleForTesting;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.PlaybackException;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.Renderer;
import com.google.android.exoplayer2.RenderersFactory;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.TracksInfo;
import com.google.android.exoplayer2.audio.AudioRendererEventListener;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.extractor.mp4.Mp4Extractor;
import com.google.android.exoplayer2.metadata.MetadataOutput;
import com.google.android.exoplayer2.source.DefaultMediaSourceFactory;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.MediaSourceFactory;
import com.google.android.exoplayer2.text.TextOutput;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.util.Clock;
import com.google.android.exoplayer2.util.Log;
import com.google.android.exoplayer2.util.MimeTypes;
import com.google.android.exoplayer2.util.Util;
import com.google.android.exoplayer2.video.VideoRendererEventListener;
import java.io.IOException;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
/**
* A transcoding transformer to transform media inputs.
*
* <p>Temporary copy of the {@link Transformer} class, which transforms by transcoding rather than
* by muxing. This class is intended to replace the Transformer class.
*
* <p>TODO(http://b/202131097): Replace the Transformer class with TranscodingTransformer, and
* rename this class to Transformer.
*
* <p>The same TranscodingTransformer instance can be used to transform multiple inputs
* (sequentially, not concurrently).
*
* <p>TranscodingTransformer instances must be accessed from a single application thread. For the
* vast majority of cases this should be the application's main thread. The thread on which a
* TranscodingTransformer instance must be accessed can be explicitly specified by passing a {@link
* Looper} when creating the transcoding transformer. If no Looper is specified, then the Looper of
* the thread that the {@link TranscodingTransformer.Builder} is created on is used, or if that
* thread does not have a Looper, the Looper of the application's main thread is used. In all cases
* the Looper of the thread from which the transcoding transformer must be accessed can be queried
* using {@link #getApplicationLooper()}.
*/
@RequiresApi(18)
public final class TranscodingTransformer {
/** A builder for {@link TranscodingTransformer} instances. */
public static final class Builder {
// Mandatory field.
private @MonotonicNonNull Context context;
// Optional fields.
private @MonotonicNonNull MediaSourceFactory mediaSourceFactory;
private Muxer.Factory muxerFactory;
private boolean removeAudio;
private boolean removeVideo;
private boolean flattenForSlowMotion;
private int outputHeight;
private String outputMimeType;
@Nullable private String audioMimeType;
@Nullable private String videoMimeType;
private TranscodingTransformer.Listener listener;
private Looper looper;
private Clock clock;
/** Creates a builder with default values. */
public Builder() {
muxerFactory = new FrameworkMuxer.Factory();
outputMimeType = MimeTypes.VIDEO_MP4;
listener = new Listener() {};
looper = Util.getCurrentOrMainLooper();
clock = Clock.DEFAULT;
}
/** Creates a builder with the values of the provided {@link TranscodingTransformer}. */
private Builder(TranscodingTransformer transcodingTransformer) {
this.context = transcodingTransformer.context;
this.mediaSourceFactory = transcodingTransformer.mediaSourceFactory;
this.muxerFactory = transcodingTransformer.muxerFactory;
this.removeAudio = transcodingTransformer.transformation.removeAudio;
this.removeVideo = transcodingTransformer.transformation.removeVideo;
this.flattenForSlowMotion = transcodingTransformer.transformation.flattenForSlowMotion;
this.outputHeight = transcodingTransformer.transformation.outputHeight;
this.outputMimeType = transcodingTransformer.transformation.outputMimeType;
this.audioMimeType = transcodingTransformer.transformation.audioMimeType;
this.videoMimeType = transcodingTransformer.transformation.videoMimeType;
this.listener = transcodingTransformer.listener;
this.looper = transcodingTransformer.looper;
this.clock = transcodingTransformer.clock;
}
/**
* Sets the {@link Context}.
*
* <p>This parameter is mandatory.
*
* @param context The {@link Context}.
* @return This builder.
*/
public Builder setContext(Context context) {
this.context = context.getApplicationContext();
return this;
}
/**
* Sets the {@link MediaSourceFactory} to be used to retrieve the inputs to transform. The
* default value is a {@link DefaultMediaSourceFactory} built with the context provided in
* {@link #setContext(Context)}.
*
* @param mediaSourceFactory A {@link MediaSourceFactory}.
* @return This builder.
*/
public Builder setMediaSourceFactory(MediaSourceFactory mediaSourceFactory) {
this.mediaSourceFactory = mediaSourceFactory;
return this;
}
/**
* Sets whether to remove the audio from the output. The default value is {@code false}.
*
* <p>The audio and video cannot both be removed because the output would not contain any
* samples.
*
* @param removeAudio Whether to remove the audio.
* @return This builder.
*/
public Builder setRemoveAudio(boolean removeAudio) {
this.removeAudio = removeAudio;
return this;
}
/**
* Sets whether to remove the video from the output. The default value is {@code false}.
*
* <p>The audio and video cannot both be removed because the output would not contain any
* samples.
*
* @param removeVideo Whether to remove the video.
* @return This builder.
*/
public Builder setRemoveVideo(boolean removeVideo) {
this.removeVideo = removeVideo;
return this;
}
/**
* Sets whether the input should be flattened for media containing slow motion markers. The
* transformed output is obtained by removing the slow motion metadata and by actually slowing
* down the parts of the video and audio streams defined in this metadata. The default value for
* {@code flattenForSlowMotion} is {@code false}.
*
* <p>Only Samsung Extension Format (SEF) slow motion metadata type is supported. The
* transformation has no effect if the input does not contain this metadata type.
*
* <p>For SEF slow motion media, the following assumptions are made on the input:
*
* <ul>
* <li>The input container format is (unfragmented) MP4.
* <li>The input contains an AVC video elementary stream with temporal SVC.
* <li>The recording frame rate of the video is 120 or 240 fps.
* </ul>
*
* <p>If specifying a {@link MediaSourceFactory} using {@link
* #setMediaSourceFactory(MediaSourceFactory)}, make sure that {@link
* Mp4Extractor#FLAG_READ_SEF_DATA} is set on the {@link Mp4Extractor} used. Otherwise, the slow
* motion metadata will be ignored and the input won't be flattened.
*
* @param flattenForSlowMotion Whether to flatten for slow motion.
* @return This builder.
*/
public Builder setFlattenForSlowMotion(boolean flattenForSlowMotion) {
this.flattenForSlowMotion = flattenForSlowMotion;
return this;
}
/**
* Sets the output resolution for the video, using the output height. The default value is to
* use the same height as the input. Output width will scale to preserve the input video's
* aspect ratio.
*
* <p>For example, a 1920x1440 video can be scaled to 640x480 by calling setResolution(480).
*
* @param outputHeight The output height for the video, in pixels.
* @return This builder.
*/
public Builder setResolution(int outputHeight) {
this.outputHeight = outputHeight;
return this;
}
/**
* Sets the MIME type of the output. The default value is {@link MimeTypes#VIDEO_MP4}. Supported
* values are:
*
* <ul>
* <li>{@link MimeTypes#VIDEO_MP4}
* <li>{@link MimeTypes#VIDEO_WEBM} from API level 21
* </ul>
*
* @param outputMimeType The MIME type of the output.
* @return This builder.
*/
public Builder setOutputMimeType(String outputMimeType) {
this.outputMimeType = outputMimeType;
return this;
}
/**
* Sets the video MIME type of the output. The default value is to use the same MIME type as the
* input. Supported values are:
*
* <ul>
* <li>when the container MIME type is {@link MimeTypes#VIDEO_MP4}:
* <ul>
* <li>{@link MimeTypes#VIDEO_H263}
* <li>{@link MimeTypes#VIDEO_H264}
* <li>{@link MimeTypes#VIDEO_H265} from API level 24
* <li>{@link MimeTypes#VIDEO_MP4V}
* </ul>
* <li>when the container MIME type is {@link MimeTypes#VIDEO_WEBM}:
* <ul>
* <li>{@link MimeTypes#VIDEO_VP8}
* <li>{@link MimeTypes#VIDEO_VP9} from API level 24
* </ul>
* </ul>
*
* @param videoMimeType The MIME type of the video samples in the output.
* @return This builder.
*/
public Builder setVideoMimeType(String videoMimeType) {
this.videoMimeType = videoMimeType;
return this;
}
/**
* Sets the audio MIME type of the output. The default value is to use the same MIME type as the
* input. Supported values are:
*
* <ul>
* <li>when the container MIME type is {@link MimeTypes#VIDEO_MP4}:
* <ul>
* <li>{@link MimeTypes#AUDIO_AAC}
* <li>{@link MimeTypes#AUDIO_AMR_NB}
* <li>{@link MimeTypes#AUDIO_AMR_WB}
* </ul>
* <li>when the container MIME type is {@link MimeTypes#VIDEO_WEBM}:
* <ul>
* <li>{@link MimeTypes#AUDIO_VORBIS}
* </ul>
* </ul>
*
* @param audioMimeType The MIME type of the audio samples in the output.
* @return This builder.
*/
public Builder setAudioMimeType(String audioMimeType) {
this.audioMimeType = audioMimeType;
return this;
}
/**
* Sets the {@link TranscodingTransformer.Listener} to listen to the transformation events.
*
* <p>This is equivalent to {@link TranscodingTransformer#setListener(Listener)}.
*
* @param listener A {@link TranscodingTransformer.Listener}.
* @return This builder.
*/
public Builder setListener(TranscodingTransformer.Listener listener) {
this.listener = listener;
return this;
}
/**
* Sets the {@link Looper} that must be used for all calls to the transcoding transformer and
* that is used to call listeners on. The default value is the Looper of the thread that this
* builder was created on, or if that thread does not have a Looper, the Looper of the
* application's main thread.
*
* @param looper A {@link Looper}.
* @return This builder.
*/
public Builder setLooper(Looper looper) {
this.looper = looper;
return this;
}
/**
* Sets the {@link Clock} that will be used by the transcoding transformer. The default value is
* {@link Clock#DEFAULT}.
*
* @param clock The {@link Clock} instance.
* @return This builder.
*/
@VisibleForTesting
/* package */ Builder setClock(Clock clock) {
this.clock = clock;
return this;
}
/**
* Sets the factory for muxers that write the media container. The default value is a {@link
* FrameworkMuxer.Factory}.
*
* @param muxerFactory A {@link Muxer.Factory}.
* @return This builder.
*/
@VisibleForTesting
/* package */ Builder setMuxerFactory(Muxer.Factory muxerFactory) {
this.muxerFactory = muxerFactory;
return this;
}
/**
* Builds a {@link TranscodingTransformer} instance.
*
* @throws IllegalStateException If the {@link Context} has not been provided.
* @throws IllegalStateException If both audio and video have been removed (otherwise the output
* would not contain any samples).
* @throws IllegalStateException If the muxer doesn't support the requested output MIME type.
* @throws IllegalStateException If the muxer doesn't support the requested audio MIME type.
*/
public TranscodingTransformer build() {
checkStateNotNull(context);
if (mediaSourceFactory == null) {
DefaultExtractorsFactory defaultExtractorsFactory = new DefaultExtractorsFactory();
if (flattenForSlowMotion) {
defaultExtractorsFactory.setMp4ExtractorFlags(Mp4Extractor.FLAG_READ_SEF_DATA);
}
mediaSourceFactory = new DefaultMediaSourceFactory(context, defaultExtractorsFactory);
}
checkState(
muxerFactory.supportsOutputMimeType(outputMimeType),
"Unsupported output MIME type: " + outputMimeType);
// TODO(ME): Test with values of 10, 100, 1000).
Log.e("TranscodingTransformer", "outputHeight = " + outputHeight);
if (outputHeight == 0) {
// TODO(ME): get output height from input video.
outputHeight = 480;
}
if (audioMimeType != null) {
checkSampleMimeType(audioMimeType);
}
if (videoMimeType != null) {
checkSampleMimeType(videoMimeType);
}
Transformation transformation =
new Transformation(
removeAudio,
removeVideo,
flattenForSlowMotion,
outputHeight,
outputMimeType,
audioMimeType,
videoMimeType);
return new TranscodingTransformer(
context, mediaSourceFactory, muxerFactory, transformation, listener, looper, clock);
}
private void checkSampleMimeType(String sampleMimeType) {
checkState(
muxerFactory.supportsSampleMimeType(sampleMimeType, outputMimeType),
"Unsupported sample MIME type "
+ sampleMimeType
+ " for container MIME type "
+ outputMimeType);
}
}
/** A listener for the transformation events. */
public interface Listener {
/**
* Called when the transformation is completed.
*
* @param inputMediaItem The {@link MediaItem} for which the transformation is completed.
*/
default void onTransformationCompleted(MediaItem inputMediaItem) {}
/**
* Called if an error occurs during the transformation.
*
* @param inputMediaItem The {@link MediaItem} for which the error occurs.
* @param exception The exception describing the error.
*/
default void onTransformationError(MediaItem inputMediaItem, Exception exception) {}
}
/**
* Progress state. One of {@link #PROGRESS_STATE_WAITING_FOR_AVAILABILITY}, {@link
* #PROGRESS_STATE_AVAILABLE}, {@link #PROGRESS_STATE_UNAVAILABLE}, {@link
* #PROGRESS_STATE_NO_TRANSFORMATION}
*/
@Documented
@Retention(RetentionPolicy.SOURCE)
@IntDef({
PROGRESS_STATE_WAITING_FOR_AVAILABILITY,
PROGRESS_STATE_AVAILABLE,
PROGRESS_STATE_UNAVAILABLE,
PROGRESS_STATE_NO_TRANSFORMATION
})
public @interface ProgressState {}
/**
* Indicates that the progress is unavailable for the current transformation, but might become
* available.
*/
public static final int PROGRESS_STATE_WAITING_FOR_AVAILABILITY = 0;
/** Indicates that the progress is available. */
public static final int PROGRESS_STATE_AVAILABLE = 1;
/** Indicates that the progress is permanently unavailable for the current transformation. */
public static final int PROGRESS_STATE_UNAVAILABLE = 2;
/** Indicates that there is no current transformation. */
public static final int PROGRESS_STATE_NO_TRANSFORMATION = 4;
private final Context context;
private final MediaSourceFactory mediaSourceFactory;
private final Muxer.Factory muxerFactory;
private final Transformation transformation;
private final Looper looper;
private final Clock clock;
private TranscodingTransformer.Listener listener;
@Nullable private MuxerWrapper muxerWrapper;
@Nullable private ExoPlayer player;
@ProgressState private int progressState;
private TranscodingTransformer(
Context context,
MediaSourceFactory mediaSourceFactory,
Muxer.Factory muxerFactory,
Transformation transformation,
TranscodingTransformer.Listener listener,
Looper looper,
Clock clock) {
checkState(
!transformation.removeAudio || !transformation.removeVideo,
"Audio and video cannot both be removed.");
checkState(!(transformation.removeVideo));
this.context = context;
this.mediaSourceFactory = mediaSourceFactory;
this.muxerFactory = muxerFactory;
this.transformation = transformation;
this.listener = listener;
this.looper = looper;
this.clock = clock;
progressState = PROGRESS_STATE_NO_TRANSFORMATION;
}
/**
* Returns a {@link TranscodingTransformer.Builder} initialized with the values of this instance.
*/
public Builder buildUpon() {
return new Builder(this);
}
/**
* Sets the {@link TranscodingTransformer.Listener} to listen to the transformation events.
*
* @param listener A {@link TranscodingTransformer.Listener}.
* @throws IllegalStateException If this method is called from the wrong thread.
*/
public void setListener(TranscodingTransformer.Listener listener) {
verifyApplicationThread();
this.listener = listener;
}
/**
* Starts an asynchronous operation to transform the given {@link MediaItem}.
*
* <p>The transformation state is notified through the {@link Builder#setListener(Listener)
* listener}.
*
* <p>Concurrent transformations on the same TranscodingTransformer object are not allowed.
*
* <p>The output can contain at most one video track and one audio track. Other track types are
* ignored. For adaptive bitrate {@link MediaSource media sources}, the highest bitrate video and
* audio streams are selected.
*
* @param mediaItem The {@link MediaItem} to transform. The supported sample formats depend on the
* {@link Muxer} and on the output container format. For the {@link FrameworkMuxer}, they are
* described in {@link MediaMuxer#addTrack(MediaFormat)}.
* @param path The path to the output file.
* @throws IllegalArgumentException If the path is invalid.
* @throws IllegalStateException If this method is called from the wrong thread.
* @throws IllegalStateException If a transformation is already in progress.
* @throws IOException If an error occurs opening the output file for writing.
*/
public void startTransformation(MediaItem mediaItem, String path) throws IOException {
startTransformation(mediaItem, muxerFactory.create(path, transformation.outputMimeType));
}
/**
* Starts an asynchronous operation to transform the given {@link MediaItem}.
*
* <p>The transformation state is notified through the {@link Builder#setListener(Listener)
* listener}.
*
* <p>Concurrent transformations on the same TranscodingTransformer object are not allowed.
*
* <p>The output can contain at most one video track and one audio track. Other track types are
* ignored. For adaptive bitrate {@link MediaSource media sources}, the highest bitrate video and
* audio streams are selected.
*
* @param mediaItem The {@link MediaItem} to transform. The supported sample formats depend on the
* {@link Muxer} and on the output container format. For the {@link FrameworkMuxer}, they are
* described in {@link MediaMuxer#addTrack(MediaFormat)}.
* @param parcelFileDescriptor A readable and writable {@link ParcelFileDescriptor} of the output.
* The file referenced by this ParcelFileDescriptor should not be used before the
* transformation is completed. It is the responsibility of the caller to close the
* ParcelFileDescriptor. This can be done after this method returns.
* @throws IllegalArgumentException If the file descriptor is invalid.
* @throws IllegalStateException If this method is called from the wrong thread.
* @throws IllegalStateException If a transformation is already in progress.
* @throws IOException If an error occurs opening the output file for writing.
*/
@RequiresApi(26)
public void startTransformation(MediaItem mediaItem, ParcelFileDescriptor parcelFileDescriptor)
throws IOException {
startTransformation(
mediaItem, muxerFactory.create(parcelFileDescriptor, transformation.outputMimeType));
}
private void startTransformation(MediaItem mediaItem, Muxer muxer) {
verifyApplicationThread();
if (player != null) {
throw new IllegalStateException("There is already a transformation in progress.");
}
MuxerWrapper muxerWrapper =
new MuxerWrapper(muxer, muxerFactory, transformation.outputMimeType);
this.muxerWrapper = muxerWrapper;
DefaultTrackSelector trackSelector = new DefaultTrackSelector(context);
trackSelector.setParameters(
new DefaultTrackSelector.ParametersBuilder(context)
.setForceHighestSupportedBitrate(true)
.build());
// Arbitrarily decrease buffers for playback so that samples start being sent earlier to the
// muxer (rebuffers are less problematic for the transformation use case).
DefaultLoadControl loadControl =
new DefaultLoadControl.Builder()
.setBufferDurationsMs(
DEFAULT_MIN_BUFFER_MS,
DEFAULT_MAX_BUFFER_MS,
DEFAULT_BUFFER_FOR_PLAYBACK_MS / 10,
DEFAULT_BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS / 10)
.build();
player =
new ExoPlayer.Builder(
context,
new TranscodingTransformerRenderersFactory(context, muxerWrapper, transformation))
.setMediaSourceFactory(mediaSourceFactory)
.setTrackSelector(trackSelector)
.setLoadControl(loadControl)
.setLooper(looper)
.setClock(clock)
.build();
player.setMediaItem(mediaItem);
player.addListener(new TranscodingTransformerPlayerListener(mediaItem, muxerWrapper));
player.prepare();
progressState = PROGRESS_STATE_WAITING_FOR_AVAILABILITY;
}
/**
* Returns the {@link Looper} associated with the application thread that's used to access the
* transcoding transformer and on which transcoding transformer events are received.
*/
public Looper getApplicationLooper() {
return looper;
}
/**
* Returns the current {@link ProgressState} and updates {@code progressHolder} with the current
* progress if it is {@link #PROGRESS_STATE_AVAILABLE available}.
*
* <p>After a transformation {@link Listener#onTransformationCompleted(MediaItem) completes}, this
* method returns {@link #PROGRESS_STATE_NO_TRANSFORMATION}.
*
* @param progressHolder A {@link ProgressHolder}, updated to hold the percentage progress if
* {@link #PROGRESS_STATE_AVAILABLE available}.
* @return The {@link ProgressState}.
* @throws IllegalStateException If this method is called from the wrong thread.
*/
@ProgressState
public int getProgress(ProgressHolder progressHolder) {
verifyApplicationThread();
if (progressState == PROGRESS_STATE_AVAILABLE) {
Player player = checkNotNull(this.player);
long durationMs = player.getDuration();
long positionMs = player.getCurrentPosition();
progressHolder.progress = min((int) (positionMs * 100 / durationMs), 99);
}
return progressState;
}
/**
* Cancels the transformation that is currently in progress, if any.
*
* @throws IllegalStateException If this method is called from the wrong thread.
*/
public void cancel() {
releaseResources(/* forCancellation= */ true);
}
/**
* Releases the resources.
*
* @param forCancellation Whether the reason for releasing the resources is the transformation
* cancellation.
* @throws IllegalStateException If this method is called from the wrong thread.
* @throws IllegalStateException If the muxer is in the wrong state and {@code forCancellation} is
* false.
*/
private void releaseResources(boolean forCancellation) {
verifyApplicationThread();
if (player != null) {
player.release();
player = null;
}
if (muxerWrapper != null) {
muxerWrapper.release(forCancellation);
muxerWrapper = null;
}
progressState = PROGRESS_STATE_NO_TRANSFORMATION;
}
private void verifyApplicationThread() {
if (Looper.myLooper() != looper) {
throw new IllegalStateException("Transcoding Transformer is accessed on the wrong thread.");
}
}
private static final class TranscodingTransformerRenderersFactory implements RenderersFactory {
private final Context context;
private final MuxerWrapper muxerWrapper;
private final TransformerMediaClock mediaClock;
private final Transformation transformation;
public TranscodingTransformerRenderersFactory(
Context context, MuxerWrapper muxerWrapper, Transformation transformation) {
this.context = context;
this.muxerWrapper = muxerWrapper;
this.transformation = transformation;
mediaClock = new TransformerMediaClock();
}
@Override
public Renderer[] createRenderers(
Handler eventHandler,
VideoRendererEventListener videoRendererEventListener,
AudioRendererEventListener audioRendererEventListener,
TextOutput textRendererOutput,
MetadataOutput metadataRendererOutput) {
int rendererCount = transformation.removeAudio || transformation.removeVideo ? 1 : 2;
Renderer[] renderers = new Renderer[rendererCount];
int index = 0;
if (!transformation.removeAudio) {
renderers[index] = new TransformerAudioRenderer(muxerWrapper, mediaClock, transformation);
index++;
}
if (!transformation.removeVideo) {
renderers[index] =
new TransformerTranscodingVideoRenderer(
context, muxerWrapper, mediaClock, transformation);
index++;
}
return renderers;
}
}
private final class TranscodingTransformerPlayerListener implements Player.Listener {
private final MediaItem mediaItem;
private final MuxerWrapper muxerWrapper;
public TranscodingTransformerPlayerListener(MediaItem mediaItem, MuxerWrapper muxerWrapper) {
this.mediaItem = mediaItem;
this.muxerWrapper = muxerWrapper;
}
@Override
public void onPlaybackStateChanged(int state) {
if (state == Player.STATE_ENDED) {
handleTransformationEnded(/* exception= */ null);
}
}
@Override
public void onTimelineChanged(Timeline timeline, int reason) {
if (progressState != PROGRESS_STATE_WAITING_FOR_AVAILABILITY) {
return;
}
Timeline.Window window = new Timeline.Window();
timeline.getWindow(/* windowIndex= */ 0, window);
if (!window.isPlaceholder) {
long durationUs = window.durationUs;
// Make progress permanently unavailable if the duration is unknown, so that it doesn't jump
// to a high value at the end of the transformation if the duration is set once the media is
// entirely loaded.
progressState =
durationUs <= 0 || durationUs == C.TIME_UNSET
? PROGRESS_STATE_UNAVAILABLE
: PROGRESS_STATE_AVAILABLE;
checkNotNull(player).play();
}
}
@Override
public void onTracksInfoChanged(TracksInfo tracksInfo) {
if (muxerWrapper.getTrackCount() == 0) {
handleTransformationEnded(
new IllegalStateException(
"The output does not contain any tracks. Check that at least one of the input"
+ " sample formats is supported."));
}
}
@Override
public void onPlayerError(PlaybackException error) {
handleTransformationEnded(error);
}
private void handleTransformationEnded(@Nullable Exception exception) {
try {
releaseResources(/* forCancellation= */ false);
} catch (IllegalStateException e) {
if (exception == null) {
exception = e;
}
}
if (exception == null) {
listener.onTransformationCompleted(mediaItem);
} else {
listener.onTransformationError(mediaItem, exception);
}
}
}
}
| Allow remove video transformer option.
PiperOrigin-RevId: 406849436
| library/transformer/src/main/java/com/google/android/exoplayer2/transformer/TranscodingTransformer.java | Allow remove video transformer option. |
|
Java | apache-2.0 | 84202c29e6b9385feddbb349a5722b71955993b9 | 0 | iyounus/incubator-systemml,gweidner/incubator-systemml,dusenberrymw/incubator-systemml,dusenberrymw/systemml,dhutchis/systemml,niketanpansare/systemml,akchinSTC/systemml,iyounus/incubator-systemml,asurve/arvind-sysml2,asurve/incubator-systemml,iyounus/incubator-systemml,gweidner/systemml,deroneriksson/incubator-systemml,akchinSTC/systemml,gweidner/incubator-systemml,deroneriksson/incubator-systemml,Myasuka/systemml,gweidner/systemml,akchinSTC/systemml,asurve/incubator-systemml,Wenpei/incubator-systemml,Myasuka/systemml,deroneriksson/incubator-systemml,apache/incubator-systemml,dusenberrymw/incubator-systemml,iyounus/incubator-systemml,dusenberrymw/incubator-systemml,asurve/incubator-systemml,asurve/incubator-systemml,deroneriksson/incubator-systemml,apache/incubator-systemml,deroneriksson/incubator-systemml,asurve/arvind-sysml2,sandeep-n/incubator-systemml,nakul02/systemml,nakul02/systemml,asurve/arvind-sysml2,asurve/systemml,fschueler/incubator-systemml,asurve/arvind-sysml2,iyounus/incubator-systemml,dhutchis/systemml,niketanpansare/incubator-systemml,sandeep-n/incubator-systemml,gweidner/incubator-systemml,deroneriksson/systemml,fschueler/incubator-systemml,asurve/systemml,deroneriksson/systemml,dhutchis/systemml,dusenberrymw/incubator-systemml,gweidner/incubator-systemml,apache/incubator-systemml,deroneriksson/incubator-systemml,Wenpei/incubator-systemml,nakul02/incubator-systemml,dusenberrymw/incubator-systemml,dhutchis/systemml,Myasuka/systemml,dusenberrymw/systemml,nakul02/systemml,niketanpansare/systemml,apache/incubator-systemml,apache/incubator-systemml,Wenpei/incubator-systemml,gweidner/systemml,gweidner/incubator-systemml,dusenberrymw/systemml,asurve/systemml,asurve/arvind-sysml2,asurve/incubator-systemml,nakul02/systemml,asurve/incubator-systemml,niketanpansare/systemml,akchinSTC/systemml,nakul02/incubator-systemml,asurve/systemml,asurve/systemml,fschueler/incubator-systemml,apache/incubator-systemml,sandeep-n/incubator-systemml,niketanpansare/systemml,dusenberrymw/systemml,niketanpansare/incubator-systemml,nakul02/systemml,dhutchis/systemml,dusenberrymw/systemml,gweidner/systemml,gweidner/systemml,deroneriksson/systemml,fschueler/incubator-systemml,akchinSTC/systemml,niketanpansare/systemml,deroneriksson/systemml,nakul02/incubator-systemml,nakul02/incubator-systemml,iyounus/incubator-systemml,Myasuka/systemml,deroneriksson/systemml,akchinSTC/systemml,niketanpansare/incubator-systemml,asurve/arvind-sysml2,niketanpansare/incubator-systemml,gweidner/systemml,dhutchis/systemml,dusenberrymw/incubator-systemml,niketanpansare/systemml,nakul02/systemml,Myasuka/systemml,Wenpei/incubator-systemml,dusenberrymw/systemml,nakul02/incubator-systemml,gweidner/incubator-systemml,asurve/systemml,nakul02/incubator-systemml,Myasuka/systemml,deroneriksson/systemml,sandeep-n/incubator-systemml | /**
* IBM Confidential
* OCO Source Materials
* (C) Copyright IBM Corp. 2010, 2015
* The source code for this program is not published or otherwise divested of its trade secrets, irrespective of what has been deposited with the U.S. Copyright Office.
*/
package com.ibm.bi.dml.runtime.instructions.spark;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.Function2;
import scala.Tuple2;
import com.ibm.bi.dml.parser.Expression.DataType;
import com.ibm.bi.dml.parser.Expression.ValueType;
import com.ibm.bi.dml.runtime.DMLRuntimeException;
import com.ibm.bi.dml.runtime.DMLUnsupportedOperationException;
import com.ibm.bi.dml.runtime.controlprogram.context.ExecutionContext;
import com.ibm.bi.dml.runtime.controlprogram.context.SparkExecutionContext;
import com.ibm.bi.dml.runtime.functionobjects.CM;
import com.ibm.bi.dml.runtime.instructions.Instruction;
import com.ibm.bi.dml.runtime.instructions.InstructionUtils;
import com.ibm.bi.dml.runtime.instructions.cp.CM_COV_Object;
import com.ibm.bi.dml.runtime.instructions.cp.CPOperand;
import com.ibm.bi.dml.runtime.instructions.cp.DoubleObject;
import com.ibm.bi.dml.runtime.instructions.cp.ScalarObject;
import com.ibm.bi.dml.runtime.matrix.data.MatrixBlock;
import com.ibm.bi.dml.runtime.matrix.data.MatrixIndexes;
import com.ibm.bi.dml.runtime.matrix.operators.CMOperator;
import com.ibm.bi.dml.runtime.matrix.operators.CMOperator.AggregateOperationTypes;
/**
*
*/
public class CentralMomentSPInstruction extends UnarySPInstruction
{
@SuppressWarnings("unused")
private static final String _COPYRIGHT = "Licensed Materials - Property of IBM\n(C) Copyright IBM Corp. 2010, 2015\n" +
"US Government Users Restricted Rights - Use, duplication disclosure restricted by GSA ADP Schedule Contract with IBM Corp.";
public CentralMomentSPInstruction(CMOperator op, CPOperand in1, CPOperand in2,
CPOperand in3, CPOperand out, String opcode, String str)
{
super(op, in1, in2, in3, out, opcode, str);
}
/**
*
* @param str
* @return
* @throws DMLRuntimeException
*/
public static Instruction parseInstruction(String str)
throws DMLRuntimeException
{
CPOperand in1 = new CPOperand("", ValueType.UNKNOWN, DataType.UNKNOWN);
CPOperand in2 = null;
CPOperand in3 = null;
CPOperand out = new CPOperand("", ValueType.UNKNOWN, DataType.UNKNOWN);
String opcode = InstructionUtils.getOpCode(str);
//check supported opcode
if( !opcode.equalsIgnoreCase("cm") ) {
throw new DMLRuntimeException("Unsupported opcode "+opcode);
}
String[] parts = InstructionUtils.getInstructionPartsWithValueType(str);
if ( parts.length == 4 ) {
// Example: CP.cm.mVar0.Var1.mVar2; (without weights)
in2 = new CPOperand("", ValueType.UNKNOWN, DataType.UNKNOWN);
parseUnaryInstruction(str, in1, in2, out);
}
else if ( parts.length == 5) {
// CP.cm.mVar0.mVar1.Var2.mVar3; (with weights)
in2 = new CPOperand("", ValueType.UNKNOWN, DataType.UNKNOWN);
in3 = new CPOperand("", ValueType.UNKNOWN, DataType.UNKNOWN);
parseUnaryInstruction(str, in1, in2, in3, out);
}
// Exact order of the central moment MAY NOT be known at compilation time.
// We first try to parse the second argument as an integer, and if we fail,
// we simply pass -1 so that getCMAggOpType() picks up AggregateOperationTypes.INVALID.
// It must be updated at run time in processInstruction() method.
int cmOrder;
try {
if ( in3 == null ) {
cmOrder = Integer.parseInt(in2.getName());
}
else {
cmOrder = Integer.parseInt(in3.getName());
}
} catch(NumberFormatException e) {
cmOrder = -1; // unknown at compilation time
}
AggregateOperationTypes opType = CMOperator.getCMAggOpType(cmOrder);
CMOperator cm = new CMOperator(CM.getCMFnObject(opType), opType);
return new CentralMomentSPInstruction(cm, in1, in2, in3, out, opcode, str);
}
@Override
public void processInstruction( ExecutionContext ec )
throws DMLRuntimeException, DMLUnsupportedOperationException
{
SparkExecutionContext sec = (SparkExecutionContext)ec;
//parse 'order' input argument
CPOperand scalarInput = (input3==null ? input2 : input3);
ScalarObject order = ec.getScalarInput(scalarInput.getName(), scalarInput.getValueType(), scalarInput.isLiteral());
CMOperator cop = ((CMOperator)_optr);
if ( cop.getAggOpType() == AggregateOperationTypes.INVALID ) {
cop.setCMAggOp((int)order.getLongValue());
}
//get input
JavaPairRDD<MatrixIndexes,MatrixBlock> in1 = sec.getBinaryBlockRDDHandleForVariable( input1.getName() );
//process central moment instruction
CM_COV_Object cmobj = null;
if( input3 == null ) //w/o weights
{
cmobj = in1.values().map(new RDDCMFunction(cop))
.reduce(new RDDCMReduceFunction(cop));
}
else //with weights
{
JavaPairRDD<MatrixIndexes,MatrixBlock> in2 = sec.getBinaryBlockRDDHandleForVariable( input2.getName() );
cmobj = in1.join( in2 )
.values().map(new RDDCMWeightsFunction(cop))
.reduce(new RDDCMReduceFunction(cop));
}
//create scalar output (no lineage information required)
double val = cmobj.getRequiredResult(_optr);
DoubleObject ret = new DoubleObject(output.getName(), val);
ec.setScalarOutput(output.getName(), ret);
}
/**
*
*/
private static class RDDCMFunction implements Function<MatrixBlock, CM_COV_Object>
{
private static final long serialVersionUID = 2293839116041610644L;
private CMOperator _op = null;
public RDDCMFunction( CMOperator op ) {
_op = op;
}
@Override
public CM_COV_Object call(MatrixBlock arg0)
throws Exception
{
//execute cm operations
return arg0.cmOperations(_op);
}
}
/**
*
*/
private static class RDDCMWeightsFunction implements Function<Tuple2<MatrixBlock,MatrixBlock>, CM_COV_Object>
{
private static final long serialVersionUID = -8949715516574052497L;
private CMOperator _op = null;
public RDDCMWeightsFunction( CMOperator op ) {
_op = op;
}
@Override
public CM_COV_Object call(Tuple2<MatrixBlock,MatrixBlock> arg0)
throws Exception
{
MatrixBlock input = arg0._1();
MatrixBlock weights = arg0._2();
//execute cm operations
return input.cmOperations(_op, weights);
}
}
private static class RDDCMReduceFunction implements Function2<CM_COV_Object, CM_COV_Object, CM_COV_Object>
{
@SuppressWarnings("unused")
private static final String _COPYRIGHT = "Licensed Materials - Property of IBM\n(C) Copyright IBM Corp. 2010, 2015\n" +
"US Government Users Restricted Rights - Use, duplication disclosure restricted by GSA ADP Schedule Contract with IBM Corp.";
private static final long serialVersionUID = 3272260751983866544L;
private CMOperator _op = null;
public RDDCMReduceFunction( CMOperator op ) {
_op = op;
}
@Override
public CM_COV_Object call(CM_COV_Object arg0, CM_COV_Object arg1)
throws Exception
{
CM_COV_Object out = new CM_COV_Object();
//execute cm combine operations
_op.fn.execute(out, arg0);
_op.fn.execute(out, arg1);
return out;
}
}
}
| SystemML/SystemML/src/main/java/com/ibm/bi/dml/runtime/instructions/spark/CentralMomentSPInstruction.java | /**
* IBM Confidential
* OCO Source Materials
* (C) Copyright IBM Corp. 2010, 2015
* The source code for this program is not published or otherwise divested of its trade secrets, irrespective of what has been deposited with the U.S. Copyright Office.
*/
package com.ibm.bi.dml.runtime.instructions.spark;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.Function2;
import scala.Tuple2;
import com.ibm.bi.dml.parser.Expression.DataType;
import com.ibm.bi.dml.parser.Expression.ValueType;
import com.ibm.bi.dml.runtime.DMLRuntimeException;
import com.ibm.bi.dml.runtime.DMLUnsupportedOperationException;
import com.ibm.bi.dml.runtime.controlprogram.context.ExecutionContext;
import com.ibm.bi.dml.runtime.controlprogram.context.SparkExecutionContext;
import com.ibm.bi.dml.runtime.functionobjects.CM;
import com.ibm.bi.dml.runtime.instructions.Instruction;
import com.ibm.bi.dml.runtime.instructions.InstructionUtils;
import com.ibm.bi.dml.runtime.instructions.cp.CM_COV_Object;
import com.ibm.bi.dml.runtime.instructions.cp.CPOperand;
import com.ibm.bi.dml.runtime.instructions.cp.CentralMomentCPInstruction;
import com.ibm.bi.dml.runtime.instructions.cp.DoubleObject;
import com.ibm.bi.dml.runtime.instructions.cp.ScalarObject;
import com.ibm.bi.dml.runtime.matrix.data.MatrixBlock;
import com.ibm.bi.dml.runtime.matrix.data.MatrixIndexes;
import com.ibm.bi.dml.runtime.matrix.operators.AggregateUnaryOperator;
import com.ibm.bi.dml.runtime.matrix.operators.CMOperator;
import com.ibm.bi.dml.runtime.matrix.operators.CMOperator.AggregateOperationTypes;
/**
*
*/
public class CentralMomentSPInstruction extends AggregateUnarySPInstruction
{
@SuppressWarnings("unused")
private static final String _COPYRIGHT = "Licensed Materials - Property of IBM\n(C) Copyright IBM Corp. 2010, 2015\n" +
"US Government Users Restricted Rights - Use, duplication disclosure restricted by GSA ADP Schedule Contract with IBM Corp.";
public CentralMomentSPInstruction(AggregateUnaryOperator op, CPOperand in, CPOperand out, String opcode, String istr){
super(op, null, in, out, null, opcode, istr);
}
/**
*
* @param str
* @return
* @throws DMLRuntimeException
*/
public static Instruction parseInstruction(String str)
throws DMLRuntimeException
{
CPOperand in1 = new CPOperand("", ValueType.UNKNOWN, DataType.UNKNOWN);
CPOperand in2 = null;
CPOperand in3 = null;
CPOperand out = new CPOperand("", ValueType.UNKNOWN, DataType.UNKNOWN);
String opcode = InstructionUtils.getOpCode(str);
//check supported opcode
if( !opcode.equalsIgnoreCase("cm") ) {
throw new DMLRuntimeException("Unsupported opcode "+opcode);
}
String[] parts = InstructionUtils.getInstructionPartsWithValueType(str);
if ( parts.length == 4 ) {
// Example: CP.cm.mVar0.Var1.mVar2; (without weights)
in2 = new CPOperand("", ValueType.UNKNOWN, DataType.UNKNOWN);
parseUnaryInstruction(str, in1, in2, out);
}
else if ( parts.length == 5) {
// CP.cm.mVar0.mVar1.Var2.mVar3; (with weights)
in2 = new CPOperand("", ValueType.UNKNOWN, DataType.UNKNOWN);
in3 = new CPOperand("", ValueType.UNKNOWN, DataType.UNKNOWN);
parseUnaryInstruction(str, in1, in2, in3, out);
}
// Exact order of the central moment MAY NOT be known at compilation time.
// We first try to parse the second argument as an integer, and if we fail,
// we simply pass -1 so that getCMAggOpType() picks up AggregateOperationTypes.INVALID.
// It must be updated at run time in processInstruction() method.
int cmOrder;
try {
if ( in3 == null ) {
cmOrder = Integer.parseInt(in2.getName());
}
else {
cmOrder = Integer.parseInt(in3.getName());
}
} catch(NumberFormatException e) {
cmOrder = -1; // unknown at compilation time
}
AggregateOperationTypes opType = CMOperator.getCMAggOpType(cmOrder);
CMOperator cm = new CMOperator(CM.getCMFnObject(opType), opType);
return new CentralMomentCPInstruction(cm, in1, in2, in3, out, opcode, str);
}
@Override
public void processInstruction( ExecutionContext ec )
throws DMLRuntimeException, DMLUnsupportedOperationException
{
SparkExecutionContext sec = (SparkExecutionContext)ec;
//parse 'order' input argument
CPOperand scalarInput = (input3==null ? input2 : input3);
ScalarObject order = ec.getScalarInput(scalarInput.getName(), scalarInput.getValueType(), scalarInput.isLiteral());
CMOperator cop = ((CMOperator)_optr);
if ( cop.getAggOpType() == AggregateOperationTypes.INVALID ) {
cop.setCMAggOp((int)order.getLongValue());
}
//get input
JavaPairRDD<MatrixIndexes,MatrixBlock> in1 = sec.getBinaryBlockRDDHandleForVariable( input1.getName() );
//process central moment instruction
CM_COV_Object cmobj = null;
if( input3 == null ) //w/o weights
{
cmobj = in1.values().map(new RDDCMFunction(cop))
.reduce(new RDDCMReduceFunction(cop));
}
else //with weights
{
JavaPairRDD<MatrixIndexes,MatrixBlock> in2 = sec.getBinaryBlockRDDHandleForVariable( input2.getName() );
cmobj = in1.join( in2 )
.values().map(new RDDCMWeightsFunction(cop))
.reduce(new RDDCMReduceFunction(cop));
}
//create scalar output (no lineage information required)
double val = cmobj.getRequiredResult(_optr);
DoubleObject ret = new DoubleObject(output.getName(), val);
ec.setScalarOutput(output.getName(), ret);
}
/**
*
*/
private static class RDDCMFunction implements Function<MatrixBlock, CM_COV_Object>
{
private static final long serialVersionUID = 2293839116041610644L;
private CMOperator _op = null;
public RDDCMFunction( CMOperator op ) {
_op = op;
}
@Override
public CM_COV_Object call(MatrixBlock arg0)
throws Exception
{
//execute cm operations
return arg0.cmOperations(_op);
}
}
/**
*
*/
private static class RDDCMWeightsFunction implements Function<Tuple2<MatrixBlock,MatrixBlock>, CM_COV_Object>
{
private static final long serialVersionUID = -8949715516574052497L;
private CMOperator _op = null;
public RDDCMWeightsFunction( CMOperator op ) {
_op = op;
}
@Override
public CM_COV_Object call(Tuple2<MatrixBlock,MatrixBlock> arg0)
throws Exception
{
MatrixBlock input = arg0._1();
MatrixBlock weights = arg0._2();
//execute cm operations
return input.cmOperations(_op, weights);
}
}
public class RDDCMReduceFunction implements Function2<CM_COV_Object, CM_COV_Object, CM_COV_Object>
{
@SuppressWarnings("unused")
private static final String _COPYRIGHT = "Licensed Materials - Property of IBM\n(C) Copyright IBM Corp. 2010, 2015\n" +
"US Government Users Restricted Rights - Use, duplication disclosure restricted by GSA ADP Schedule Contract with IBM Corp.";
private static final long serialVersionUID = 3272260751983866544L;
private CMOperator _op = null;
public RDDCMReduceFunction( CMOperator op ) {
_op = op;
}
@Override
public CM_COV_Object call(CM_COV_Object arg0, CM_COV_Object arg1)
throws Exception
{
CM_COV_Object out = new CM_COV_Object();
//execute cm combine operations
_op.fn.execute(out, arg0);
_op.fn.execute(out, arg1);
return out;
}
}
}
| 94919: Spark Backend - Fix spark central moment instruction (cp redirection, inst closure)
| SystemML/SystemML/src/main/java/com/ibm/bi/dml/runtime/instructions/spark/CentralMomentSPInstruction.java | 94919: Spark Backend - Fix spark central moment instruction (cp redirection, inst closure) |
|
Java | apache-2.0 | 6569442066678765486dc7d69ce4d160bd21dcf0 | 0 | CrystalCraftMC/ZeroSuit | /*
* Copyright 2015 CrystalCraftMC
*
* 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.crystalcraftmc.zerosuit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import javax.swing.Timer;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World.Environment;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.Vector;
/**Main class:
* This program will automatically enable fly-mode when someone enters an area
*
* @author Alex Woodward
*/
public class ZeroSuit extends JavaPlugin implements Listener {
/**This holds all regions of zero g's*/
private ArrayList<ZeroGArea> zeroArea = new ArrayList<ZeroGArea>();
/**Holds all players who have flying perms*/
private ArrayList<String> flyPerms = new ArrayList<String>();
/**Holds players who got a "entered zero-g" message in the last half a second*/
private ArrayList<Player> msgCap = new ArrayList<Player>();
/**Holds players with zerosuit on*/
private ArrayList<Player> zs = new ArrayList<Player>();
/**Update checks on people currently wearing zerosuits*/
private Timer tim;
/**Holds this instance*/
ZeroSuit thisInstance;
public void onEnable() {
this.initializeZeroGAreaFile();
this.initializePermsFile();
this.getServer().getPluginManager().registerEvents(this, this);
thisInstance = this;
tim = new Timer(500, new Update());
tim.start();
}
public void onDisable() {
msgCap.clear();
tim.stop();
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String args[]) {
if(sender instanceof Player) {
Player p = (Player)sender;
if(p.hasPermission("ZeroSuit.zerog") && label.equalsIgnoreCase("zerog")) {
if(args.length == 8) {
if(args[0].equalsIgnoreCase("add")) {
boolean validArguments = true;
if(!this.isInt(args[1]))
validArguments = false;
if(!this.isInt(args[2]))
validArguments = false;
if(!this.isInt(args[3]))
validArguments = false;
if(!this.isInt(args[4]))
validArguments = false;
if(!this.isInt(args[5]))
validArguments = false;
if(!this.isInt(args[6]))
validArguments = false;
if(validArguments) {
String world = "";
if(p.getWorld().getEnvironment() == Environment.NORMAL)
world = "overworld";
else if(p.getWorld().getEnvironment() == Environment.NETHER)
world = "nether";
else if(p.getWorld().getEnvironment() == Environment.THE_END)
world = "end";
for(int i = 0; i < zeroArea.size(); i++) {
if(zeroArea.get(i).getID().equalsIgnoreCase(args[7])) {
p.sendMessage(ChatColor.RED + "Error; a zero-suit area with ID: " +
ChatColor.GOLD + args[7] + ChatColor.RED + " already " +
"exists. Do /zerogflyperms to view all current zero-suit areas.");
return true;
}
}
zeroArea.add(new ZeroGArea(Integer.parseInt(args[1]),
Integer.parseInt(args[2]),
Integer.parseInt(args[3]), Integer.parseInt(args[4]),
Integer.parseInt(args[5]), Integer.parseInt(args[6]),
world, args[7]));
this.updateZeroGAreaFile();
p.sendMessage(ChatColor.GOLD + "Area successfully added.");
return true;
}
else {
p.sendMessage(ChatColor.RED + "Error; between arguments 2-7 (inclusive) some " +
"are not valid integer values.");
return false;
}
}
else {
p.sendMessage(ChatColor.RED + "Error; the first argument must read \'add\' or \'remove\'");
return false;
}
}
else if(args.length == 2) {
if(args[0].equalsIgnoreCase("remove")) {
for(int i = 0; i < zeroArea.size(); i++) {
if(zeroArea.get(i).getID().equalsIgnoreCase(args[1])) {
zeroArea.remove(i);
this.updateZeroGAreaFile();
p.sendMessage(ChatColor.BLUE + "Area successfully removed.");
return true;
}
}
p.sendMessage(ChatColor.RED + args[1] + ChatColor.GOLD + " is not " +
"an existing zero-gravity region ID. Type /zerog to view all current " +
"zero gravity regions.");
return true;
}
else {
p.sendMessage(ChatColor.RED + "Error; your first argument was not \'remove\'");
return false;
}
}
else if(args.length == 0) {
if(zeroArea.size() == 0) {
p.sendMessage(ChatColor.BLUE + "There are no zero-gravity regions currently made");
return true;
}
for(int i = 0; i < zeroArea.size(); i++) {
p.sendMessage(zeroArea.get(i).toString());
}
return true;
}
else {
return false;
}
}
else if(!p.hasPermission("ZeroSuit.zerog") && label.equalsIgnoreCase("zerog")) {
p.sendMessage(ChatColor.RED + "You do not have permission to perform this command.");
return true;
}
else if(p.hasPermission("ZeroSuit.zeroghelp") && label.equalsIgnoreCase("zeroghelp")) {
StringBuilder sb = new StringBuilder();
sb.append(ChatColor.LIGHT_PURPLE + "/zerog\n");
sb.append(ChatColor.AQUA + "This 0 argument command will list all areas that " +
"are zero-gravity regions\n");
sb.append(ChatColor.LIGHT_PURPLE + "/zerog <remove> <nameID>\n" +
ChatColor.AQUA + "This 2 argument command will remove a specified zero-gravity region\n");
sb.append(ChatColor.LIGHT_PURPLE + "/zerog <add> <x1> <y1> <z1> <x2> <y2> <z2> <nameID>\n" +
ChatColor.AQUA + "This 8 argument command will create a zero-gravity region in the " +
"world you're in (overworld | nether | end) at the given coordinates\n");
sb.append(ChatColor.BLUE + "/zerogfast\n" + ChatColor.AQUA +
"Sets your flyspeed to fast\n");
sb.append(ChatColor.BLUE + "/zerogslow\n" + ChatColor.AQUA +
"Sets your flyspeed to slow\n");
sb.append(ChatColor.GREEN + "/zeroghelp\n" + ChatColor.AQUA +
"Lists All ZeroSuit Commands");
p.sendMessage(sb.toString());
return true;
}
else if(!p.hasPermission("ZeroSuit.zeroghelp") && label.equalsIgnoreCase("zeroghelp")) {
p.sendMessage(ChatColor.RED + "Error; you do not have permission for this command.");
return true;
}
else if(label.equalsIgnoreCase("zerogfast")) {
p.setFlySpeed((float).2);
p.sendMessage(ChatColor.DARK_PURPLE + "Fly Speed Set To " + ChatColor.RED + "fast");
return true;
}
else if(label.equalsIgnoreCase("zerogslow")) {
p.setFlySpeed((float).1);
p.sendMessage(ChatColor.DARK_PURPLE + "Fly Speed Set To " + ChatColor.RED + "slow");
return true;
}
return false;
}
else
return false;
}
/**Will enable zerosuit if clicked*/
@EventHandler
public void zeroSuit(PlayerInteractEvent e) {
if(e.getAction() == Action.RIGHT_CLICK_BLOCK) {
if(e.getClickedBlock().getType() == Material.STONE_BUTTON ||
e.getClickedBlock().getType() == Material.WOOD_BUTTON) {
for(int i = 0; i < zeroArea.size(); i++) {
if(isInZeroG(e.getClickedBlock().getLocation(), zeroArea.get(i))) {
boolean isInList = false;
for(int ii = 0; ii < zs.size(); ii++) {
if(zs.get(ii).equals(e.getPlayer().getName()))
isInList = true;
}
if(!isInList)
zs.add(e.getPlayer());
e.getPlayer().setVelocity(new Vector(0, 1, 0));
e.getPlayer().setAllowFlight(true);
e.getPlayer().setFlying(true);
e.getPlayer().sendMessage(ChatColor.DARK_RED + "Now Entering " +
ChatColor.AQUA + "Zero-Gravity");
return;
}
}
}
}
}
///**Will let the player fly if they're in a zero-g area,
//* and will not let them fly if they aren't
//*/
/*@EventHandler
public void zeroGCheck(PlayerMoveEvent e) {
int zeroGIndex = -1;
for(int i = 0; i < zeroArea.size(); i++) {
boolean isInZeroG = this.isInZeroG(e.getPlayer().getLocation(), zeroArea.get(i));
if(isInZeroG)
zeroGIndex = i;
}
if(zeroGIndex != -1) {
if(!e.getPlayer().isFlying()) {
e.getPlayer().setAllowFlight(true);
e.getPlayer().setFlying(true);
boolean isInMsgCap = false;
for(int i = 0; i < msgCap.size(); i++) {
if(e.getPlayer().getName().equals(msgCap.get(i).getName()))
isInMsgCap = true;
}
if(!isInMsgCap) {
e.getPlayer().sendMessage(ChatColor.DARK_RED + "Now Entering " +
ChatColor.AQUA + "Zero-Gravity");
msgCap.add(e.getPlayer());
final Player p = e.getPlayer();
this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
public void run() {
msgCap.remove(p);
}
}, 10L);
}
}
}
else {
boolean hasFlyPerms = this.hasFlyPerms(e.getPlayer());
if(!hasFlyPerms) {
if(e.getPlayer().isFlying()) {
e.getPlayer().setAllowFlight(false);
e.getPlayer().setFlying(false);
}
}
else
e.getPlayer().setAllowFlight(true);
}
}*/
///**Will disable flying after a tp event*/
@EventHandler
public void noTpFly(PlayerTeleportEvent e) {
final Player p = e.getPlayer();
boolean gettoInZero = false;
for(int i = 0; i < zeroArea.size(); i++) {
if(!this.isInZeroG(e.getTo(), zeroArea.get(i))) {
gettoInZero = true;
}
}
if(!gettoInZero) {
if(!hasFlyPerms(e.getPlayer())) {
p.setFlying(false);
p.setAllowFlight(false);
}
}
}
/**This method checks whether a player is in a certain zeroArea region
* @return boolean, true if they're in the zeroArea region
*/
public boolean isInZeroG(Location loc, ZeroGArea zga) {
String world = "";
if(loc.getWorld().getEnvironment() == Environment.NORMAL)
world = "overworld";
else if(loc.getWorld().getEnvironment() == Environment.NETHER)
world = "nether";
else if(loc.getWorld().getEnvironment() == Environment.THE_END)
world = "end";
if(!world.equalsIgnoreCase(zga.getWorld())) {
return false;
}
boolean isInX, isInY, isInZ;
if(zga.x1 < zga.x2) {
isInX = loc.getX() < zga.x2 && loc.getX() > zga.x1 ? true : false;
}
else {
isInX = loc.getX() > zga.x2 && loc.getX() < zga.x1 ? true : false;
}
if(zga.y1 < zga.y2) {
isInY = loc.getY() < zga.y2 && loc.getY() > zga.y1 ? true : false;
}
else {
isInY = loc.getY() > zga.y2 && loc.getY() < zga.y1 ? true : false;
}
if(zga.z1 < zga.z2) {
isInZ = loc.getZ() < zga.z2 && loc.getZ() > zga.z1 ? true : false;
}
else {
isInZ = loc.getZ() > zga.z2 && loc.getZ() < zga.z1 ? true : false;
}
boolean isInsideZeroG = isInZ && isInY && isInX;
return isInsideZeroG;
}
/**This will initialize & read in data from the zerogarea .ser file*/
public void initializeZeroGAreaFile() {
File file = new File("ZeroSuitFiles\\ZeroGArea.ser");
if(!file.exists()) {
if(!new File("ZeroSuitFiles").exists())
new File("ZeroSuitFiles").mkdir();
}
else {
try{
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
zeroArea = (ArrayList)ois.readObject();
ois.close();
fis.close();
}catch(IOException e) { e.printStackTrace();
}catch(ClassNotFoundException e) { e.printStackTrace(); }
}
}
/**Updates the zerogarea file*/
public void updateZeroGAreaFile() {
File file = new File("ZeroSuitFiles\\ZeroGArea.ser");
if(!file.exists()) {
if(!new File("ZeroSuitFiles").exists())
new File("ZeroSuitFiles").mkdir();
}
else
file.delete();
try{
FileOutputStream fos = new FileOutputStream(new File("ZeroSuitFiles\\ZeroGArea.ser"));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(zeroArea);
oos.close();
fos.close();
}catch(IOException e) { e.printStackTrace(); }
}
/**Initializes & reads in the people who have permission*/
public void initializePermsFile() {
File file = new File("ZeroSuitFiles\\FlyPerms.ser");
if(file.exists())
file.delete();
if(!new File("ZeroSuitFiles").exists())
new File("ZeroSuitFiles").mkdir();
}
/**Checks whether a player has permission to fly
* @return boolean, true if the player has permission to fly
*/
public boolean hasFlyPerms(Player p) {
if(p.getGameMode() == GameMode.CREATIVE)
return true;
return false;
}
/*Checks whether a number is an int or not
* @return boolean, true if the number is an int
*/
public boolean isInt(String test) {
try{
Integer.parseInt(test);
return true;
}catch(NumberFormatException e) { return false; }
}
private class Update implements ActionListener {
public void actionPerformed(ActionEvent e) {
thisInstance.getServer().getScheduler().scheduleSyncDelayedTask(thisInstance, new Runnable() {
public void run() {
for(int i = 0; i < zs.size(); i++) {
if(!zs.get(i).isOnline()) {
zs.get(i).setFlying(false);
zs.get(i).setAllowFlight(false);
zs.remove(zs.get(i));
i--;
continue;
}
boolean isInZero = false;
for(int ii = 0; ii < zeroArea.size(); ii++) {
if(isInZeroG(zs.get(i).getLocation(), zeroArea.get(ii)))
isInZero = true;
}
if(!isInZero && !hasFlyPerms(zs.get(i))) {
zs.get(i).setAllowFlight(false);
zs.get(i).setFlying(false);
zs.remove(i);
i--;
}
else if(isInZero) {
zs.get(i).setAllowFlight(true);
zs.get(i).setFlying(true);
}
else if(hasFlyPerms(zs.get(i))) {
zs.get(i).setAllowFlight(true);
zs.remove(i);
i--;
}
}
}
}, 0L);
}
}
@EventHandler
public void noFlyLog(PlayerLoginEvent e) {
final Player p = e.getPlayer();
this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
public void run() {
boolean disable = !hasFlyPerms(p);
if(disable) {
p.setFlying(false);
p.setAllowFlight(false);
}
}
}, 5L);
}
}
| src/main/java/com/crystalcraftmc/zerosuit/ZeroSuit.java | /*
* Copyright 2015 CrystalCraftMC
*
* 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.crystalcraftmc.zerosuit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import javax.swing.Timer;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World.Environment;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.Vector;
/**Main class:
* This program will automatically enable fly-mode when someone enters an area
*
* @author Alex Woodward
*/
public class ZeroSuit extends JavaPlugin implements Listener {
/**This holds all regions of zero g's*/
private ArrayList<ZeroGArea> zeroArea = new ArrayList<ZeroGArea>();
/**Holds all players who have flying perms*/
private ArrayList<String> flyPerms = new ArrayList<String>();
/**Holds players who got a "entered zero-g" message in the last half a second*/
private ArrayList<Player> msgCap = new ArrayList<Player>();
/**Holds players with zerosuit on*/
private ArrayList<Player> zs = new ArrayList<Player>();
/**Update checks on people currently wearing zerosuits*/
private Timer tim;
/**Holds this instance*/
ZeroSuit thisInstance;
public void onEnable() {
this.initializeZeroGAreaFile();
this.initializePermsFile();
this.getServer().getPluginManager().registerEvents(this, this);
thisInstance = this;
tim = new Timer(500, new Update());
tim.start();
}
public void onDisable() {
msgCap.clear();
tim.stop();
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String args[]) {
if(sender instanceof Player) {
Player p = (Player)sender;
if(p.hasPermission("ZeroSuit.zerog") && label.equalsIgnoreCase("zerog")) {
if(args.length == 8) {
if(args[0].equalsIgnoreCase("add")) {
boolean validArguments = true;
if(!this.isInt(args[1]))
validArguments = false;
if(!this.isInt(args[2]))
validArguments = false;
if(!this.isInt(args[3]))
validArguments = false;
if(!this.isInt(args[4]))
validArguments = false;
if(!this.isInt(args[5]))
validArguments = false;
if(!this.isInt(args[6]))
validArguments = false;
if(validArguments) {
String world = "";
if(p.getWorld().getEnvironment() == Environment.NORMAL)
world = "overworld";
else if(p.getWorld().getEnvironment() == Environment.NETHER)
world = "nether";
else if(p.getWorld().getEnvironment() == Environment.THE_END)
world = "end";
for(int i = 0; i < zeroArea.size(); i++) {
if(zeroArea.get(i).getID().equalsIgnoreCase(args[7])) {
p.sendMessage(ChatColor.RED + "Error; a zero-suit area with ID: " +
ChatColor.GOLD + args[7] + ChatColor.RED + " already " +
"exists. Do /zerogflyperms to view all current zero-suit areas.");
return true;
}
}
zeroArea.add(new ZeroGArea(Integer.parseInt(args[1]),
Integer.parseInt(args[2]),
Integer.parseInt(args[3]), Integer.parseInt(args[4]),
Integer.parseInt(args[5]), Integer.parseInt(args[6]),
world, args[7]));
this.updateZeroGAreaFile();
p.sendMessage(ChatColor.GOLD + "Area successfully added.");
return true;
}
else {
p.sendMessage(ChatColor.RED + "Error; between arguments 2-7 (inclusive) some " +
"are not valid integer values.");
return false;
}
}
else {
p.sendMessage(ChatColor.RED + "Error; the first argument must read \'add\' or \'remove\'");
return false;
}
}
else if(args.length == 2) {
if(args[0].equalsIgnoreCase("remove")) {
for(int i = 0; i < zeroArea.size(); i++) {
if(zeroArea.get(i).getID().equalsIgnoreCase(args[1])) {
zeroArea.remove(i);
this.updateZeroGAreaFile();
p.sendMessage(ChatColor.BLUE + "Area successfully removed.");
return true;
}
}
p.sendMessage(ChatColor.RED + args[1] + ChatColor.GOLD + " is not " +
"an existing zero-gravity region ID. Type /zerog to view all current " +
"zero gravity regions.");
return true;
}
else {
p.sendMessage(ChatColor.RED + "Error; your first argument was not \'remove\'");
return false;
}
}
else if(args.length == 0) {
if(zeroArea.size() == 0) {
p.sendMessage(ChatColor.BLUE + "There are no zero-gravity regions currently made");
return true;
}
for(int i = 0; i < zeroArea.size(); i++) {
p.sendMessage(zeroArea.get(i).toString());
}
return true;
}
else {
return false;
}
}
else if(!p.hasPermission("ZeroSuit.zerog") && label.equalsIgnoreCase("zerog")) {
p.sendMessage(ChatColor.RED + "You do not have permission to perform this command.");
return true;
}
else if(p.hasPermission("ZeroSuit.zeroghelp") && label.equalsIgnoreCase("zeroghelp")) {
StringBuilder sb = new StringBuilder();
sb.append(ChatColor.LIGHT_PURPLE + "/zerog\n");
sb.append(ChatColor.AQUA + "This 0 argument command will list all areas that " +
"are zero-gravity regions\n");
sb.append(ChatColor.LIGHT_PURPLE + "/zerog <remove> <nameID>\n" +
ChatColor.AQUA + "This 2 argument command will remove a specified zero-gravity region\n");
sb.append(ChatColor.LIGHT_PURPLE + "/zerog <add> <x1> <y1> <z1> <x2> <y2> <z2> <nameID>\n" +
ChatColor.AQUA + "This 8 argument command will create a zero-gravity region in the " +
"world you're in (overworld | nether | end) at the given coordinates\n");
sb.append(ChatColor.BLUE + "/zerogfast\n" + ChatColor.AQUA +
"Sets your flyspeed to fast\n");
sb.append(ChatColor.BLUE + "/zerogslow\n" + ChatColor.AQUA +
"Sets your flyspeed to slow\n");
sb.append(ChatColor.GREEN + "/zeroghelp\n" + ChatColor.AQUA +
"Lists All ZeroSuit Commands");
p.sendMessage(sb.toString());
return true;
}
else if(!p.hasPermission("ZeroSuit.zeroghelp") && label.equalsIgnoreCase("zeroghelp")) {
p.sendMessage(ChatColor.RED + "Error; you do not have permission for this command.");
return true;
}
else if(label.equalsIgnoreCase("zerogfast")) {
p.setFlySpeed((float).2);
p.sendMessage(ChatColor.DARK_PURPLE + "Fly Speed Set To " + ChatColor.RED + "fast");
return true;
}
else if(label.equalsIgnoreCase("zerogslow")) {
p.setFlySpeed((float).1);
p.sendMessage(ChatColor.DARK_PURPLE + "Fly Speed Set To " + ChatColor.RED + "slow");
return true;
}
return false;
}
else
return false;
}
/**Will enable zerosuit if clicked*/
@EventHandler
public void zeroSuit(PlayerInteractEvent e) {
if(e.getAction() == Action.RIGHT_CLICK_BLOCK) {
if(e.getClickedBlock().getType() == Material.STONE_BUTTON ||
e.getClickedBlock().getType() == Material.WOOD_BUTTON) {
for(int i = 0; i < zeroArea.size(); i++) {
if(isInZeroG(e.getClickedBlock().getLocation(), zeroArea.get(i))) {
boolean isInList = false;
for(int ii = 0; ii < zs.size(); ii++) {
if(zs.get(ii).equals(e.getPlayer().getName()))
isInList = true;
}
if(!isInList)
zs.add(e.getPlayer());
e.getPlayer().setVelocity(new Vector(0, 1, 0));
e.getPlayer().setAllowFlight(true);
e.getPlayer().setFlying(true);
e.getPlayer().sendMessage(ChatColor.DARK_RED + "Now Entering " +
ChatColor.AQUA + "Zero-Gravity");
return;
}
}
}
}
}
///**Will let the player fly if they're in a zero-g area,
//* and will not let them fly if they aren't
//*/
/*@EventHandler
public void zeroGCheck(PlayerMoveEvent e) {
int zeroGIndex = -1;
for(int i = 0; i < zeroArea.size(); i++) {
boolean isInZeroG = this.isInZeroG(e.getPlayer().getLocation(), zeroArea.get(i));
if(isInZeroG)
zeroGIndex = i;
}
if(zeroGIndex != -1) {
if(!e.getPlayer().isFlying()) {
e.getPlayer().setAllowFlight(true);
e.getPlayer().setFlying(true);
boolean isInMsgCap = false;
for(int i = 0; i < msgCap.size(); i++) {
if(e.getPlayer().getName().equals(msgCap.get(i).getName()))
isInMsgCap = true;
}
if(!isInMsgCap) {
e.getPlayer().sendMessage(ChatColor.DARK_RED + "Now Entering " +
ChatColor.AQUA + "Zero-Gravity");
msgCap.add(e.getPlayer());
final Player p = e.getPlayer();
this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
public void run() {
msgCap.remove(p);
}
}, 10L);
}
}
}
else {
boolean hasFlyPerms = this.hasFlyPerms(e.getPlayer());
if(!hasFlyPerms) {
if(e.getPlayer().isFlying()) {
e.getPlayer().setAllowFlight(false);
e.getPlayer().setFlying(false);
}
}
else
e.getPlayer().setAllowFlight(true);
}
}*/
///**Will disable flying after a tp event*/
@EventHandler
public void noTpFly(PlayerTeleportEvent e) {
final Player p = e.getPlayer();
boolean gettoInZero = false;
for(int i = 0; i < zeroArea.size(); i++) {
if(!this.isInZeroG(e.getTo(), zeroArea.get(i))) {
gettoInZero = true;
}
}
if(!gettoInZero) {
if(!hasFlyPerms(e.getPlayer())) {
p.setFlying(false);
p.setAllowFlight(false);
}
}
}
/**This method checks whether a player is in a certain zeroArea region
* @return boolean, true if they're in the zeroArea region
*/
public boolean isInZeroG(Location loc, ZeroGArea zga) {
String world = "";
if(loc.getWorld().getEnvironment() == Environment.NORMAL)
world = "overworld";
else if(loc.getWorld().getEnvironment() == Environment.NETHER)
world = "nether";
else if(loc.getWorld().getEnvironment() == Environment.THE_END)
world = "end";
if(!world.equalsIgnoreCase(zga.getWorld())) {
return false;
}
boolean isInX, isInY, isInZ;
if(zga.x1 < zga.x2) {
isInX = loc.getX() < zga.x2 && loc.getX() > zga.x1 ? true : false;
}
else {
isInX = loc.getX() > zga.x2 && loc.getX() < zga.x1 ? true : false;
}
if(zga.y1 < zga.y2) {
isInY = loc.getY() < zga.y2 && loc.getY() > zga.y1 ? true : false;
}
else {
isInY = loc.getY() > zga.y2 && loc.getY() < zga.y1 ? true : false;
}
if(zga.z1 < zga.z2) {
isInZ = loc.getZ() < zga.z2 && loc.getZ() > zga.z1 ? true : false;
}
else {
isInZ = loc.getZ() > zga.z2 && loc.getZ() < zga.z1 ? true : false;
}
boolean isInsideZeroG = isInZ && isInY && isInX;
return isInsideZeroG;
}
/**This will initialize & read in data from the zerogarea .ser file*/
public void initializeZeroGAreaFile() {
File file = new File("ZeroSuitFiles\\ZeroGArea.ser");
if(!file.exists()) {
if(!new File("ZeroSuitFiles").exists())
new File("ZeroSuitFiles").mkdir();
}
else {
try{
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
zeroArea = (ArrayList)ois.readObject();
ois.close();
fis.close();
}catch(IOException e) { e.printStackTrace();
}catch(ClassNotFoundException e) { e.printStackTrace(); }
}
}
/**Updates the zerogarea file*/
public void updateZeroGAreaFile() {
File file = new File("ZeroSuitFiles\\ZeroGArea.ser");
if(!file.exists()) {
if(!new File("ZeroSuitFiles").exists())
new File("ZeroSuitFiles").mkdir();
}
else
file.delete();
try{
FileOutputStream fos = new FileOutputStream(new File("ZeroSuitFiles\\ZeroGArea.ser"));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(zeroArea);
oos.close();
fos.close();
}catch(IOException e) { e.printStackTrace(); }
}
/**Initializes & reads in the people who have permission*/
public void initializePermsFile() {
File file = new File("ZeroSuitFiles\\FlyPerms.ser");
if(file.exists())
file.delete();
if(!new File("ZeroSuitFiles").exists())
new File("ZeroSuitFiles").mkdir();
}
/**Checks whether a player has permission to fly
* @return boolean, true if the player has permission to fly
*/
public boolean hasFlyPerms(Player p) {
if(p.getGameMode() == GameMode.CREATIVE)
return true;
return false;
}
/*Checks whether a number is an int or not
* @return boolean, true if the number is an int
*/
public boolean isInt(String test) {
try{
Integer.parseInt(test);
return true;
}catch(NumberFormatException e) { return false; }
}
private class Update implements ActionListener {
public void actionPerformed(ActionEvent e) {
thisInstance.getServer().getScheduler().scheduleSyncDelayedTask(thisInstance, new Runnable() {
public void run() {
for(int i = 0; i < zs.size(); i++) {
if(!zs.get(i).isOnline()) {
zs.get(i).setFlying(false);
zs.get(i).setAllowFlight(false);
zs.remove(zs.get(i));
i--;
continue;
}
boolean isInZero = false;
for(int ii = 0; ii < zeroArea.size(); ii++) {
if(isInZeroG(zs.get(i).getLocation(), zeroArea.get(ii)))
isInZero = true;
}
if(!isInZero && !hasFlyPerms(zs.get(i))) {
zs.get(i).setAllowFlight(false);
zs.get(i).setFlying(false);
zs.remove(i);
i--;
}
else if(isInZero) {
zs.get(i).setAllowFlight(true);
zs.get(i).setFlying(true);
}
else if(hasFlyPerms(zs.get(i))) {
zs.get(i).setAllowFlight(true);
zs.remove(i);
i--;
}
}
}
}, 0L);
}
}
@EventHandler
public void noFlyLog(PlayerLoginEvent e) {
final Player p = e.getPlayer();
this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
public void run() {
boolean disable = !hasFlyPerms(p);
if(disable) {
p.setFlying(false);
p.setAllowFlight(false);
}
}
}, 5L);
}
}
| proper imports | src/main/java/com/crystalcraftmc/zerosuit/ZeroSuit.java | proper imports |
|
Java | apache-2.0 | 9e233a1736de4d6f6aed5a631ed89993885b15fb | 0 | dev9com/crash-dummy,dev9com/crash-dummy | package com.dev9.crash.info;
import java.security.CodeSource;
import java.security.ProtectionDomain;
public class ClassFileLocator {
public String find(String canonicalName) {
Class clazz = null;
if(canonicalName == null)
return "No class specified.";
try {
clazz = Class.forName(canonicalName);
} catch (ClassNotFoundException e) {
return "Can't find the class at all.";
}
ProtectionDomain pd = clazz.getProtectionDomain();
CodeSource cs = pd.getCodeSource();
if (cs == null)
return "<unknown, likely rt.jar / Core JDK>";
else
return cs.getLocation().toExternalForm();
}
}
| src/main/java/com/dev9/crash/info/ClassFileLocator.java | package com.dev9.crash.info;
import java.security.CodeSource;
import java.security.ProtectionDomain;
public class ClassFileLocator {
public String find(String canonicalName) {
Class clazz = null;
try {
clazz = Class.forName(canonicalName);
} catch (ClassNotFoundException e) {
return "Can't find the class at all.";
}
ProtectionDomain pd = clazz.getProtectionDomain();
CodeSource cs = pd.getCodeSource();
if (cs == null)
return "<unknown, likely rt.jar / Core JDK>";
else
return cs.getLocation().toExternalForm();
}
}
| Guard against null.
| src/main/java/com/dev9/crash/info/ClassFileLocator.java | Guard against null. |
|
Java | apache-2.0 | c0c43fc0be8c869493b11b0e3599c523265c5801 | 0 | MarioCodes/ProyectosClaseDAM,MarioCodes/Desarrollo_Proyectos_Clase | /*
* To change this license header, choose License Headers Window Project Properties.
* To change this template file, choose Tools | Templates
* and open the template Window the editor.
*/
package web;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.table.DefaultTableModel;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
/**
* todo: implementar la forma de cambios aleatorios, aunque sea un cambio radical siempre en la misma empresa.
* Proyecto de proceso de una pagina web.
* Clase Principal y unica.
* @author Mario Codes Sánchez
* @since 14/02/2017
*/
public class Window extends javax.swing.JFrame {
private static boolean escanear;
private static float porcentaje;
private static long espera; //ms de esperas entre escaneos en el programa.
private static DefaultTableModel model = new DefaultTableModel(); //Model donde cargare los datos e implementare.
private static Document document;
private static Elements tabla, headersWeb, datos;
private static String url;
private static String[] modelHeaders;
private static String[][] modelData, oldModelData;
/**
* Creates new form in
*/
public Window() {
initComponents();
this.setTitle("Informacion Relativa al Mercado.");
this.setResizable(false);
this.setLocationRelativeTo(null);
}
/**
* Limpieza de los headers para obtener solo texto y no codigo.
* @param element Element actual a tratar.
* @return String con el nombre de la cabecera limpio.
*/
private static String limpiezaHeaders(Element element) {
String header = element.toString();
header = header.substring(header.indexOf('>')+1);
header = header.substring(0, header.indexOf('<'));
return header;
}
/**
* Conversion de Elements a String[] que se puede usar directamente como headers en el JTable.mode() al instanciarlo.
* @param elements Elementos a tratar.
* @return String[] a utilizar directamente como header para table.model().
*/
private static String[] getHeaders(Elements elements) {
ArrayList<String> headersTmp = new ArrayList<>();
String[] headers;
for (int i = 0; i < elements.size()-1; i++) { //-1 para quitar lo de 'informacion relacionada'.
headersTmp.add(limpiezaHeaders(elements.get(i)));
}
headers = new String[headersTmp.size()];
for(int i = 0; i < headersTmp.size(); i++) {
headers[i] = headersTmp.get(i);
}
return headers;
}
/**
* Comprueba si queda alguna tag en al string que eliminar.
* @param string String a chequear.
* @return True si aun quedan tags por eliminar.
*/
private static boolean tagsLeft(String string) {
return string.contains("</") || string.contains(">");
}
/**
* Le quitamos una tag a la String pasada.
* @param string String sobre la que operar.
* @return String con una tag menos.
*/
private static String quitarTag(String string) {
try {
string = string.substring(string.indexOf('>')+1, string.lastIndexOf('<'));
}catch(StringIndexOutOfBoundsException ex) {
string = string.substring(string.indexOf('>')+1);
}
return string;
}
/**
* Conversion de un Nodo para obtener la String que nos interesa.
* @param node Nodo del cual extraemos la informacion.
* @return String con la informacion limpia.
*/
private static String convertNode(Node node) {
String nodo = node.toString();
while(tagsLeft(nodo)) {
nodo = quitarTag(nodo);
}
return nodo;
}
/**
* Quita una etiqueta HTML de la String que se le pasa.
* @param string String a la cual se quiere quitar una etiqueta.
* @return String sin esa etiqueta.
*/
private static String quitarLayerNormal(String string) {
string = string.substring(string.indexOf('>')+1, string.lastIndexOf('<'));
return string;
}
/**
* Quitado expreso de la etiqueta <img />. Hay algunos valores que no la contienen, por lo que es necesario buscarla expresamente.
* @param string String a chequear.
* @return String sin la etiqueta imagen si la contenia.
*/
private static String quitarLayerImg(String string) {
if(string.contains("<img")) {
string = string.substring(string.indexOf('>')+1, string.lastIndexOf('<'));
}
return string;
}
/**
* Chequea la String para comprobar si es un valor que sube o baja. Si se mantiene se marca como baja.
* @param string String a chequear.
* @return True si sube, false si no.
*/
private static boolean getTipo(String string) {
return string.contains("\"Sube\"");
}
/**
* Conversion de un element suelto a String[] para aniadirlo a la Tabla.
* Hago la conversion a mano. Son valores tan irregulares que no puedo automatizarlos.
* @param element Element a convertir.
* @return String[] convertida.
*/
private static String[] convertElement(Element element) {
String[] datos = new String[5];
try {
for(int i = 0; i < 2; i++){
datos[i] = convertNode(element.childNode(i));
}
datos[2] = convertNode(element.childNode(2).unwrap()) +"; " +convertNode(element.childNode(4)) +"h";
//No me gusta dejar esto asi pero hay demasiados cambios como para meterlos en metodos independientes, se deberia poder automatizar los recortes pero me da demasiados probremas. Ahora mismo esta manual para cada caso en concreto.
String s = quitarLayerNormal(element.childNode(5).toString());
s = quitarLayerNormal(s);
boolean sube = getTipo(s);
s = quitarLayerImg(s);
String cambioValor = s.substring(s.indexOf('>')+1, s.indexOf('>')+5);
String porcentaje = s.substring(s.lastIndexOf('>')+1).trim();
if(porcentaje.isEmpty()) porcentaje = "(0,00%)"; //Tengo problemas para capturar los 0% porque la pagina lo estructura de otra manera. Solo esta vacio cuando es 0%.
if(sube) datos[3] = "+" +cambioValor +"; " +porcentaje;
else datos[3] = "-" +cambioValor +"; " +porcentaje;
datos[4] = convertNode(element.childNode(6));
}catch(IndexOutOfBoundsException ex) {
System.out.println("ArrayIndex en convertElement(Element element) capturado: " +ex.getLocalizedMessage());
}
return datos;
}
/**
* Conversion de Elements a String[][] que usare directamente como Datos de JTable.mode().
* @param elements Elements con los datos raw.
* @return String[][] con los datos convertidos.
*/
private static String[][] getData(Elements elements) {
int size = elements.get(0).childNodeSize();
String[][] datos = new String[size][];
for(int i = 0; i < size; i++) {
datos[i] = convertElement(elements.get(0).child(i));
}
return datos;
}
/**
* Proceso de adecuacion y obtencion de datos de la web.
*/
private static void adecuacionDatos() {
modelHeaders = getHeaders(headersWeb);
if(oldModelData == null) { //Para la primera iteracion del programa.
modelData = getData(tabla);
oldModelData = modelData;
}
else {
oldModelData = modelData;
modelData = getData(tabla);
}
model = new DefaultTableModel(modelData, modelHeaders);
Window.jTable.setModel(model);
}
/**
* Get de los elementos necesarios para el parse.
*/
private static void iniElementos(String url) {
try {
document = Jsoup.connect(url).get(); //Selecciona el documento entero.
tabla = document.select("table tbody"); //De ese documento, pilla la tabla. Contiene los datos que nos interesan.
for(int i = 0; i < 4; i++) { //Eliminacion de paja que hay por enmedio, con esto lo dejo listo para tratar.
tabla.remove(tabla.get(0));
}
headersWeb = document.select("thead tr th");
datos = document.select("tr");
}catch(IOException ex) {
ex.printStackTrace();
}
}
/**
* Proceso entero de recoleccion y filtrado de los datos.
* @param url Url a la que nos conectamos.
*/
private static void tratamientoDatos(String url) {
Window.url = url;
iniElementos(url);
adecuacionDatos();
}
/**
* Obtencion del numero limite mediante el cual si se sobrepasa habra que dar aviso al usuario.
* @param porcentaje Porcentaje establecido por el usuario para dar aviso.
* @param valor Valor el cual chequeamos.
* @return Valor limite para avisar.
*/
private static long getLimite(long valor) {
return (long) (valor*Window.porcentaje/100);
}
/**
* Parse de numero estilo "###.###.###"
* Java no entiende que los .'s son para separar grupos de numero y se cree que son decimales. No encuentro nada que me solucione la vida, asi que lo creo yo.
* @param string String a parsear.
* @return Long correctamente formado.
*/
private static long parseLong(String string) {
String parse = "";
try {
while(string.contains(".")) {
parse += string.substring(0, string.indexOf('.'));
string = string.substring(string.indexOf('.')+1);
}
parse += string; //Para el ultimo resto y numeros sin punto.
}catch(NullPointerException ex) {
System.out.println("Problema con el parseo custom del Long. " +ex.getLocalizedMessage());
}
return Long.parseLong(parse);
}
/**
* Comprobacion de si un valor se pasa del limite establecido por el porcentaje indicado.
* @param cambio Cambio realizado entre el escaneo viejo y el actual.
* @param limite Limite del cual si se pasa hay que dar aviso.
* @return True si el cambio se pasa de, o iguala el limite.
*/
private static boolean checkLimite(long cambio, long limite) {
boolean isOver;
if(cambio >= 0) isOver = cambio > limite;
else {
limite -= limite*2;
isOver = cambio <= limite;
}
return isOver;
}
/**
* Comparacion de los valores anteriores con los nuevos escaneados. Si hay un cambio por arriba o abajo superior al porcentaje establecido, da aviso.
* El porcentaje lo tengo en cuenta a traves del valor Viejo.
* @param datosViejos Datos del escaneo anterior para tener una base sobre la cual comparar.
* @param datosNuevos Datos del escaneo nuevo.
*/
private static void comparacion(String[][] datosViejos, String[][] datosNuevos, int comienzoHilo, int limiteHilo) {
long valorNuevo, valorViejo, cambio, cambioLimite;
for (int indiceEmpresa = comienzoHilo; indiceEmpresa < limiteHilo; indiceEmpresa++) {
try {
valorNuevo = parseLong(datosNuevos[indiceEmpresa][4]);
valorViejo = parseLong(datosViejos[indiceEmpresa][4]);
cambioLimite = getLimite(valorNuevo);
cambio = valorNuevo-valorViejo;
boolean over = checkLimite(cambio, cambioLimite);
if(over) System.out.printf("%n¡ATENCION! ¡Cambio que ha sobrepasado el limite! Empresa %S. Valor anterior: %d. Limite de: %d. Cambio de: %d. Valor actual: %d", datosNuevos[indiceEmpresa][0], valorViejo, cambioLimite, cambio, valorNuevo);
}catch(ArrayIndexOutOfBoundsException ex) {
System.out.println("Capturado error de ArrayIndexOut en comparacion(). " +ex.getLocalizedMessage()); //Cosas raras que pasan al trabajar con hilos. Auqnue el limite esta establecido en < (NO <=!) se pasa igualmente y revienta.
}
}
// System.out.printf("Valor viejo: %d, Valor Nuevo: %d, Cambio: %d, CambioLimite: %d, Limite superado: %s\n" ,valorViejo, valorNuevo, cambio, cambioLimite, res); //Para testeo.
}
/**
* Calculo del limite de calculo de cada hilo, dividiendo la carga de trabajo en 4 hilos. Si hay 2 Arrays de diferente tamanio, se toma en cunta la de menor.
* Se divide equitativamente y el ultimo hilo se lleva el resto.
* @param datosViejos Escaneo de los datos viejos.
* @param datosNuevos Escaneo del ultimo juego de datos.
* @return int[numeroHilo][0] = limite inferior; [1] = limite superior;
*/
private static int[][] calculoLimitesHilo(String[][] datosViejos, String[][] datosNuevos) {
int numHilos = 4;
int[][] limites = new int[numHilos][2]; //[x][0] limite comienzo. [x][1] limite fin.
int limiteMinimo = datosViejos.length < datosNuevos.length ? datosViejos.length : datosNuevos.length;
int division = limiteMinimo/numHilos;
int maximo = division;
for (int i = 0; i < 3; i++) {
limites[i][0] = maximo-division;
limites[i][1] = maximo;
maximo += division;
// System.out.printf("%n#Hilos: %d. Limite total menor: %d. Limite del hilo #%d: %d(inferior), %d(superior)", numHilos, limiteMinimo, i+1, limites[i][0], limites[i][1]);
}
limites[3][0] = limites[2][1];
limites[3][1] = limiteMinimo;
// System.out.printf("%n#Hilos: %d. Limite total menor: %d. Limite del hilo #%d: %d(inferior), %d(superior)", numHilos, limiteMinimo, 4, limites[3][0], limites[3][1]);
return limites;
}
/**
* Ejecucion del escaneo en si mismo. Vuelve a obtener los datos de la pagina y compara los valores totales nuevos contra los anteriores.
* Divide la carga de trabajo en 4 hilos, aunque no hacia mucha falta ya que es poca cantidad de datos a tratar, algo de tiempo si que gana.
* @param url url sobre la que esta operando el programa.
*/
private static void escanear(String url) {
setEscanear(true);
while(isEscanear()) {
try {
tratamientoDatos(url);
System.out.printf("%nEscaneo realizado sobre %s buscando un %.2f%% de cambio.", url, porcentaje);
int[][] limites = calculoLimitesHilo(oldModelData, modelData);
new Thread(() -> comparacion(oldModelData, modelData, limites[0][0], limites[0][1])).start();
new Thread(() -> comparacion(oldModelData, modelData, limites[1][0], limites[1][1])).start();
new Thread(() -> comparacion(oldModelData, modelData, limites[2][0], limites[2][1])).start();
new Thread(() -> comparacion(oldModelData, modelData, limites[3][0], limites[3][1])).start();
Thread.sleep(espera);
} catch (InterruptedException ex) {
System.out.println("Problema con Thread.sleep en escanear(String url). " +ex.getLocalizedMessage());
}
}
System.out.printf("%nEscaneo anterior sobre %s parado.", url);
}
/**
* Cambio de la fuente de datos junto a la Label que informa al usuario.
* La diferencia con tratamientoDatos(String url) es que cuando se llama a este, tambien cambia el titulo del Panel de informacion.
* @param url URL de donde sacar los datos.
*/
private static void cambioDatos(String url) {
setEscanear(false);
tratamientoDatos(url);
switch(url) {
case "https://es.finance.yahoo.com/actives?e=mc":
Window.jPanelInformacion.setBorder(BorderFactory.createTitledBorder("Informacion: Valores mas Activos."));
break;
case "https://es.finance.yahoo.com/gainers?e=mc":
Window.jPanelInformacion.setBorder(BorderFactory.createTitledBorder("Informacion: Mayores Subidas de Precio."));
break;
case "https://es.finance.yahoo.com/losers?e=mc":
Window.jPanelInformacion.setBorder(BorderFactory.createTitledBorder("Informacion: Bajan de Precio."));
break;
default:
break;
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroupDatos = new javax.swing.ButtonGroup();
jPanelInformacion = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable = new javax.swing.JTable();
jPanelParametros = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jButtonEscaner = new javax.swing.JButton();
jSpinnerPorcentaje = new javax.swing.JSpinner();
jSpinnerTiempoMS = new javax.swing.JSpinner();
jMenuBar1 = new javax.swing.JMenuBar();
jMenuFile = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuValores = new javax.swing.JMenu();
jRadioButtonMenuItemActivos = new javax.swing.JRadioButtonMenuItem();
jRadioButtonMenuItemSubidas = new javax.swing.JRadioButtonMenuItem();
jRadioButtonMenuItemBajadas = new javax.swing.JRadioButtonMenuItem();
jMenuTesteo = new javax.swing.JMenu();
jCheckBoxMenuItemCambioAleatorio = new javax.swing.JCheckBoxMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanelInformacion.setBorder(javax.swing.BorderFactory.createTitledBorder("Informacion: Valores mas Activos."));
jTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
jTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jScrollPane1.setViewportView(jTable);
javax.swing.GroupLayout jPanelInformacionLayout = new javax.swing.GroupLayout(jPanelInformacion);
jPanelInformacion.setLayout(jPanelInformacionLayout);
jPanelInformacionLayout.setHorizontalGroup(
jPanelInformacionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelInformacionLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1)
.addContainerGap())
);
jPanelInformacionLayout.setVerticalGroup(
jPanelInformacionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelInformacionLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1)
.addGap(9, 9, 9))
);
jPanelParametros.setBorder(javax.swing.BorderFactory.createTitledBorder("Parametros"));
jLabel1.setText("Porcentaje de Aviso");
jLabel2.setText("Tiempo entre Escaneos (ms)");
jButtonEscaner.setText("Escanear");
jButtonEscaner.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonEscanerActionPerformed(evt);
}
});
jSpinnerPorcentaje.setModel(new javax.swing.SpinnerNumberModel(Float.valueOf(0.1f), Float.valueOf(0.01f), Float.valueOf(500.0f), Float.valueOf(0.05f)));
jSpinnerTiempoMS.setModel(new javax.swing.SpinnerNumberModel(Long.valueOf(5000L), Long.valueOf(1000L), Long.valueOf(60000L), Long.valueOf(1000L)));
javax.swing.GroupLayout jPanelParametrosLayout = new javax.swing.GroupLayout(jPanelParametros);
jPanelParametros.setLayout(jPanelParametrosLayout);
jPanelParametrosLayout.setHorizontalGroup(
jPanelParametrosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelParametrosLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jSpinnerPorcentaje, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(38, 38, 38)
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(jSpinnerTiempoMS, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
.addComponent(jButtonEscaner)
.addContainerGap())
);
jPanelParametrosLayout.setVerticalGroup(
jPanelParametrosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelParametrosLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelParametrosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jButtonEscaner)
.addComponent(jSpinnerPorcentaje, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jSpinnerTiempoMS, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jMenuFile.setText("File");
jMenuItem1.setText("Salir");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenuFile.add(jMenuItem1);
jMenuBar1.add(jMenuFile);
jMenuValores.setText("Valores");
buttonGroupDatos.add(jRadioButtonMenuItemActivos);
jRadioButtonMenuItemActivos.setSelected(true);
jRadioButtonMenuItemActivos.setText("Valores mas Activos");
jRadioButtonMenuItemActivos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonMenuItemActivosActionPerformed(evt);
}
});
jMenuValores.add(jRadioButtonMenuItemActivos);
buttonGroupDatos.add(jRadioButtonMenuItemSubidas);
jRadioButtonMenuItemSubidas.setText("Mayores Subidas de Precio");
jRadioButtonMenuItemSubidas.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonMenuItemSubidasActionPerformed(evt);
}
});
jMenuValores.add(jRadioButtonMenuItemSubidas);
buttonGroupDatos.add(jRadioButtonMenuItemBajadas);
jRadioButtonMenuItemBajadas.setText("Bajan de Precio");
jRadioButtonMenuItemBajadas.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonMenuItemBajadasActionPerformed(evt);
}
});
jMenuValores.add(jRadioButtonMenuItemBajadas);
jMenuBar1.add(jMenuValores);
jMenuTesteo.setText("Testing");
jCheckBoxMenuItemCambioAleatorio.setText("Cambio Aleatorio");
jMenuTesteo.add(jCheckBoxMenuItemCambioAleatorio);
jMenuBar1.add(jMenuTesteo);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanelInformacion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanelParametros, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanelParametros, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanelInformacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
System.exit(0);
}//GEN-LAST:event_jMenuItem1ActionPerformed
private void jRadioButtonMenuItemActivosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonMenuItemActivosActionPerformed
cambioDatos("https://es.finance.yahoo.com/actives?e=mc");
}//GEN-LAST:event_jRadioButtonMenuItemActivosActionPerformed
private void jRadioButtonMenuItemSubidasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonMenuItemSubidasActionPerformed
cambioDatos("https://es.finance.yahoo.com/gainers?e=mc");
}//GEN-LAST:event_jRadioButtonMenuItemSubidasActionPerformed
private void jRadioButtonMenuItemBajadasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonMenuItemBajadasActionPerformed
cambioDatos("https://es.finance.yahoo.com/losers?e=mc");
}//GEN-LAST:event_jRadioButtonMenuItemBajadasActionPerformed
private void jButtonEscanerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEscanerActionPerformed
Window.porcentaje = (float) Window.jSpinnerPorcentaje.getValue();
Window.espera = (long) Window.jSpinnerTiempoMS.getValue();
new Thread(() -> escanear(url)).start();
}//GEN-LAST:event_jButtonEscanerActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced Window Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Window().setVisible(true);
tratamientoDatos("https://es.finance.yahoo.com/actives?e=mc");
}
});
}
/**
* @return the escanear
*/
public static synchronized boolean isEscanear() {
return escanear;
}
/**
* @param aEscanear the escanear to set
*/
public static synchronized void setEscanear(boolean aEscanear) {
escanear = aEscanear;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroupDatos;
private javax.swing.JButton jButtonEscaner;
private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItemCambioAleatorio;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenu jMenuFile;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenu jMenuTesteo;
private javax.swing.JMenu jMenuValores;
private static javax.swing.JPanel jPanelInformacion;
private javax.swing.JPanel jPanelParametros;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItemActivos;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItemBajadas;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItemSubidas;
private javax.swing.JScrollPane jScrollPane1;
private static javax.swing.JSpinner jSpinnerPorcentaje;
private static javax.swing.JSpinner jSpinnerTiempoMS;
private static javax.swing.JTable jTable;
// End of variables declaration//GEN-END:variables
}
| Web/src/web/Window.java | /*
* To change this license header, choose License Headers Window Project Properties.
* To change this template file, choose Tools | Templates
* and open the template Window the editor.
*/
package web;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.table.DefaultTableModel;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
/**
* todo: implementar la forma de cambios aleatorios, aunque sea un cambio radical siempre en la misma empresa.
* Proyecto de proceso de una pagina web.
* Clase Principal y unica.
* @author Mario Codes Sánchez
* @since 14/02/2017
*/
public class Window extends javax.swing.JFrame {
private static boolean escanear;
private static float porcentaje;
private static long espera; //ms de esperas entre escaneos en el programa.
private static DefaultTableModel model = new DefaultTableModel(); //Model donde cargare los datos e implementare.
private static Document document;
private static Elements tabla, headersWeb, datos;
private static String url;
private static String[] modelHeaders;
private static String[][] modelData, oldModelData;
/**
* Creates new form in
*/
public Window() {
initComponents();
this.setTitle("Informacion Relativa al Mercado.");
this.setResizable(false);
this.setLocationRelativeTo(null);
}
/**
* Limpieza de los headers para obtener solo texto y no codigo.
* @param element Element actual a tratar.
* @return String con el nombre de la cabecera limpio.
*/
private static String limpiezaHeaders(Element element) {
String header = element.toString();
header = header.substring(header.indexOf('>')+1);
header = header.substring(0, header.indexOf('<'));
return header;
}
/**
* Conversion de Elements a String[] que se puede usar directamente como headers en el JTable.mode() al instanciarlo.
* @param elements Elementos a tratar.
* @return String[] a utilizar directamente como header para table.model().
*/
private static String[] getHeaders(Elements elements) {
ArrayList<String> headersTmp = new ArrayList<>();
String[] headers;
for (int i = 0; i < elements.size()-1; i++) { //-1 para quitar lo de 'informacion relacionada'.
headersTmp.add(limpiezaHeaders(elements.get(i)));
}
headers = new String[headersTmp.size()];
for(int i = 0; i < headersTmp.size(); i++) {
headers[i] = headersTmp.get(i);
}
return headers;
}
/**
* Comprueba si queda alguna tag en al string que eliminar.
* @param string String a chequear.
* @return True si aun quedan tags por eliminar.
*/
private static boolean tagsLeft(String string) {
return string.contains("</") || string.contains(">");
}
/**
* Le quitamos una tag a la String pasada.
* @param string String sobre la que operar.
* @return String con una tag menos.
*/
private static String quitarTag(String string) {
try {
string = string.substring(string.indexOf('>')+1, string.lastIndexOf('<'));
}catch(StringIndexOutOfBoundsException ex) {
string = string.substring(string.indexOf('>')+1);
}
return string;
}
/**
* Conversion de un Nodo para obtener la String que nos interesa.
* @param node Nodo del cual extraemos la informacion.
* @return String con la informacion limpia.
*/
private static String convertNode(Node node) {
String nodo = node.toString();
while(tagsLeft(nodo)) {
nodo = quitarTag(nodo);
}
return nodo;
}
/**
* Quita una etiqueta HTML de la String que se le pasa.
* @param string String a la cual se quiere quitar una etiqueta.
* @return String sin esa etiqueta.
*/
private static String quitarLayerNormal(String string) {
string = string.substring(string.indexOf('>')+1, string.lastIndexOf('<'));
return string;
}
/**
* Quitado expreso de la etiqueta <img />. Hay algunos valores que no la contienen, por lo que es necesario buscarla expresamente.
* @param string String a chequear.
* @return String sin la etiqueta imagen si la contenia.
*/
private static String quitarLayerImg(String string) {
if(string.contains("<img")) {
string = string.substring(string.indexOf('>')+1, string.lastIndexOf('<'));
}
return string;
}
/**
* Chequea la String para comprobar si es un valor que sube o baja. Si se mantiene se marca como baja.
* @param string String a chequear.
* @return True si sube, false si no.
*/
private static boolean getTipo(String string) {
return string.contains("\"Sube\"");
}
/**
* Conversion de un element suelto a String[] para aniadirlo a la Tabla.
* Hago la conversion a mano. Son valores tan irregulares que no puedo automatizarlos.
* @param element Element a convertir.
* @return String[] convertida.
*/
private static String[] convertElement(Element element) {
String[] datos = new String[5];
try {
for(int i = 0; i < 2; i++){
datos[i] = convertNode(element.childNode(i));
}
datos[2] = convertNode(element.childNode(2).unwrap()) +"; " +convertNode(element.childNode(4)) +"h";
//No me gusta dejar esto asi pero hay demasiados cambios como para meterlos en metodos independientes, se deberia poder automatizar los recortes pero me da demasiados probremas. Ahora mismo esta manual para cada caso en concreto.
String s = quitarLayerNormal(element.childNode(5).toString());
s = quitarLayerNormal(s);
boolean sube = getTipo(s);
s = quitarLayerImg(s);
String cambioValor = s.substring(s.indexOf('>')+1, s.indexOf('>')+5);
String porcentaje = s.substring(s.lastIndexOf('>')+1).trim();
if(porcentaje.isEmpty()) porcentaje = "(0,00%)"; //Tengo problemas para capturar los 0% porque la pagina lo estructura de otra manera. Solo esta vacio cuando es 0%.
if(sube) datos[3] = "+" +cambioValor +"; " +porcentaje;
else datos[3] = "-" +cambioValor +"; " +porcentaje;
datos[4] = convertNode(element.childNode(6));
}catch(IndexOutOfBoundsException ex) {
System.out.println("ArrayIndex en convertElement(Element element) capturado: " +ex.getLocalizedMessage());
}
return datos;
}
/**
* Conversion de Elements a String[][] que usare directamente como Datos de JTable.mode().
* @param elements Elements con los datos raw.
* @return String[][] con los datos convertidos.
*/
private static String[][] getData(Elements elements) {
int size = elements.get(0).childNodeSize();
String[][] datos = new String[size][];
for(int i = 0; i < size; i++) {
datos[i] = convertElement(elements.get(0).child(i));
}
return datos;
}
/**
* Proceso de adecuacion y obtencion de datos de la web.
*/
private static void adecuacionDatos() {
modelHeaders = getHeaders(headersWeb);
if(oldModelData == null) { //Para la primera iteracion del programa.
modelData = getData(tabla);
oldModelData = modelData;
}
else {
oldModelData = modelData;
modelData = getData(tabla);
}
model = new DefaultTableModel(modelData, modelHeaders);
Window.jTable.setModel(model);
}
/**
* Get de los elementos necesarios para el parse.
*/
private static void iniElementos(String url) {
try {
document = Jsoup.connect(url).get(); //Selecciona el documento entero.
tabla = document.select("table tbody"); //De ese documento, pilla la tabla. Contiene los datos que nos interesan.
for(int i = 0; i < 4; i++) { //Eliminacion de paja que hay por enmedio, con esto lo dejo listo para tratar.
tabla.remove(tabla.get(0));
}
headersWeb = document.select("thead tr th");
datos = document.select("tr");
}catch(IOException ex) {
ex.printStackTrace();
}
}
/**
* Proceso entero de recoleccion y filtrado de los datos.
* @param url Url a la que nos conectamos.
*/
private static void tratamientoDatos(String url) {
Window.url = url;
iniElementos(url);
adecuacionDatos();
}
/**
* Obtencion del numero limite mediante el cual si se sobrepasa habra que dar aviso al usuario.
* @param porcentaje Porcentaje establecido por el usuario para dar aviso.
* @param valor Valor el cual chequeamos.
* @return Valor limite para avisar.
*/
private static long getLimite(long valor) {
return (long) (valor*Window.porcentaje/100);
}
/**
* Parse de numero estilo "###.###.###"
* Java no entiende que los .'s son para separar grupos de numero y se cree que son decimales. No encuentro nada que me solucione la vida, asi que lo creo yo.
* @param string String a parsear.
* @return Long correctamente formado.
*/
private static long parseLong(String string) {
String parse = "";
try {
while(string.contains(".")) {
parse += string.substring(0, string.indexOf('.'));
string = string.substring(string.indexOf('.')+1);
}
parse += string; //Para el ultimo resto y numeros sin punto.
}catch(NullPointerException ex) {
System.out.println("Problema con el parseo custom del Long. " +ex.getLocalizedMessage());
}
return Long.parseLong(parse);
}
/**
* Comprobacion de si un valor se pasa del limite establecido por el porcentaje indicado.
* @param cambio Cambio realizado entre el escaneo viejo y el actual.
* @param limite Limite del cual si se pasa hay que dar aviso.
* @return True si el cambio se pasa de, o iguala el limite.
*/
private static boolean checkLimite(long cambio, long limite) {
boolean isOver;
if(cambio >= 0) isOver = cambio > limite;
else {
limite -= limite*2;
isOver = cambio <= limite;
}
return isOver;
}
/**
* Comparacion de los valores anteriores con los nuevos escaneados. Si hay un cambio por arriba o abajo superior al porcentaje establecido, da aviso.
* El porcentaje lo tengo en cuenta a traves del valor Viejo.
* @param datosViejos Datos del escaneo anterior para tener una base sobre la cual comparar.
* @param datosNuevos Datos del escaneo nuevo.
*/
private static void comparacion(String[][] datosViejos, String[][] datosNuevos, int comienzoHilo, int limiteHilo) {
long valorNuevo, valorViejo, cambio, cambioLimite;
for (int indiceEmpresa = comienzoHilo; indiceEmpresa < limiteHilo; indiceEmpresa++) {
try {
valorNuevo = parseLong(datosNuevos[indiceEmpresa][4]);
valorViejo = parseLong(datosViejos[indiceEmpresa][4]);
cambioLimite = getLimite(valorNuevo);
cambio = valorNuevo-valorViejo;
boolean over = checkLimite(cambio, cambioLimite);
if(over) System.out.printf("%n¡ATENCION! ¡Cambio que ha sobrepasado el limite! Empresa %S. Valor anterior: %d. Limite de: %d. Cambio de: %d. Valor actual: %d", datosNuevos[indiceEmpresa][0], valorViejo, cambioLimite, cambio, valorNuevo);
}catch(ArrayIndexOutOfBoundsException ex) {
System.out.println("Capturado error de ArrayIndexOut en comparacion(). " +ex.getLocalizedMessage()); //Cosas raras que pasan al trabajar con hilos. Auqnue el limite esta establecido en < (NO <=!) se pasa igualmente y revienta.
}
}
// System.out.printf("Valor viejo: %d, Valor Nuevo: %d, Cambio: %d, CambioLimite: %d, Limite superado: %s\n" ,valorViejo, valorNuevo, cambio, cambioLimite, res); //Para testeo.
}
private static int[][] getLimitesHilo(String[][] datosViejos, String[][] datosNuevos) {
int numHilos = 4;
int[][] limites = new int[numHilos][2]; //[x][0] limite comienzo. [x][1] limite fin.
int limiteMinimo = datosViejos.length < datosNuevos.length ? datosViejos.length : datosNuevos.length;
int division = limiteMinimo/numHilos;
int maximo = division;
for (int i = 0; i < 3; i++) {
limites[i][0] = maximo-division;
limites[i][1] = maximo;
maximo += division;
System.out.printf("%n#Hilos: %d. Limite total menor: %d. Limite del hilo #%d: %d(intefior), %d(superior)", numHilos, limiteMinimo, i, limites[i][0], limites[i][1]);
}
limites[3][0] = maximo-(division);
limites[3][1] = maximo;
System.out.printf("%n#Hilos: %d. Limite total menor: %d. Limite del hilo #%d: %d(intefior), %d(superior)", numHilos, limiteMinimo, 3, limites[3][0], limites[3][1]);
return limites;
}
/**
* Ejecucion del escaneo en si mismo. Vuelve a obtener los datos de la pagina y compara los valores totales nuevos contra los anteriores.
* Divide la carga de trabajo en 4 hilos, aunque no hacia mucha falta ya que es poca cantidad de datos a tratar, algo de tiempo si que gana.
* @param url url sobre la que esta operando el programa.
*/
private static void escanear(String url) {
setEscanear(true);
while(isEscanear()) {
try {
tratamientoDatos(url);
System.out.printf("%nEscaneo realizado sobre %s buscando un %.2f%% de cambio.", url, porcentaje);
getLimitesHilo(oldModelData, modelData);
new Thread(() -> comparacion(oldModelData, modelData, 0, 25)).start(); //fixme: cambiar la forma de repartir la carga de trabajo para que sea mas dinamico.
new Thread(() -> comparacion(oldModelData, modelData, 25, 50)).start();
new Thread(() -> comparacion(oldModelData, modelData, 50, 75)).start();
new Thread(() -> comparacion(oldModelData, modelData, 75, 100)).start();
Thread.sleep(espera);
} catch (InterruptedException ex) {
System.out.println("Problema con Thread.sleep en escanear(String url). " +ex.getLocalizedMessage());
}
}
System.out.printf("%nEscaneo anterior sobre %s parado.", url);
}
/**
* Cambio de la fuente de datos junto a la Label que informa al usuario.
* La diferencia con tratamientoDatos(String url) es que cuando se llama a este, tambien cambia el titulo del Panel de informacion.
* @param url URL de donde sacar los datos.
*/
private static void cambioDatos(String url) {
setEscanear(false);
tratamientoDatos(url);
switch(url) {
case "https://es.finance.yahoo.com/actives?e=mc":
Window.jPanelInformacion.setBorder(BorderFactory.createTitledBorder("Informacion: Valores mas Activos."));
break;
case "https://es.finance.yahoo.com/gainers?e=mc":
Window.jPanelInformacion.setBorder(BorderFactory.createTitledBorder("Informacion: Mayores Subidas de Precio."));
break;
case "https://es.finance.yahoo.com/losers?e=mc":
Window.jPanelInformacion.setBorder(BorderFactory.createTitledBorder("Informacion: Bajan de Precio."));
break;
default:
break;
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroupDatos = new javax.swing.ButtonGroup();
jPanelInformacion = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable = new javax.swing.JTable();
jPanelParametros = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jButtonEscaner = new javax.swing.JButton();
jSpinnerPorcentaje = new javax.swing.JSpinner();
jSpinnerTiempoMS = new javax.swing.JSpinner();
jMenuBar1 = new javax.swing.JMenuBar();
jMenuFile = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuValores = new javax.swing.JMenu();
jRadioButtonMenuItemActivos = new javax.swing.JRadioButtonMenuItem();
jRadioButtonMenuItemSubidas = new javax.swing.JRadioButtonMenuItem();
jRadioButtonMenuItemBajadas = new javax.swing.JRadioButtonMenuItem();
jMenuTesteo = new javax.swing.JMenu();
jCheckBoxMenuItemCambioAleatorio = new javax.swing.JCheckBoxMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanelInformacion.setBorder(javax.swing.BorderFactory.createTitledBorder("Informacion: Valores mas Activos."));
jTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
jTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jScrollPane1.setViewportView(jTable);
javax.swing.GroupLayout jPanelInformacionLayout = new javax.swing.GroupLayout(jPanelInformacion);
jPanelInformacion.setLayout(jPanelInformacionLayout);
jPanelInformacionLayout.setHorizontalGroup(
jPanelInformacionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelInformacionLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1)
.addContainerGap())
);
jPanelInformacionLayout.setVerticalGroup(
jPanelInformacionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelInformacionLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1)
.addGap(9, 9, 9))
);
jPanelParametros.setBorder(javax.swing.BorderFactory.createTitledBorder("Parametros"));
jLabel1.setText("Porcentaje de Aviso");
jLabel2.setText("Tiempo entre Escaneos (ms)");
jButtonEscaner.setText("Escanear");
jButtonEscaner.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonEscanerActionPerformed(evt);
}
});
jSpinnerPorcentaje.setModel(new javax.swing.SpinnerNumberModel(Float.valueOf(0.1f), Float.valueOf(0.01f), Float.valueOf(500.0f), Float.valueOf(0.05f)));
jSpinnerTiempoMS.setModel(new javax.swing.SpinnerNumberModel(Long.valueOf(5000L), Long.valueOf(1000L), Long.valueOf(60000L), Long.valueOf(1000L)));
javax.swing.GroupLayout jPanelParametrosLayout = new javax.swing.GroupLayout(jPanelParametros);
jPanelParametros.setLayout(jPanelParametrosLayout);
jPanelParametrosLayout.setHorizontalGroup(
jPanelParametrosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelParametrosLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jSpinnerPorcentaje, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(38, 38, 38)
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(jSpinnerTiempoMS, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
.addComponent(jButtonEscaner)
.addContainerGap())
);
jPanelParametrosLayout.setVerticalGroup(
jPanelParametrosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelParametrosLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelParametrosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jButtonEscaner)
.addComponent(jSpinnerPorcentaje, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jSpinnerTiempoMS, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jMenuFile.setText("File");
jMenuItem1.setText("Salir");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenuFile.add(jMenuItem1);
jMenuBar1.add(jMenuFile);
jMenuValores.setText("Valores");
buttonGroupDatos.add(jRadioButtonMenuItemActivos);
jRadioButtonMenuItemActivos.setSelected(true);
jRadioButtonMenuItemActivos.setText("Valores mas Activos");
jRadioButtonMenuItemActivos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonMenuItemActivosActionPerformed(evt);
}
});
jMenuValores.add(jRadioButtonMenuItemActivos);
buttonGroupDatos.add(jRadioButtonMenuItemSubidas);
jRadioButtonMenuItemSubidas.setText("Mayores Subidas de Precio");
jRadioButtonMenuItemSubidas.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonMenuItemSubidasActionPerformed(evt);
}
});
jMenuValores.add(jRadioButtonMenuItemSubidas);
buttonGroupDatos.add(jRadioButtonMenuItemBajadas);
jRadioButtonMenuItemBajadas.setText("Bajan de Precio");
jRadioButtonMenuItemBajadas.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonMenuItemBajadasActionPerformed(evt);
}
});
jMenuValores.add(jRadioButtonMenuItemBajadas);
jMenuBar1.add(jMenuValores);
jMenuTesteo.setText("Testing");
jCheckBoxMenuItemCambioAleatorio.setText("Cambio Aleatorio");
jMenuTesteo.add(jCheckBoxMenuItemCambioAleatorio);
jMenuBar1.add(jMenuTesteo);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanelInformacion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanelParametros, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanelParametros, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanelInformacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
System.exit(0);
}//GEN-LAST:event_jMenuItem1ActionPerformed
private void jRadioButtonMenuItemActivosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonMenuItemActivosActionPerformed
cambioDatos("https://es.finance.yahoo.com/actives?e=mc");
}//GEN-LAST:event_jRadioButtonMenuItemActivosActionPerformed
private void jRadioButtonMenuItemSubidasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonMenuItemSubidasActionPerformed
cambioDatos("https://es.finance.yahoo.com/gainers?e=mc");
}//GEN-LAST:event_jRadioButtonMenuItemSubidasActionPerformed
private void jRadioButtonMenuItemBajadasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonMenuItemBajadasActionPerformed
cambioDatos("https://es.finance.yahoo.com/losers?e=mc");
}//GEN-LAST:event_jRadioButtonMenuItemBajadasActionPerformed
private void jButtonEscanerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEscanerActionPerformed
Window.porcentaje = (float) Window.jSpinnerPorcentaje.getValue();
Window.espera = (long) Window.jSpinnerTiempoMS.getValue();
new Thread(() -> escanear(url)).start();
}//GEN-LAST:event_jButtonEscanerActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced Window Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Window().setVisible(true);
tratamientoDatos("https://es.finance.yahoo.com/actives?e=mc");
}
});
}
/**
* @return the escanear
*/
public static synchronized boolean isEscanear() {
return escanear;
}
/**
* @param aEscanear the escanear to set
*/
public static synchronized void setEscanear(boolean aEscanear) {
escanear = aEscanear;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroupDatos;
private javax.swing.JButton jButtonEscaner;
private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItemCambioAleatorio;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenu jMenuFile;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenu jMenuTesteo;
private javax.swing.JMenu jMenuValores;
private static javax.swing.JPanel jPanelInformacion;
private javax.swing.JPanel jPanelParametros;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItemActivos;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItemBajadas;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItemSubidas;
private javax.swing.JScrollPane jScrollPane1;
private static javax.swing.JSpinner jSpinnerPorcentaje;
private static javax.swing.JSpinner jSpinnerTiempoMS;
private static javax.swing.JTable jTable;
// End of variables declaration//GEN-END:variables
}
| Limites de los hilos testeados, el ultimo hilo se lleva el resto de carga de trabajo. Falta meter la forma de testeo automatico.
| Web/src/web/Window.java | Limites de los hilos testeados, el ultimo hilo se lleva el resto de carga de trabajo. Falta meter la forma de testeo automatico. |
|
Java | apache-2.0 | 003d2818c4b06349cce1c8770781b31edd1dfdfc | 0 | mariusj/org.openntf.domino,OpenNTF/org.openntf.domino,rPraml/org.openntf.domino,mariusj/org.openntf.domino,OpenNTF/org.openntf.domino,rPraml/org.openntf.domino,mariusj/org.openntf.domino,OpenNTF/org.openntf.domino,rPraml/org.openntf.domino,rPraml/org.openntf.domino | package org.openntf.domino.xsp.helpers;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.faces.application.Application;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import org.openntf.domino.AutoMime;
import org.openntf.domino.ext.Session.Fixes;
import org.openntf.domino.utils.DominoUtils;
import org.openntf.domino.utils.Factory;
import org.openntf.domino.xsp.Activator;
import org.openntf.domino.xsp.XspOpenLogErrorHolder;
import com.ibm.xsp.application.ApplicationEx;
import com.ibm.xsp.context.FacesContextEx;
import com.ibm.xsp.el.ImplicitObjectFactory;
import com.ibm.xsp.util.TypedUtil;
//import org.openntf.domino.Session;
/**
* Factory for managing the plugin
*/
@SuppressWarnings("unchecked")
public class OpenntfDominoImplicitObjectFactory2 implements ImplicitObjectFactory {
// NTF The reason the Factory2 version exists is because we were testing moving the "global" settings like
// godmode and marcel to the xsp.properties and making them per-Application rather than server-wide.
private static Boolean GODMODE;
/**
* Gets the application map, allowing us to track Xsp Properties enabled per application
*
* @param ctx
* @return Map<String, Object>
* @since org.openntf.domino.xsp 4.5.0
*/
private static Map<String, Object> getAppMap(final FacesContext ctx) {
if (ctx == null)
return new HashMap<String, Object>();
ExternalContext ec = ctx.getExternalContext();
if (ec == null)
return new HashMap<String, Object>();
Map<String, Object> result = ec.getApplicationMap();
return result;
}
/**
* Gets the serverScope map (ServerBean instance)
*
* @param ctx
* FacesContext
* @return Map<String, Object> serverScope
* @since org.openntf.domino.xsp 4.5.0
*/
private static Map<String, Object> getServerMap(final FacesContext ctx) {
return ServerBean.getCurrentInstance();
}
/**
* Whether godMode is enabled in Xsp Properties
*
* @return boolean godMode
* @since org.openntf.domino.xsp 2.5.0
*/
private static boolean isGodMode() {
if (GODMODE == null) {
GODMODE = Boolean.FALSE;
String[] envs = Activator.getEnvironmentStrings();
if (envs != null) {
for (String s : envs) {
if (s.equalsIgnoreCase("godmode")) {
GODMODE = Boolean.TRUE;
}
}
}
}
return GODMODE.booleanValue();
}
/**
* common code to test if a flag is set in the Xsp properties
*
* @param ctx
* @param flagName
* use upperCase for flagName, e.g. RAID
* @return
*/
private static boolean isAppFlagSet(final FacesContext ctx, final String flagName) {
// Map<String, Object> appMap = ctx.getExternalContext().getApplicationMap();
Object current = getAppMap(ctx).get(OpenntfDominoImplicitObjectFactory2.class.getName() + "_" + flagName);
if (current == null) {
current = Boolean.FALSE;
String[] envs = Activator.getXspProperty(Activator.PLUGIN_ID);
if (envs != null) {
for (String s : envs) {
if (s.equalsIgnoreCase(flagName)) {
current = Boolean.TRUE;
}
}
}
getAppMap(ctx).put(OpenntfDominoImplicitObjectFactory2.class.getName() + "_" + flagName, current);
}
return (Boolean) current;
}
/**
* Gets whether the godMode flag is enabled for the application
*
* @param ctx
* FacesContext
* @return boolean
* @since org.openntf.domino.xsp 2.5.0
*/
public static boolean isAppGodMode(final FacesContext ctx) {
return isAppFlagSet(ctx, "GODMODE");
}
/**
* Whether the application is currently under surveillance by {@link NSA}
*
* @param ctx
* FacesContext
* @return boolean
* @since org.openntf.domino.xsp 4.5.0
*/
public static boolean isAppUnderSurveillance(final FacesContext ctx) {
// Map<String, Object> appMap = ctx.getExternalContext().getApplicationMap();
Object current = getAppMap(ctx).get(OpenntfDominoImplicitObjectFactory2.class.getName() + "_NSA");
if (current == null) {
current = Boolean.FALSE;
String[] envs = Activator.getXspProperty(Activator.PLUGIN_ID);
if (envs != null) {
for (String s : envs) {
if (s.equalsIgnoreCase("nsa")) {
current = Boolean.TRUE;
Application app = ctx.getApplication();
if (app instanceof ApplicationEx) {
NSA.INSTANCE.registerApplication((ApplicationEx) app);
NSA.INSTANCE.registerSession((ApplicationEx) app, (HttpSession) ctx.getExternalContext().getSession(true));
}
}
}
} else {
// System.out.println("XSP ENV IS NULL!!");
}
getAppMap(ctx).put(OpenntfDominoImplicitObjectFactory2.class.getName() + "_NSA", current);
} else {
// System.out.println("Current found: " + String.valueOf(current));
}
return (Boolean) current;
}
/**
* Gets the AutoMime option enabled for the application, an instance of the enum {@link AutoMime}
*
* @param ctx
* FacesContext
* @return AutoMime
* @since org.openntf.domino.xsp 5.0.0
*/
private static AutoMime getAppAutoMime(final FacesContext ctx) {
// Map<String, Object> appMap = ctx.getExternalContext().getApplicationMap();
Object current = getAppMap(ctx).get(OpenntfDominoImplicitObjectFactory2.class.getName() + "_AUTOMIME");
if (current == null) {
current = AutoMime.WRAP_ALL;
String[] envs = Activator.getXspProperty(Activator.PLUGIN_ID);
if (envs != null) {
for (String s : envs) {
if (s.equalsIgnoreCase("automime32k")) {
current = AutoMime.WRAP_32K;
}
if (s.equalsIgnoreCase("automimenone")) {
current = AutoMime.WRAP_NONE;
}
}
}
getAppMap(ctx).put(OpenntfDominoImplicitObjectFactory2.class.getName() + "_AUTOMIME", current);
}
return (AutoMime) current;
}
/**
* Gets whether the marcel flag is enabled for the application
*
* @param ctx
* FacesContext
* @return boolean
* @since org.openntf.domino.xsp 3.0.0
*/
private static boolean isAppMimeFriendly(final FacesContext ctx) {
return isAppFlagSet(ctx, "MARCEL");
}
/**
* Gets whether the khan flag is enabled for the application
*
* @param ctx
* FacesContext
* @return boolean
* @since org.openntf.domino.xsp 3.0.0
*/
private static boolean isAppAllFix(final FacesContext ctx) {
return isAppFlagSet(ctx, "KHAN");
}
/**
* Ggets whether the raid flag is enabled for the application
*
* @param ctx
* FacesContext
* @return boolean
* @since org.openntf.domino.xsp 3.0.0
*/
private static boolean isAppDebug(final FacesContext ctx) {
return isAppFlagSet(ctx, "RAID");
}
/**
* List of implicit objects (global variables accessible via VariableResolver)
*
* @since org.openntf.domino.xsp 2.5.0
*/
private final String[][] implicitObjectList = {
{ (isGodMode() ? "session" : "opensession"), org.openntf.domino.Session.class.getName() },
{ (isGodMode() ? "database" : "opendatabase"), org.openntf.domino.Database.class.getName() },
{ (Activator.isAPIEnabled() ? "openLogBean" : "openNtfLogBean"), org.openntf.domino.xsp.XspOpenLogErrorHolder.class.getName() } };
/**
* Constructor
*/
public OpenntfDominoImplicitObjectFactory2() {
// System.out.println("Created implicit object factory 2");
}
/**
* Gets the current Session
*
* @param ctx
* FacesContext
* @return Session
* @since org.openntf.domino 3.0.0
*/
private org.openntf.domino.Session createSession(final FacesContextEx ctx) {
org.openntf.domino.Session session = null;
isAppUnderSurveillance(ctx);
String sessionKey = isAppGodMode(ctx) ? "session" : "opensession";
Map<String, Object> localMap = TypedUtil.getRequestMap(ctx.getExternalContext());
lotus.domino.Session rawSession = (lotus.domino.Session) localMap.get("session");
if (rawSession == null) {
rawSession = (lotus.domino.Session) ctx.getApplication().getVariableResolver().resolveVariable(ctx, "session");
}
if (rawSession != null) {
session = Factory.fromLotus(rawSession, org.openntf.domino.Session.SCHEMA, null);
// Factory.setNoRecycle(session, true);
session.setAutoMime(getAppAutoMime(ctx));
if (isAppMimeFriendly(ctx))
session.setConvertMIME(false);
if (isAppAllFix(ctx)) {
for (Fixes fix : Fixes.values()) {
session.setFixEnable(fix, true);
}
}
if (isAppFlagSet(ctx, "BUBBLEEXCEPTIONS")) {
DominoUtils.setBubbleExceptions(true);
}
localMap.put(sessionKey, session);
} else {
System.out.println("Unable to locate 'session' through request map or variable resolver. Unable to auto-wrap.");
}
return session;
}
/**
* Gets the current database
*
* @param ctx
* FacesContext
* @param session
* Session
* @return Database current database
* @since org.openntf.domino.xsp 3.0.0
*/
private org.openntf.domino.Database createDatabase(final FacesContextEx ctx, final org.openntf.domino.Session session) {
org.openntf.domino.Database database = null;
String dbKey = isAppGodMode(ctx) ? "database" : "opendatabase";
Map<String, Object> localMap = TypedUtil.getRequestMap(ctx.getExternalContext());
lotus.domino.Database rawDatabase = (lotus.domino.Database) localMap.get("database");
if (rawDatabase == null) {
rawDatabase = (lotus.domino.Database) ctx.getApplication().getVariableResolver().resolveVariable(ctx, "database");
}
if (rawDatabase != null) {
database = Factory.fromLotus(rawDatabase, org.openntf.domino.Database.SCHEMA, session);
Factory.setNoRecycle(database, true);
localMap.put(dbKey, database);
} else {
System.out.println("Unable to locate 'database' through request map or variable resolver. Unable to auto-wrap.");
}
return database;
}
/**
* Loads the userScope for the current user for the current Application
*
* @param ctx
* FacesContext
* @param session
* Session
* @return Map<String, Object> corresponding to userScope global variable
* @since org.openntf.domino.xsp 4.5.0
*/
private Map<String, Object> createUserScope(final FacesContextEx ctx, final org.openntf.domino.Session session) {
String key = session.getEffectiveUserName();
Map<String, Object> userscope = null;
Object chk = getAppMap(ctx).get(key);
if (chk == null) {
userscope = new ConcurrentHashMap<String, Object>();
getAppMap(ctx).put(key, userscope);
} else {
userscope = (Map<String, Object>) chk;
}
Map<String, Object> localMap = TypedUtil.getRequestMap(ctx.getExternalContext());
localMap.put("userScope", userscope);
return userscope;
}
/**
* Loads the identityScope for the current user for the whole server
*
* @param ctx
* FacesContext
* @param session
* Session
* @return Map<String, Object> corresponding to identityScope global variable
* @since org.openntf.domino.xsp 4.5.0
*/
private Map<String, Object> createIdentityScope(final FacesContextEx ctx, final org.openntf.domino.Session session) {
String key = session.getEffectiveUserName();
Map<String, Object> userscope = null;
Object chk = getServerMap(ctx).get(key);
if (chk == null) {
userscope = new ConcurrentHashMap<String, Object>();
getServerMap(ctx).put(key, userscope);
} else {
userscope = (Map<String, Object>) chk;
}
Map<String, Object> localMap = TypedUtil.getRequestMap(ctx.getExternalContext());
localMap.put("identityScope", userscope);
return userscope;
}
/**
* Loads the serverScope for the server
*
* @param ctx
* FacesContext
* @param session
* Session
* @return Map<String, Object> corresponding to serverScope global variable
* @since org.openntf.domino.xsp 4.5.0
*/
private Map<String, Object> createServerScope(final FacesContextEx ctx, final org.openntf.domino.Session session) {
Map<String, Object> server = getServerMap(ctx);
Map<String, Object> localMap = TypedUtil.getRequestMap(ctx.getExternalContext());
localMap.put("serverScope", server);
return server;
}
/**
* Loads the openLogBean for the application to sessionScope
*
* @param ctx
* FacesContext
* @since org.openntf.domino.xsp 4.5.0
*/
public void createLogHolder(final FacesContextEx ctx) {
if (isAppDebug(ctx)) {
System.out.println("Beginning creation of log holder...");
}
if (Activator.isAPIEnabled()) {
Map<String, Object> localMap = TypedUtil.getSessionMap(ctx.getExternalContext());
XspOpenLogErrorHolder ol_ = new XspOpenLogErrorHolder();
localMap.put("openLogBean", ol_);
if (isAppDebug(ctx)) {
System.out.println("Created log holder...");
}
}
}
/*
* (non-Javadoc)
*
* @see com.ibm.xsp.el.ImplicitObjectFactory#createImplicitObjects(com.ibm.xsp.context.FacesContextEx)
*/
@Override
public void createImplicitObjects(final FacesContextEx ctx) {
if (isAppDebug(ctx)) {
System.out.println("Beginning creation of implicit objects...");
}
// TODO RPr: I enabled the "setClassLoader" here
Factory.setClassLoader(ctx.getContextClassLoader());
Factory.setServiceLocator(new Factory.AppServiceLocator() {
final ApplicationEx app = ctx.getApplicationEx();
Map<Class<?>, List<?>> cache = new HashMap<Class<?>, List<?>>();
public <T> List<T> findApplicationServices(final Class<T> serviceClazz) {
List<T> ret = (List<T>) cache.get(serviceClazz);
if (ret == null) {
ret = (List<T>) AccessController.doPrivileged(new PrivilegedAction<List<T>>() {
public List<T> run() {
return app.findServices(serviceClazz.getName());
}
});
if (Comparable.class.isAssignableFrom(serviceClazz)) {
Collections.sort((List<? extends Comparable>) ret);
}
cache.put(serviceClazz, ret);
}
return ret;
}
});
org.openntf.domino.Session session = createSession(ctx);
@SuppressWarnings("unused")
org.openntf.domino.Database database = createDatabase(ctx, session);
createUserScope(ctx, session);
createIdentityScope(ctx, session);
createServerScope(ctx, session);
createLogHolder(ctx);
if (isAppDebug(ctx)) {
System.out.println("Done creating implicit objects.");
}
}
/*
* (non-Javadoc)
*
* @see com.ibm.xsp.el.ImplicitObjectFactory#getDynamicImplicitObject(com.ibm.xsp.context.FacesContextEx, java.lang.String)
*/
@Override
public Object getDynamicImplicitObject(final FacesContextEx paramFacesContextEx, final String paramString) {
// TODO Auto-generated method stub
return null;
}
/*
* (non-Javadoc)
*
* @see com.ibm.xsp.el.ImplicitObjectFactory#destroyImplicitObjects(javax.faces.context.FacesContext)
*/
@Override
public void destroyImplicitObjects(final FacesContext paramFacesContext) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see com.ibm.xsp.el.ImplicitObjectFactory#getImplicitObjectList()
*/
@Override
public String[][] getImplicitObjectList() {
return this.implicitObjectList;
}
}
| org.openntf.domino.xsp/src/org/openntf/domino/xsp/helpers/OpenntfDominoImplicitObjectFactory2.java | package org.openntf.domino.xsp.helpers;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.faces.application.Application;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import org.openntf.domino.AutoMime;
import org.openntf.domino.ext.Session.Fixes;
import org.openntf.domino.utils.Factory;
import org.openntf.domino.xsp.Activator;
import org.openntf.domino.xsp.XspOpenLogErrorHolder;
import com.ibm.xsp.application.ApplicationEx;
import com.ibm.xsp.context.FacesContextEx;
import com.ibm.xsp.el.ImplicitObjectFactory;
import com.ibm.xsp.util.TypedUtil;
//import org.openntf.domino.Session;
/**
* Factory for managing the plugin
*/
@SuppressWarnings("unchecked")
public class OpenntfDominoImplicitObjectFactory2 implements ImplicitObjectFactory {
// NTF The reason the Factory2 version exists is because we were testing moving the "global" settings like
// godmode and marcel to the xsp.properties and making them per-Application rather than server-wide.
private static Boolean GODMODE;
/**
* Gets the application map, allowing us to track Xsp Properties enabled per application
*
* @param ctx
* @return Map<String, Object>
* @since org.openntf.domino.xsp 4.5.0
*/
private static Map<String, Object> getAppMap(final FacesContext ctx) {
if (ctx == null)
return new HashMap<String, Object>();
ExternalContext ec = ctx.getExternalContext();
if (ec == null)
return new HashMap<String, Object>();
Map<String, Object> result = ec.getApplicationMap();
return result;
}
/**
* Gets the serverScope map (ServerBean instance)
*
* @param ctx
* FacesContext
* @return Map<String, Object> serverScope
* @since org.openntf.domino.xsp 4.5.0
*/
private static Map<String, Object> getServerMap(final FacesContext ctx) {
return ServerBean.getCurrentInstance();
}
/**
* Whether godMode is enabled in Xsp Properties
*
* @return boolean godMode
* @since org.openntf.domino.xsp 2.5.0
*/
private static boolean isGodMode() {
if (GODMODE == null) {
GODMODE = Boolean.FALSE;
String[] envs = Activator.getEnvironmentStrings();
if (envs != null) {
for (String s : envs) {
if (s.equalsIgnoreCase("godmode")) {
GODMODE = Boolean.TRUE;
}
}
}
}
return GODMODE.booleanValue();
}
/**
* Gets whether the godMode flag is enabled for the application
*
* @param ctx
* FacesContext
* @return boolean
* @since org.openntf.domino.xsp 2.5.0
*/
public static boolean isAppGodMode(final FacesContext ctx) {
// Map<String, Object> appMap = ctx.getExternalContext().getApplicationMap();
Object current = getAppMap(ctx).get(OpenntfDominoImplicitObjectFactory2.class.getName() + "_GODMODE");
if (current == null) {
// System.out.println("Current not found. Creating...");
current = Boolean.FALSE;
String[] envs = Activator.getXspProperty(Activator.PLUGIN_ID);
if (envs != null) {
// if (envs.length == 0) {
// System.out.println("Got an empty string array!");
// }
for (String s : envs) {
// System.out.println("Xsp check: " + s);
if (s.equalsIgnoreCase("godmode")) {
current = Boolean.TRUE;
}
}
} else {
// System.out.println("XSP ENV IS NULL!!");
}
getAppMap(ctx).put(OpenntfDominoImplicitObjectFactory2.class.getName() + "_GODMODE", current);
} else {
// System.out.println("Current found: " + String.valueOf(current));
}
return (Boolean) current;
}
/**
* Whether the application is currently under surveillance by {@link NSA}
*
* @param ctx
* FacesContext
* @return boolean
* @since org.openntf.domino.xsp 4.5.0
*/
public static boolean isAppUnderSurveillance(final FacesContext ctx) {
// Map<String, Object> appMap = ctx.getExternalContext().getApplicationMap();
Object current = getAppMap(ctx).get(OpenntfDominoImplicitObjectFactory2.class.getName() + "_NSA");
if (current == null) {
current = Boolean.FALSE;
String[] envs = Activator.getXspProperty(Activator.PLUGIN_ID);
if (envs != null) {
for (String s : envs) {
if (s.equalsIgnoreCase("nsa")) {
current = Boolean.TRUE;
Application app = ctx.getApplication();
if (app instanceof ApplicationEx) {
NSA.INSTANCE.registerApplication((ApplicationEx) app);
NSA.INSTANCE.registerSession((ApplicationEx) app, (HttpSession) ctx.getExternalContext().getSession(true));
}
}
}
} else {
// System.out.println("XSP ENV IS NULL!!");
}
getAppMap(ctx).put(OpenntfDominoImplicitObjectFactory2.class.getName() + "_NSA", current);
} else {
// System.out.println("Current found: " + String.valueOf(current));
}
return (Boolean) current;
}
/**
* Gets the AutoMime option enabled for the application, an instance of the enum {@link AutoMime}
*
* @param ctx
* FacesContext
* @return AutoMime
* @since org.openntf.domino.xsp 5.0.0
*/
private static AutoMime getAppAutoMime(final FacesContext ctx) {
// Map<String, Object> appMap = ctx.getExternalContext().getApplicationMap();
Object current = getAppMap(ctx).get(OpenntfDominoImplicitObjectFactory2.class.getName() + "_AUTOMIME");
if (current == null) {
current = AutoMime.WRAP_ALL;
String[] envs = Activator.getXspProperty(Activator.PLUGIN_ID);
if (envs != null) {
for (String s : envs) {
if (s.equalsIgnoreCase("automime32k")) {
current = AutoMime.WRAP_32K;
}
if (s.equalsIgnoreCase("automimenone")) {
current = AutoMime.WRAP_NONE;
}
}
}
getAppMap(ctx).put(OpenntfDominoImplicitObjectFactory2.class.getName() + "_AUTOMIME", current);
}
return (AutoMime) current;
}
/**
* Gets whether the marcel flag is enabled for the application
*
* @param ctx
* FacesContext
* @return boolean
* @since org.openntf.domino.xsp 3.0.0
*/
private static boolean isAppMimeFriendly(final FacesContext ctx) {
// Map<String, Object> appMap = ctx.getExternalContext().getApplicationMap();
Object current = getAppMap(ctx).get(OpenntfDominoImplicitObjectFactory2.class.getName() + "_MARCEL");
if (current == null) {
current = Boolean.FALSE;
String[] envs = Activator.getXspProperty(Activator.PLUGIN_ID);
if (envs != null) {
for (String s : envs) {
if (s.equalsIgnoreCase("marcel")) {
current = Boolean.TRUE;
}
}
}
getAppMap(ctx).put(OpenntfDominoImplicitObjectFactory2.class.getName() + "_MARCEL", current);
}
return (Boolean) current;
}
/**
* Gets whether the khan flag is enabled for the application
*
* @param ctx
* FacesContext
* @return boolean
* @since org.openntf.domino.xsp 3.0.0
*/
private static boolean isAppAllFix(final FacesContext ctx) {
// Map<String, Object> appMap = ctx.getExternalContext().getApplicationMap();
Object current = getAppMap(ctx).get(OpenntfDominoImplicitObjectFactory2.class.getName() + "_KHAN");
if (current == null) {
current = Boolean.FALSE;
String[] envs = Activator.getXspProperty(Activator.PLUGIN_ID);
if (envs != null) {
for (String s : envs) {
if (s.equalsIgnoreCase("khan")) {
current = Boolean.TRUE;
}
}
}
getAppMap(ctx).put(OpenntfDominoImplicitObjectFactory2.class.getName() + "_KHAN", current);
}
return (Boolean) current;
}
/**
* Ggets whether the raid flag is enabled for the application
*
* @param ctx
* FacesContext
* @return boolean
* @since org.openntf.domino.xsp 3.0.0
*/
private static boolean isAppDebug(final FacesContext ctx) {
// Map<String, Object> appMap = ctx.getExternalContext().getApplicationMap();
Object current = getAppMap(ctx).get(OpenntfDominoImplicitObjectFactory2.class.getName() + "_RAID");
if (current == null) {
current = Boolean.FALSE;
String[] envs = Activator.getXspProperty(Activator.PLUGIN_ID);
if (envs != null) {
for (String s : envs) {
if (s.equalsIgnoreCase("raid")) {
current = Boolean.TRUE;
}
}
}
getAppMap(ctx).put(OpenntfDominoImplicitObjectFactory2.class.getName() + "_RAID", current);
}
return (Boolean) current;
}
/**
* List of implicit objects (global variables accessible via VariableResolver)
*
* @since org.openntf.domino.xsp 2.5.0
*/
private final String[][] implicitObjectList = {
{ (isGodMode() ? "session" : "opensession"), org.openntf.domino.Session.class.getName() },
{ (isGodMode() ? "database" : "opendatabase"), org.openntf.domino.Database.class.getName() },
{ (Activator.isAPIEnabled() ? "openLogBean" : "openNtfLogBean"), org.openntf.domino.xsp.XspOpenLogErrorHolder.class.getName() } };
/**
* Constructor
*/
public OpenntfDominoImplicitObjectFactory2() {
// System.out.println("Created implicit object factory 2");
}
/**
* Gets the current Session
*
* @param ctx
* FacesContext
* @return Session
* @since org.openntf.domino 3.0.0
*/
private org.openntf.domino.Session createSession(final FacesContextEx ctx) {
org.openntf.domino.Session session = null;
isAppUnderSurveillance(ctx);
String sessionKey = isAppGodMode(ctx) ? "session" : "opensession";
Map<String, Object> localMap = TypedUtil.getRequestMap(ctx.getExternalContext());
lotus.domino.Session rawSession = (lotus.domino.Session) localMap.get("session");
if (rawSession == null) {
rawSession = (lotus.domino.Session) ctx.getApplication().getVariableResolver().resolveVariable(ctx, "session");
}
if (rawSession != null) {
session = Factory.fromLotus(rawSession, org.openntf.domino.Session.SCHEMA, null);
// Factory.setNoRecycle(session, true);
session.setAutoMime(getAppAutoMime(ctx));
if (isAppMimeFriendly(ctx))
session.setConvertMIME(false);
if (isAppAllFix(ctx)) {
for (Fixes fix : Fixes.values()) {
session.setFixEnable(fix, true);
}
}
localMap.put(sessionKey, session);
} else {
System.out.println("Unable to locate 'session' through request map or variable resolver. Unable to auto-wrap.");
}
return session;
}
/**
* Gets the current database
*
* @param ctx
* FacesContext
* @param session
* Session
* @return Database current database
* @since org.openntf.domino.xsp 3.0.0
*/
private org.openntf.domino.Database createDatabase(final FacesContextEx ctx, final org.openntf.domino.Session session) {
org.openntf.domino.Database database = null;
String dbKey = isAppGodMode(ctx) ? "database" : "opendatabase";
Map<String, Object> localMap = TypedUtil.getRequestMap(ctx.getExternalContext());
lotus.domino.Database rawDatabase = (lotus.domino.Database) localMap.get("database");
if (rawDatabase == null) {
rawDatabase = (lotus.domino.Database) ctx.getApplication().getVariableResolver().resolveVariable(ctx, "database");
}
if (rawDatabase != null) {
database = Factory.fromLotus(rawDatabase, org.openntf.domino.Database.SCHEMA, session);
Factory.setNoRecycle(database, true);
localMap.put(dbKey, database);
} else {
System.out.println("Unable to locate 'database' through request map or variable resolver. Unable to auto-wrap.");
}
return database;
}
/**
* Loads the userScope for the current user for the current Application
*
* @param ctx
* FacesContext
* @param session
* Session
* @return Map<String, Object> corresponding to userScope global variable
* @since org.openntf.domino.xsp 4.5.0
*/
private Map<String, Object> createUserScope(final FacesContextEx ctx, final org.openntf.domino.Session session) {
String key = session.getEffectiveUserName();
Map<String, Object> userscope = null;
Object chk = getAppMap(ctx).get(key);
if (chk == null) {
userscope = new ConcurrentHashMap<String, Object>();
getAppMap(ctx).put(key, userscope);
} else {
userscope = (Map<String, Object>) chk;
}
Map<String, Object> localMap = TypedUtil.getRequestMap(ctx.getExternalContext());
localMap.put("userScope", userscope);
return userscope;
}
/**
* Loads the identityScope for the current user for the whole server
*
* @param ctx
* FacesContext
* @param session
* Session
* @return Map<String, Object> corresponding to identityScope global variable
* @since org.openntf.domino.xsp 4.5.0
*/
private Map<String, Object> createIdentityScope(final FacesContextEx ctx, final org.openntf.domino.Session session) {
String key = session.getEffectiveUserName();
Map<String, Object> userscope = null;
Object chk = getServerMap(ctx).get(key);
if (chk == null) {
userscope = new ConcurrentHashMap<String, Object>();
getServerMap(ctx).put(key, userscope);
} else {
userscope = (Map<String, Object>) chk;
}
Map<String, Object> localMap = TypedUtil.getRequestMap(ctx.getExternalContext());
localMap.put("identityScope", userscope);
return userscope;
}
/**
* Loads the serverScope for the server
*
* @param ctx
* FacesContext
* @param session
* Session
* @return Map<String, Object> corresponding to serverScope global variable
* @since org.openntf.domino.xsp 4.5.0
*/
private Map<String, Object> createServerScope(final FacesContextEx ctx, final org.openntf.domino.Session session) {
Map<String, Object> server = getServerMap(ctx);
Map<String, Object> localMap = TypedUtil.getRequestMap(ctx.getExternalContext());
localMap.put("serverScope", server);
return server;
}
/**
* Loads the openLogBean for the application to sessionScope
*
* @param ctx
* FacesContext
* @since org.openntf.domino.xsp 4.5.0
*/
public void createLogHolder(final FacesContextEx ctx) {
if (isAppDebug(ctx)) {
System.out.println("Beginning creation of log holder...");
}
if (Activator.isAPIEnabled()) {
Map<String, Object> localMap = TypedUtil.getSessionMap(ctx.getExternalContext());
XspOpenLogErrorHolder ol_ = new XspOpenLogErrorHolder();
localMap.put("openLogBean", ol_);
if (isAppDebug(ctx)) {
System.out.println("Created log holder...");
}
}
}
/*
* (non-Javadoc)
*
* @see com.ibm.xsp.el.ImplicitObjectFactory#createImplicitObjects(com.ibm.xsp.context.FacesContextEx)
*/
@Override
public void createImplicitObjects(final FacesContextEx ctx) {
if (isAppDebug(ctx)) {
System.out.println("Beginning creation of implicit objects...");
}
// Factory.setClassLoader(ctx.getContextClassLoader());
// ctx.addRequestListener(new ContextListener());
org.openntf.domino.Session session = createSession(ctx);
@SuppressWarnings("unused")
org.openntf.domino.Database database = createDatabase(ctx, session);
createUserScope(ctx, session);
createIdentityScope(ctx, session);
createServerScope(ctx, session);
createLogHolder(ctx);
if (isAppDebug(ctx)) {
System.out.println("Done creating implicit objects.");
}
}
/*
* (non-Javadoc)
*
* @see com.ibm.xsp.el.ImplicitObjectFactory#getDynamicImplicitObject(com.ibm.xsp.context.FacesContextEx, java.lang.String)
*/
@Override
public Object getDynamicImplicitObject(final FacesContextEx paramFacesContextEx, final String paramString) {
// TODO Auto-generated method stub
return null;
}
/*
* (non-Javadoc)
*
* @see com.ibm.xsp.el.ImplicitObjectFactory#destroyImplicitObjects(javax.faces.context.FacesContext)
*/
@Override
public void destroyImplicitObjects(final FacesContext paramFacesContext) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see com.ibm.xsp.el.ImplicitObjectFactory#getImplicitObjectList()
*/
@Override
public String[][] getImplicitObjectList() {
return this.implicitObjectList;
}
}
| removed redundant code from OpenntfDominoImplicitObjectFactory2.java
| org.openntf.domino.xsp/src/org/openntf/domino/xsp/helpers/OpenntfDominoImplicitObjectFactory2.java | removed redundant code from OpenntfDominoImplicitObjectFactory2.java |
|
Java | apache-2.0 | b6b858eba0838d98aae1a4d4a6a99fc04bafbfff | 0 | gstevey/gradle,lsmaira/gradle,robinverduijn/gradle,lsmaira/gradle,gstevey/gradle,lsmaira/gradle,robinverduijn/gradle,blindpirate/gradle,blindpirate/gradle,lsmaira/gradle,blindpirate/gradle,blindpirate/gradle,lsmaira/gradle,lsmaira/gradle,gstevey/gradle,lsmaira/gradle,robinverduijn/gradle,blindpirate/gradle,gradle/gradle,robinverduijn/gradle,blindpirate/gradle,gstevey/gradle,robinverduijn/gradle,gradle/gradle,gradle/gradle,gradle/gradle,gradle/gradle,robinverduijn/gradle,gradle/gradle,gstevey/gradle,gstevey/gradle,robinverduijn/gradle,gradle/gradle,gstevey/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,lsmaira/gradle,blindpirate/gradle,gradle/gradle,lsmaira/gradle,robinverduijn/gradle,gstevey/gradle,blindpirate/gradle,lsmaira/gradle,robinverduijn/gradle,gstevey/gradle,robinverduijn/gradle,blindpirate/gradle,robinverduijn/gradle | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.composite.internal;
import org.gradle.api.artifacts.component.ProjectComponentIdentifier;
import org.gradle.api.internal.artifacts.ivyservice.projectmodule.LocalComponentRegistry;
import org.gradle.api.internal.artifacts.ivyservice.projectmodule.ProjectArtifactBuilder;
import org.gradle.initialization.BuildIdentity;
import org.gradle.initialization.IncludedBuildExecuter;
import org.gradle.initialization.IncludedBuildTaskGraph;
import org.gradle.internal.component.local.model.LocalComponentArtifactMetadata;
import org.gradle.internal.service.ServiceRegistry;
import java.io.File;
/**
* Resolves and builds IDE metadata artifacts from other projects within the same build.
*
* When building IDE metadata artifacts for an included build, the regular (jar) artifacts for that build are not
* created. To ensure this, a separate {@link IncludedBuildArtifactBuilder} instance is used for building.
* (The session-scoped {@link IncludedBuildArtifactBuilder} instance is primed to create all included build artifacts in a single execution.)
*/
public class CompositeBuildIdeProjectResolver {
private final LocalComponentRegistry registry;
private final ProjectArtifactBuilder artifactBuilder;
public static CompositeBuildIdeProjectResolver from(ServiceRegistry services) {
return new CompositeBuildIdeProjectResolver(services.get(LocalComponentRegistry.class), services.get(IncludedBuildExecuter.class), services.get(BuildIdentity.class));
}
public CompositeBuildIdeProjectResolver(LocalComponentRegistry registry, IncludedBuildExecuter executer, BuildIdentity buildIdentity) {
this.registry = registry;
// Can't use the session-scope `IncludedBuildTaskGraph`, because we don't want to be execute jar tasks (which are pre-registered)
// This should be addressed in gradle/composite-builds#104
IncludedBuildTaskGraph taskGraph = new DefaultIncludedBuildTaskGraph(executer);
artifactBuilder = new CompositeProjectArtifactBuilder(new IncludedBuildArtifactBuilder(taskGraph), buildIdentity);
}
/**
* Finds an IDE metadata artifact with the specified type. Does not execute tasks to build the artifact.
*
* IDE metadata artifacts are registered by IDE plugins via {@link org.gradle.api.internal.artifacts.ivyservice.projectmodule.ProjectLocalComponentProvider#registerAdditionalArtifact(org.gradle.api.artifacts.component.ProjectComponentIdentifier, org.gradle.internal.component.local.model.LocalComponentArtifactMetadata)}
*/
public LocalComponentArtifactMetadata findArtifact(ProjectComponentIdentifier project, String type) {
for (LocalComponentArtifactMetadata artifactMetaData : registry.getAdditionalArtifacts(project)) {
if (artifactMetaData.getName().getType().equals(type)) {
return artifactMetaData;
}
}
return null;
}
/**
* Finds an IDE metadata artifact with the specified type, and executes tasks to build the artifact file.
*/
public File buildArtifactFile(ProjectComponentIdentifier project, String type) {
LocalComponentArtifactMetadata artifactMetaData = findArtifact(project, type);
if (artifactMetaData == null) {
return null;
}
artifactBuilder.build(artifactMetaData);
return artifactMetaData.getFile();
}
}
| subprojects/composite-builds/src/main/java/org/gradle/composite/internal/CompositeBuildIdeProjectResolver.java | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.composite.internal;
import org.gradle.api.artifacts.component.ProjectComponentIdentifier;
import org.gradle.api.internal.artifacts.ivyservice.projectmodule.LocalComponentRegistry;
import org.gradle.api.internal.artifacts.ivyservice.projectmodule.ProjectArtifactBuilder;
import org.gradle.initialization.BuildIdentity;
import org.gradle.initialization.IncludedBuildExecuter;
import org.gradle.initialization.IncludedBuildTaskGraph;
import org.gradle.internal.component.local.model.LocalComponentArtifactMetadata;
import org.gradle.internal.service.ServiceRegistry;
import java.io.File;
/**
* Resolves and builds IDE metadata artifacts from other projects within the same build.
*
* When building IDE metadata artifacts for an included build, the regular (jar) artifacts for that build are not
* created. To ensure this, a separate {@link IncludedBuildArtifactBuilder} instance is used for building.
* (The session-scoped {@link IncludedBuildArtifactBuilder} instance is primed to create all included build artifacts in a single execution.)
*/
public class CompositeBuildIdeProjectResolver {
private final LocalComponentRegistry registry;
private final ProjectArtifactBuilder artifactBuilder;
public static CompositeBuildIdeProjectResolver from(ServiceRegistry services) {
return new CompositeBuildIdeProjectResolver(services.get(LocalComponentRegistry.class), services.get(IncludedBuildExecuter.class), services.get(BuildIdentity.class));
}
public CompositeBuildIdeProjectResolver(LocalComponentRegistry registry, IncludedBuildExecuter executer, BuildIdentity buildIdentity) {
this.registry = registry;
// Can't use the session-scope `IncludedBuildTaskGraph`, because we don't want to be execute jar tasks (which are pre-registered)
IncludedBuildTaskGraph taskGraph = new DefaultIncludedBuildTaskGraph(executer);
artifactBuilder = new CompositeProjectArtifactBuilder(new IncludedBuildArtifactBuilder(taskGraph), buildIdentity);
}
/**
* Finds an IDE metadata artifact with the specified type. Does not execute tasks to build the artifact.
*
* IDE metadata artifacts are registered by IDE plugins via {@link org.gradle.api.internal.artifacts.ivyservice.projectmodule.ProjectLocalComponentProvider#registerAdditionalArtifact(org.gradle.api.artifacts.component.ProjectComponentIdentifier, org.gradle.internal.component.local.model.LocalComponentArtifactMetadata)}
*/
public LocalComponentArtifactMetadata findArtifact(ProjectComponentIdentifier project, String type) {
for (LocalComponentArtifactMetadata artifactMetaData : registry.getAdditionalArtifacts(project)) {
if (artifactMetaData.getName().getType().equals(type)) {
return artifactMetaData;
}
}
return null;
}
/**
* Finds an IDE metadata artifact with the specified type, and executes tasks to build the artifact file.
*/
public File buildArtifactFile(ProjectComponentIdentifier project, String type) {
LocalComponentArtifactMetadata artifactMetaData = findArtifact(project, type);
if (artifactMetaData == null) {
return null;
}
artifactBuilder.build(artifactMetaData);
return artifactMetaData.getFile();
}
}
| Add explanatory comment
| subprojects/composite-builds/src/main/java/org/gradle/composite/internal/CompositeBuildIdeProjectResolver.java | Add explanatory comment |
|
Java | apache-2.0 | ce1cb9880b8dbeaf93f769b2dec938a795cc1b3c | 0 | monetate/closure-compiler,vobruba-martin/closure-compiler,Yannic/closure-compiler,mprobst/closure-compiler,tdelmas/closure-compiler,nawawi/closure-compiler,google/closure-compiler,tiobe/closure-compiler,google/closure-compiler,mprobst/closure-compiler,tiobe/closure-compiler,ChadKillingsworth/closure-compiler,Yannic/closure-compiler,ChadKillingsworth/closure-compiler,monetate/closure-compiler,Yannic/closure-compiler,nawawi/closure-compiler,google/closure-compiler,shantanusharma/closure-compiler,tdelmas/closure-compiler,monetate/closure-compiler,tiobe/closure-compiler,tdelmas/closure-compiler,vobruba-martin/closure-compiler,vobruba-martin/closure-compiler,ChadKillingsworth/closure-compiler,nawawi/closure-compiler,mprobst/closure-compiler,shantanusharma/closure-compiler,ChadKillingsworth/closure-compiler,google/closure-compiler,shantanusharma/closure-compiler,shantanusharma/closure-compiler,mprobst/closure-compiler,tiobe/closure-compiler,vobruba-martin/closure-compiler,Yannic/closure-compiler,monetate/closure-compiler,nawawi/closure-compiler,tdelmas/closure-compiler | /*
* Copyright 2009 The Closure Compiler 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.javascript.jscomp;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.javascript.jscomp.PassFactory.createEmptyPass;
import static com.google.javascript.jscomp.parsing.parser.FeatureSet.ES5;
import static com.google.javascript.jscomp.parsing.parser.FeatureSet.ES6;
import static com.google.javascript.jscomp.parsing.parser.FeatureSet.ES7;
import static com.google.javascript.jscomp.parsing.parser.FeatureSet.ES8;
import static com.google.javascript.jscomp.parsing.parser.FeatureSet.ES8_MODULES;
import static com.google.javascript.jscomp.parsing.parser.FeatureSet.TYPESCRIPT;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage;
import com.google.javascript.jscomp.AbstractCompiler.MostRecentTypechecker;
import com.google.javascript.jscomp.CompilerOptions.ExtractPrototypeMemberDeclarationsMode;
import com.google.javascript.jscomp.CoverageInstrumentationPass.CoverageReach;
import com.google.javascript.jscomp.CoverageInstrumentationPass.InstrumentOption;
import com.google.javascript.jscomp.ExtractPrototypeMemberDeclarations.Pattern;
import com.google.javascript.jscomp.NodeTraversal.Callback;
import com.google.javascript.jscomp.PassFactory.HotSwapPassFactory;
import com.google.javascript.jscomp.lint.CheckArrayWithGoogObject;
import com.google.javascript.jscomp.lint.CheckDuplicateCase;
import com.google.javascript.jscomp.lint.CheckEmptyStatements;
import com.google.javascript.jscomp.lint.CheckEnums;
import com.google.javascript.jscomp.lint.CheckInterfaces;
import com.google.javascript.jscomp.lint.CheckJSDocStyle;
import com.google.javascript.jscomp.lint.CheckMissingSemicolon;
import com.google.javascript.jscomp.lint.CheckNullableReturn;
import com.google.javascript.jscomp.lint.CheckPrimitiveAsObject;
import com.google.javascript.jscomp.lint.CheckPrototypeProperties;
import com.google.javascript.jscomp.lint.CheckRequiresAndProvidesSorted;
import com.google.javascript.jscomp.lint.CheckUnusedLabels;
import com.google.javascript.jscomp.lint.CheckUselessBlocks;
import com.google.javascript.jscomp.parsing.ParserRunner;
import com.google.javascript.jscomp.parsing.parser.FeatureSet;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.Node;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Pass factories and meta-data for native JSCompiler passes.
*
* @author [email protected] (Nick Santos)
*
* NOTE(dimvar): this needs some non-trivial refactoring. The pass config should
* use as little state as possible. The recommended way for a pass to leave
* behind some state for a subsequent pass is through the compiler object.
* Any other state remaining here should only be used when the pass config is
* creating the list of checks and optimizations, not after passes have started
* executing. For example, the field namespaceForChecks should be in Compiler.
*/
public final class DefaultPassConfig extends PassConfig {
/* For the --mark-as-compiled pass */
private static final String COMPILED_CONSTANT_NAME = "COMPILED";
/* Constant name for Closure's locale */
private static final String CLOSURE_LOCALE_CONSTANT_NAME = "goog.LOCALE";
static final DiagnosticType CANNOT_USE_PROTOTYPE_AND_VAR =
DiagnosticType.error("JSC_CANNOT_USE_PROTOTYPE_AND_VAR",
"Rename prototypes and inline variables cannot be used together.");
// Miscellaneous errors.
private static final java.util.regex.Pattern GLOBAL_SYMBOL_NAMESPACE_PATTERN =
java.util.regex.Pattern.compile("^[a-zA-Z0-9$_]+$");
/**
* A global namespace to share across checking passes.
*/
private GlobalNamespace namespaceForChecks = null;
/**
* A symbol table for registering references that get removed during
* preprocessing.
*/
private PreprocessorSymbolTable preprocessorSymbolTable = null;
/**
* Global state necessary for doing hotswap recompilation of files with references to
* processed goog.modules.
*/
private ClosureRewriteModule.GlobalRewriteState moduleRewriteState = null;
/**
* Whether to protect "hidden" side-effects.
* @see CheckSideEffects
*/
private final boolean protectHiddenSideEffects;
public DefaultPassConfig(CompilerOptions options) {
super(options);
// The current approach to protecting "hidden" side-effects is to
// wrap them in a function call that is stripped later, this shouldn't
// be done in IDE mode where AST changes may be unexpected.
protectHiddenSideEffects = options != null && options.shouldProtectHiddenSideEffects();
}
GlobalNamespace getGlobalNamespace() {
return namespaceForChecks;
}
PreprocessorSymbolTable getPreprocessorSymbolTable() {
return preprocessorSymbolTable;
}
void maybeInitializePreprocessorSymbolTable(AbstractCompiler compiler) {
if (options.preservesDetailedSourceInfo()) {
Node root = compiler.getRoot();
if (preprocessorSymbolTable == null || preprocessorSymbolTable.getRootNode() != root) {
preprocessorSymbolTable = new PreprocessorSymbolTable(root);
}
}
}
void maybeInitializeModuleRewriteState() {
if (options.allowsHotswapReplaceScript() && this.moduleRewriteState == null) {
this.moduleRewriteState = new ClosureRewriteModule.GlobalRewriteState();
}
}
@Override
protected List<PassFactory> getTranspileOnlyPasses() {
List<PassFactory> passes = new ArrayList<>();
if (options.needsTranspilationFrom(TYPESCRIPT)) {
passes.add(convertEs6TypedToEs6);
}
if (options.needsTranspilationOf(FeatureSet.Feature.MODULES)) {
TranspilationPasses.addEs6ModulePass(passes);
}
passes.add(checkMissingSuper);
passes.add(checkVariableReferencesForTranspileOnly);
// It's important that the Dart super accessors pass run *before* es6ConvertSuper,
// which is a "late" ES6 pass. This is enforced in the assertValidOrder method.
if (options.dartPass && options.needsTranspilationFrom(ES6)) {
passes.add(dartSuperAccessorsPass);
}
if (options.needsTranspilationFrom(ES8)) {
TranspilationPasses.addEs2017Passes(passes);
passes.add(setFeatureSet(ES7));
}
if (options.needsTranspilationFrom(ES7)) {
TranspilationPasses.addEs2016Passes(passes);
passes.add(setFeatureSet(ES6));
}
// If the user has specified an input language of ES7 and an output language of ES6 or lower,
// we still need to run these "ES6" passes, because they do the transpilation of the ES7 **
// operator. If we split that into its own pass then the needsTranspilationFrom(ES7) call here
// can be removed.
if (options.needsTranspilationFrom(ES6) || options.needsTranspilationFrom(ES7)) {
TranspilationPasses.addEs6EarlyPasses(passes);
TranspilationPasses.addEs6LatePasses(passes);
TranspilationPasses.addPostCheckPasses(passes);
if (options.rewritePolyfills) {
TranspilationPasses.addRewritePolyfillPass(passes);
}
passes.add(setFeatureSet(options.getLanguageOut().toFeatureSet()));
}
if (!options.forceLibraryInjection.isEmpty()) {
passes.add(injectRuntimeLibraries);
}
assertAllOneTimePasses(passes);
assertValidOrderForChecks(passes);
return passes;
}
@Override
protected List<PassFactory> getWhitespaceOnlyPasses() {
List<PassFactory> passes = new ArrayList<>();
if (options.wrapGoogModulesForWhitespaceOnly) {
passes.add(whitespaceWrapGoogModules);
}
return passes;
}
private void addNewTypeCheckerPasses(List<PassFactory> checks, CompilerOptions options) {
if (options.getNewTypeInference()) {
checks.add(symbolTableForNewTypeInference);
checks.add(newTypeInference);
}
}
private void addOldTypeCheckerPasses(List<PassFactory> checks, CompilerOptions options) {
if (!options.allowsHotswapReplaceScript()) {
checks.add(inlineTypeAliases);
}
if (options.checkTypes || options.inferTypes) {
checks.add(resolveTypes);
checks.add(inferTypes);
if (options.checkTypes) {
checks.add(checkTypes);
} else {
checks.add(inferJsDocInfo);
}
// We assume that only clients who are going to re-compile, or do in-depth static analysis,
// will need the typed scope creator after the compile job.
if (!options.preservesDetailedSourceInfo() && !options.allowsHotswapReplaceScript()) {
checks.add(clearTypedScopePass);
}
}
}
@Override
protected List<PassFactory> getChecks() {
List<PassFactory> checks = new ArrayList<>();
if (options.shouldGenerateTypedExterns()) {
checks.add(closureGoogScopeAliases);
checks.add(closureRewriteClass);
checks.add(generateIjs);
checks.add(whitespaceWrapGoogModules);
return checks;
}
checks.add(createEmptyPass("beforeStandardChecks"));
// Note: ChromePass can rewrite invalid @type annotations into valid ones, so should run before
// JsDoc checks.
if (options.isChromePassEnabled()) {
checks.add(chromePass);
}
// Verify JsDoc annotations and check ES6 modules
checks.add(checkJsDocAndEs6Modules);
if (options.needsTranspilationFrom(TYPESCRIPT)) {
checks.add(convertEs6TypedToEs6);
}
if (options.enables(DiagnosticGroups.LINT_CHECKS)) {
checks.add(lintChecks);
}
if (options.closurePass && options.enables(DiagnosticGroups.LINT_CHECKS)) {
checks.add(checkRequiresAndProvidesSorted);
}
if (options.enables(DiagnosticGroups.MISSING_REQUIRE)
|| options.enables(DiagnosticGroups.STRICT_MISSING_REQUIRE)
|| options.enables(DiagnosticGroups.EXTRA_REQUIRE)) {
checks.add(checkRequires);
}
if (options.needsTranspilationOf(FeatureSet.Feature.MODULES)) {
TranspilationPasses.addEs6ModulePass(checks);
}
checks.add(checkVariableReferences);
checks.add(checkStrictMode);
if (options.closurePass) {
checks.add(closureCheckModule);
checks.add(closureRewriteModule);
}
if (options.declaredGlobalExternsOnWindow) {
checks.add(declaredGlobalExternsOnWindow);
}
checks.add(checkMissingSuper);
if (options.closurePass) {
checks.add(closureGoogScopeAliases);
checks.add(closureRewriteClass);
}
checks.add(checkSideEffects);
if (options.enables(DiagnosticGroups.MISSING_PROVIDE)) {
checks.add(checkProvides);
}
if (options.angularPass) {
checks.add(angularPass);
}
if (!options.generateExportsAfterTypeChecking && options.generateExports) {
checks.add(generateExports);
}
if (options.exportTestFunctions) {
checks.add(exportTestFunctions);
}
if (options.closurePass) {
checks.add(closurePrimitives);
}
// It's important that the PolymerPass run *after* the ClosurePrimitives and ChromePass rewrites
// and *before* the suspicious code checks. This is enforced in the assertValidOrder method.
if (options.polymerVersion != null) {
checks.add(polymerPass);
}
if (options.checkSuspiciousCode
|| options.enables(DiagnosticGroups.GLOBAL_THIS)
|| options.enables(DiagnosticGroups.DEBUGGER_STATEMENT_PRESENT)) {
checks.add(suspiciousCode);
}
if (options.closurePass && options.checkMissingGetCssNameLevel.isOn()) {
checks.add(closureCheckGetCssName);
}
if (options.syntheticBlockStartMarker != null) {
// This pass must run before the first fold constants pass.
checks.add(createSyntheticBlocks);
}
checks.add(checkVars);
if (options.inferConsts) {
checks.add(inferConsts);
}
if (options.computeFunctionSideEffects) {
checks.add(checkRegExp);
}
// This pass should run before types are assigned.
if (options.processObjectPropertyString) {
checks.add(objectPropertyStringPreprocess);
}
// It's important that the Dart super accessors pass run *before* es6ConvertSuper,
// which is a "late" ES6 pass. This is enforced in the assertValidOrder method.
if (options.dartPass && !options.getLanguageOut().toFeatureSet().contains(FeatureSet.ES6)) {
checks.add(dartSuperAccessorsPass);
}
if (options.needsTranspilationFrom(ES8)) {
TranspilationPasses.addEs2017Passes(checks);
checks.add(setFeatureSet(ES7));
}
if (options.needsTranspilationFrom(ES7) && !options.getTypeCheckEs6Natively()) {
TranspilationPasses.addEs2016Passes(checks);
checks.add(setFeatureSet(ES6));
}
if (options.needsTranspilationFrom(ES6)) {
checks.add(es6ExternsCheck);
TranspilationPasses.addEs6EarlyPasses(checks);
}
if (options.needsTranspilationFrom(ES6)) {
if (options.getTypeCheckEs6Natively()) {
TranspilationPasses.addEs6PassesBeforeNTI(checks);
} else {
TranspilationPasses.addEs6LatePasses(checks);
}
}
if (options.rewritePolyfills) {
TranspilationPasses.addRewritePolyfillPass(checks);
}
if (options.needsTranspilationFrom(ES6)) {
if (options.getTypeCheckEs6Natively()) {
checks.add(setFeatureSet(FeatureSet.NTI_SUPPORTED));
} else {
// TODO(bradfordcsmith): This marking is really about how variable scoping is handled during
// type checking. It should really be handled in a more direct fashion.
checks.add(setFeatureSet(options.getLanguageOut().toFeatureSet()));
}
}
if (!options.forceLibraryInjection.isEmpty()) {
checks.add(injectRuntimeLibraries);
}
if (options.needsTranspilationFrom(ES6)) {
checks.add(convertStaticInheritance);
}
// End of ES6 transpilation passes before NTI.
if (options.getTypeCheckEs6Natively()) {
if (!options.skipNonTranspilationPasses) {
checks.add(createEmptyPass(PassNames.BEFORE_TYPE_CHECKING));
addNewTypeCheckerPasses(checks, options);
}
if (options.needsTranspilationFrom(ES7)) {
TranspilationPasses.addEs2016Passes(checks);
checks.add(setFeatureSet(ES6));
}
if (options.needsTranspilationFrom(ES6)) {
TranspilationPasses.addEs6PassesAfterNTI(checks);
checks.add(setFeatureSet(options.getLanguageOut().toFeatureSet()));
}
}
if (!options.skipNonTranspilationPasses) {
addNonTranspilationCheckPasses(checks);
}
if (options.needsTranspilationFrom(ES6) && !options.inIncrementalCheckMode()) {
TranspilationPasses.addPostCheckPasses(checks);
}
// NOTE(dimvar): Tried to move this into the optimizations, but had to back off
// because the very first pass, normalization, rewrites the code in a way that
// causes loss of type information.
// So, I will convert the remaining optimizations to use TypeI and test that only
// in unit tests, not full builds. Once all passes are converted, then
// drop the OTI-after-NTI altogether.
// In addition, I will probably have a local edit of the repo that retains both
// types on Nodes, so I can test full builds on my machine. We can't check in such
// a change because it would greatly increase memory usage.
if (options.getNewTypeInference() && options.getRunOTIafterNTI()) {
addOldTypeCheckerPasses(checks, options);
}
// When options.generateExportsAfterTypeChecking is true, run GenerateExports after
// both type checkers, not just after NTI.
if (options.generateExportsAfterTypeChecking && options.generateExports) {
checks.add(generateExports);
}
checks.add(createEmptyPass(PassNames.AFTER_STANDARD_CHECKS));
assertAllOneTimePasses(checks);
assertValidOrderForChecks(checks);
return checks;
}
private void addNonTranspilationCheckPasses(List<PassFactory> checks) {
if (!options.getTypeCheckEs6Natively()) {
checks.add(createEmptyPass(PassNames.BEFORE_TYPE_CHECKING));
addNewTypeCheckerPasses(checks, options);
}
if (options.j2clPassMode.shouldAddJ2clPasses()) {
checks.add(j2clSourceFileChecker);
}
if (!options.getNewTypeInference()) {
addOldTypeCheckerPasses(checks, options);
}
if (!options.disables(DiagnosticGroups.CHECK_USELESS_CODE)
|| (!options.getNewTypeInference() && !options.disables(DiagnosticGroups.MISSING_RETURN))) {
checks.add(checkControlFlow);
}
// CheckAccessControls only works if check types is on.
if (options.isTypecheckingEnabled()
&& (!options.disables(DiagnosticGroups.ACCESS_CONTROLS)
|| options.enables(DiagnosticGroups.CONSTANT_PROPERTY))) {
checks.add(checkAccessControls);
}
if (!options.getNewTypeInference()) {
// NTI performs this check already
checks.add(checkConsts);
}
// Analyzer checks must be run after typechecking.
if (options.enables(DiagnosticGroups.ANALYZER_CHECKS) && options.isTypecheckingEnabled()) {
checks.add(analyzerChecks);
}
if (options.checkGlobalNamesLevel.isOn()) {
checks.add(checkGlobalNames);
}
if (!options.getConformanceConfigs().isEmpty()) {
checks.add(checkConformance);
}
// Replace 'goog.getCssName' before processing defines but after the
// other checks have been done.
if (options.closurePass) {
checks.add(closureReplaceGetCssName);
}
if (options.getTweakProcessing().isOn()) {
checks.add(processTweaks);
}
if (options.instrumentationTemplate != null || options.recordFunctionInformation) {
checks.add(computeFunctionNames);
}
if (options.checksOnly) {
// Run process defines here so that warnings/errors from that pass are emitted as part of
// checks.
// TODO(rluble): Split process defines into two stages, one that performs only checks to be
// run here, and the one that actually changes the AST that would run in the optimization
// phase.
checks.add(processDefines);
}
if (options.j2clPassMode.shouldAddJ2clPasses()) {
checks.add(j2clChecksPass);
}
}
@Override
protected List<PassFactory> getOptimizations() {
List<PassFactory> passes = new ArrayList<>();
if (options.skipNonTranspilationPasses) {
return passes;
}
passes.add(garbageCollectChecks);
// i18n
// If you want to customize the compiler to use a different i18n pass,
// you can create a PassConfig that calls replacePassFactory
// to replace this.
if (options.replaceMessagesWithChromeI18n) {
passes.add(replaceMessagesForChrome);
} else if (options.messageBundle != null) {
passes.add(replaceMessages);
}
// Defines in code always need to be processed.
passes.add(processDefines);
if (options.getTweakProcessing().shouldStrip()
|| !options.stripTypes.isEmpty()
|| !options.stripNameSuffixes.isEmpty()
|| !options.stripTypePrefixes.isEmpty()
|| !options.stripNamePrefixes.isEmpty()) {
passes.add(stripCode);
}
passes.add(normalize);
// Create extern exports after the normalize because externExports depends on unique names.
if (options.isExternExportsEnabled() || options.externExportsPath != null) {
passes.add(externExports);
}
// Gather property names in externs so they can be queried by the
// optimizing passes.
passes.add(gatherExternProperties);
if (options.instrumentForCoverage) {
passes.add(instrumentForCodeCoverage);
}
// TODO(dimvar): convert this pass to use NTI. Low priority since it's
// mostly unused. Converting it shouldn't block switching to NTI.
if (options.runtimeTypeCheck && !options.getNewTypeInference()) {
passes.add(runtimeTypeCheck);
}
// Inlines functions that perform dynamic accesses to static properties of parameters that are
// typed as {Function}. This turns a dynamic access to a static property of a class definition
// into a fully qualified access and in so doing enables better dead code stripping.
if (options.j2clPassMode.shouldAddJ2clPasses()) {
passes.add(j2clPass);
}
passes.add(createEmptyPass(PassNames.BEFORE_STANDARD_OPTIMIZATIONS));
if (options.replaceIdGenerators) {
passes.add(replaceIdGenerators);
}
// Optimizes references to the arguments variable.
if (options.optimizeArgumentsArray) {
passes.add(optimizeArgumentsArray);
}
// Abstract method removal works best on minimally modified code, and also
// only needs to run once.
if (options.closurePass && (options.removeAbstractMethods || options.removeClosureAsserts)) {
passes.add(closureCodeRemoval);
}
if (options.removeJ2clAsserts) {
passes.add(j2clAssertRemovalPass);
}
// Property disambiguation should only run once and needs to be done
// soon after type checking, both so that it can make use of type
// information and so that other passes can take advantage of the renamed
// properties.
if (options.disambiguatePrivateProperties) {
passes.add(disambiguatePrivateProperties);
}
assertAllOneTimePasses(passes);
// Inline aliases so that following optimizations don't have to understand alias chains.
if (options.collapseProperties) {
passes.add(aggressiveInlineAliases);
}
// Inline getters/setters in J2CL classes so that Object.defineProperties() calls (resulting
// from desugaring) don't block class stripping.
if (options.j2clPassMode.shouldAddJ2clPasses() && options.collapseProperties) {
// Relies on collapseProperties-triggered aggressive alias inlining.
passes.add(j2clPropertyInlinerPass);
}
// Collapsing properties can undo constant inlining, so we do this before
// the main optimization loop.
if (options.collapseProperties) {
passes.add(collapseProperties);
}
if (options.inferConsts) {
passes.add(inferConsts);
}
if (options.reportPath != null && options.smartNameRemoval) {
passes.add(initNameAnalyzeReport);
}
// TODO(mlourenco): Ideally this would be in getChecks() instead of getOptimizations(). But
// for that it needs to understand constant properties as well. See b/31301233#10.
// Needs to happen after inferConsts and collapseProperties. Detects whether invocations of
// the method goog.string.Const.from are done with an argument which is a string literal.
passes.add(checkConstParams);
// Running smart name removal before disambiguate properties allows disambiguate properties
// to be more effective if code that would prevent disambiguation can be removed.
if (options.extraSmartNameRemoval && options.smartNameRemoval) {
// These passes remove code that is dead because of define flags.
// If the dead code is weakly typed, running these passes before property
// disambiguation results in more code removal.
// The passes are one-time on purpose. (The later runs are loopable.)
if (options.foldConstants && (options.inlineVariables || options.inlineLocalVariables)) {
passes.add(earlyInlineVariables);
passes.add(earlyPeepholeOptimizations);
}
passes.add(extraSmartNamePass);
}
// RewritePolyfills is overly generous in the polyfills it adds. After type
// checking and early smart name removal, we can use the new type information
// to figure out which polyfilled prototype methods are actually called, and
// which were "false alarms" (i.e. calling a method of the same name on a
// user-provided class). We also remove any polyfills added by code that
// was smart-name-removed. This is a one-time pass, since it does not work
// after inlining - we do not attempt to aggressively remove polyfills used
// by code that is only flow-sensitively dead.
if (options.rewritePolyfills) {
passes.add(removeUnusedPolyfills);
}
// Property disambiguation should only run once and needs to be done
// soon after type checking, both so that it can make use of type
// information and so that other passes can take advantage of the renamed
// properties.
if (options.shouldDisambiguateProperties() && options.isTypecheckingEnabled()) {
passes.add(disambiguateProperties);
}
if (options.computeFunctionSideEffects) {
passes.add(markPureFunctions);
} else if (options.markNoSideEffectCalls) {
// TODO(user) The properties that this pass adds to CALL and NEW
// AST nodes increase the AST's in-memory size. Given that we are
// already running close to our memory limits, we could run into
// trouble if we end up using the @nosideeffects annotation a lot
// or compute @nosideeffects annotations by looking at function
// bodies. It should be easy to propagate @nosideeffects
// annotations as part of passes that depend on this property and
// store the result outside the AST (which would allow garbage
// collection once the pass is done).
passes.add(markNoSideEffectCalls);
}
if (options.chainCalls) {
passes.add(chainCalls);
}
if (options.smartNameRemoval || options.reportPath != null) {
passes.addAll(getCodeRemovingPasses());
passes.add(smartNamePass);
}
// This needs to come after the inline constants pass, which is run within
// the code removing passes.
if (options.closurePass) {
passes.add(closureOptimizePrimitives);
}
// ReplaceStrings runs after CollapseProperties in order to simplify
// pulling in values of constants defined in enums structures. It also runs
// after disambiguate properties and smart name removal so that it can
// correctly identify logging types and can replace references to string
// expressions.
if (!options.replaceStringsFunctionDescriptions.isEmpty()) {
passes.add(replaceStrings);
}
// TODO(user): This forces a first crack at crossModuleCodeMotion
// before devirtualization. Once certain functions are devirtualized,
// it confuses crossModuleCodeMotion ability to recognized that
// it is recursive.
// TODO(user): This is meant for a temporary quick win.
// In the future, we might want to improve our analysis in
// CrossModuleCodeMotion so we don't need to do this.
if (options.crossModuleCodeMotion) {
passes.add(crossModuleCodeMotion);
}
// Must run after ProcessClosurePrimitives, Es6ConvertSuper, and assertion removals, but
// before OptimizeCalls (specifically, OptimizeParameters) and DevirtualizePrototypeMethods.
if (options.removeSuperMethods) {
passes.add(removeSuperMethodsPass);
}
// Method devirtualization benefits from property disambiguation so
// it should run after that pass but before passes that do
// optimizations based on global names (like cross module code motion
// and inline functions). Smart Name Removal does better if run before
// this pass.
if (options.devirtualizePrototypeMethods) {
passes.add(devirtualizePrototypeMethods);
}
if (options.customPasses != null) {
passes.add(getCustomPasses(
CustomPassExecutionTime.BEFORE_OPTIMIZATION_LOOP));
}
passes.add(createEmptyPass(PassNames.BEFORE_MAIN_OPTIMIZATIONS));
// Because FlowSensitiveInlineVariables does not operate on the global scope due to compilation
// time, we need to run it once before InlineFunctions so that we don't miss inlining
// opportunities when a function will be inlined into the global scope.
if (options.inlineVariables || options.inlineLocalVariables) {
passes.add(flowSensitiveInlineVariables);
}
passes.addAll(getMainOptimizationLoop());
passes.add(createEmptyPass(PassNames.AFTER_MAIN_OPTIMIZATIONS));
passes.add(createEmptyPass("beforeModuleMotion"));
if (options.crossModuleCodeMotion) {
passes.add(crossModuleCodeMotion);
}
if (options.crossModuleMethodMotion) {
passes.add(crossModuleMethodMotion);
}
passes.add(createEmptyPass("afterModuleMotion"));
// Some optimizations belong outside the loop because running them more
// than once would either have no benefit or be incorrect.
if (options.customPasses != null) {
passes.add(getCustomPasses(
CustomPassExecutionTime.AFTER_OPTIMIZATION_LOOP));
}
if (options.inlineVariables || options.inlineLocalVariables) {
passes.add(flowSensitiveInlineVariables);
// After inlining some of the variable uses, some variables are unused.
// Re-run remove unused vars to clean it up.
if (options.removeUnusedVars || options.removeUnusedLocalVars) {
passes.add(lastRemoveUnusedVars());
}
}
// Running this pass again is required to have goog.events compile down to
// nothing when compiled on its own.
if (options.smartNameRemoval) {
passes.add(smartNamePass2);
}
if (options.collapseAnonymousFunctions) {
passes.add(collapseAnonymousFunctions);
}
// Move functions before extracting prototype member declarations.
if (options.moveFunctionDeclarations
// renamePrefixNamescape relies on moveFunctionDeclarations
// to preserve semantics.
|| options.renamePrefixNamespace != null) {
passes.add(moveFunctionDeclarations);
}
if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.MAPPED) {
passes.add(nameMappedAnonymousFunctions);
}
// The mapped name anonymous function pass makes use of information that
// the extract prototype member declarations pass removes so the former
// happens before the latter.
if (options.extractPrototypeMemberDeclarations != ExtractPrototypeMemberDeclarationsMode.OFF) {
passes.add(extractPrototypeMemberDeclarations);
}
if (options.shouldAmbiguateProperties()
&& options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED
&& options.isTypecheckingEnabled()) {
passes.add(ambiguateProperties);
}
if (options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED) {
passes.add(renameProperties);
}
// Reserve global names added to the "windows" object.
if (options.reserveRawExports) {
passes.add(gatherRawExports);
}
// This comes after property renaming because quoted property names must
// not be renamed.
if (options.convertToDottedProperties) {
passes.add(convertToDottedProperties);
}
// Property renaming must happen before this pass runs since this
// pass may convert dotted properties into quoted properties. It
// is beneficial to run before alias strings, alias keywords and
// variable renaming.
if (options.rewriteFunctionExpressions) {
passes.add(rewriteFunctionExpressions);
}
// This comes after converting quoted property accesses to dotted property
// accesses in order to avoid aliasing property names.
if (!options.aliasableStrings.isEmpty() || options.aliasAllStrings) {
passes.add(aliasStrings);
}
if (options.coalesceVariableNames) {
// Passes after this point can no longer depend on normalized AST
// assumptions because the code is marked as un-normalized
passes.add(coalesceVariableNames);
// coalesceVariables creates identity assignments and more redundant code
// that can be removed, rerun the peephole optimizations to clean them
// up.
if (options.foldConstants) {
passes.add(peepholeOptimizationsOnce);
}
}
// Passes after this point can no longer depend on normalized AST assumptions.
passes.add(markUnnormalized);
if (options.collapseVariableDeclarations) {
passes.add(exploitAssign);
passes.add(collapseVariableDeclarations);
}
// This pass works best after collapseVariableDeclarations.
passes.add(denormalize);
if (options.instrumentationTemplate != null) {
passes.add(instrumentFunctions);
}
if (options.variableRenaming != VariableRenamingPolicy.ALL) {
// If we're leaving some (or all) variables with their old names,
// then we need to undo any of the markers we added for distinguishing
// local variables ("x" -> "x$jscomp$1").
passes.add(invertContextualRenaming);
}
if (options.variableRenaming != VariableRenamingPolicy.OFF) {
passes.add(renameVars);
}
// This pass should run after names stop changing.
if (options.processObjectPropertyString) {
passes.add(objectPropertyStringPostprocess);
}
if (options.labelRenaming) {
passes.add(renameLabels);
}
if (options.foldConstants) {
passes.add(latePeepholeOptimizations);
}
if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.UNMAPPED) {
passes.add(nameUnmappedAnonymousFunctions);
}
if (protectHiddenSideEffects) {
passes.add(stripSideEffectProtection);
}
if (options.renamePrefixNamespace != null) {
if (!GLOBAL_SYMBOL_NAMESPACE_PATTERN.matcher(
options.renamePrefixNamespace).matches()) {
throw new IllegalArgumentException(
"Illegal character in renamePrefixNamespace name: "
+ options.renamePrefixNamespace);
}
passes.add(rescopeGlobalSymbols);
}
// Safety checks
passes.add(checkAstValidity);
passes.add(varCheckValidity);
// Raise to ES6, if allowed
if (options.getLanguageOut().toFeatureSet().contains(FeatureSet.ES6)) {
passes.add(optimizeToEs6);
}
assertValidOrderForOptimizations(passes);
return passes;
}
/** Creates the passes for the main optimization loop. */
private List<PassFactory> getMainOptimizationLoop() {
List<PassFactory> passes = new ArrayList<>();
if (options.inlineGetters) {
passes.add(inlineSimpleMethods);
}
passes.addAll(getCodeRemovingPasses());
if (options.inlineFunctions || options.inlineLocalFunctions) {
passes.add(inlineFunctions);
}
if (options.shouldInlineProperties() && options.isTypecheckingEnabled()) {
passes.add(inlineProperties);
}
boolean runOptimizeCalls = options.optimizeCalls
|| options.optimizeParameters
|| options.optimizeReturns;
if (options.removeUnusedVars || options.removeUnusedLocalVars) {
if (options.deadAssignmentElimination) {
passes.add(deadAssignmentsElimination);
// The Polymer source is usually not included in the compilation, but it creates
// getters/setters for many properties in compiled code. Dead property assignment
// elimination is only safe when it knows about getters/setters. Therefore, we skip
// it if the polymer pass is enabled.
if (options.polymerVersion == null) {
passes.add(deadPropertyAssignmentElimination);
}
}
if (!runOptimizeCalls) {
passes.add(getRemoveUnusedVars(PassNames.REMOVE_UNUSED_VARS, false));
}
}
if (runOptimizeCalls) {
passes.add(optimizeCalls);
// RemoveUnusedVars cleans up after optimizeCalls, so we run it here.
// It has a special name because otherwise PhaseOptimizer would change its
// position in the optimization loop.
if (options.optimizeCalls) {
passes.add(getRemoveUnusedVars("removeUnusedVars_afterOptimizeCalls", true));
}
}
if (options.j2clPassMode.shouldAddJ2clPasses()) {
passes.add(j2clConstantHoisterPass);
passes.add(j2clClinitPass);
}
assertAllLoopablePasses(passes);
return passes;
}
/** Creates several passes aimed at removing code. */
private List<PassFactory> getCodeRemovingPasses() {
List<PassFactory> passes = new ArrayList<>();
if (options.collapseObjectLiterals) {
passes.add(collapseObjectLiterals);
}
if (options.inlineVariables || options.inlineLocalVariables) {
passes.add(inlineVariables);
} else if (options.inlineConstantVars) {
passes.add(inlineConstants);
}
if (options.foldConstants) {
passes.add(peepholeOptimizations);
}
if (options.removeDeadCode) {
passes.add(removeUnreachableCode);
}
if (options.removeUnusedPrototypeProperties) {
passes.add(removeUnusedPrototypeProperties);
}
if (options.removeUnusedClassProperties) {
passes.add(removeUnusedClassProperties);
}
assertAllLoopablePasses(passes);
return passes;
}
private final HotSwapPassFactory checkSideEffects =
new HotSwapPassFactory("checkSideEffects") {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new CheckSideEffects(
compiler, options.checkSuspiciousCode, protectHiddenSideEffects);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Removes the "protector" functions that were added by CheckSideEffects. */
private final PassFactory stripSideEffectProtection =
new PassFactory(PassNames.STRIP_SIDE_EFFECT_PROTECTION, true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CheckSideEffects.StripProtection(compiler);
}
@Override
public FeatureSet featureSet() {
return FeatureSet.latest();
}
};
/** Checks for code that is probably wrong (such as stray expressions). */
private final HotSwapPassFactory suspiciousCode =
new HotSwapPassFactory("suspiciousCode") {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
List<Callback> sharedCallbacks = new ArrayList<>();
if (options.checkSuspiciousCode) {
sharedCallbacks.add(new CheckSuspiciousCode());
sharedCallbacks.add(new CheckDuplicateCase(compiler));
}
if (options.enables(DiagnosticGroups.GLOBAL_THIS)) {
sharedCallbacks.add(new CheckGlobalThis(compiler));
}
if (options.enables(DiagnosticGroups.DEBUGGER_STATEMENT_PRESENT)) {
sharedCallbacks.add(new CheckDebuggerStatement(compiler));
}
return combineChecks(compiler, sharedCallbacks);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Verify that all the passes are one-time passes. */
private static void assertAllOneTimePasses(List<PassFactory> passes) {
for (PassFactory pass : passes) {
checkState(pass.isOneTimePass());
}
}
/** Verify that all the passes are multi-run passes. */
private static void assertAllLoopablePasses(List<PassFactory> passes) {
for (PassFactory pass : passes) {
checkState(!pass.isOneTimePass());
}
}
/**
* Checks that {@code pass1} comes before {@code pass2} in {@code passList}, if both are present.
*/
private void assertPassOrder(
List<PassFactory> passList, PassFactory pass1, PassFactory pass2, String msg) {
int pass1Index = passList.indexOf(pass1);
int pass2Index = passList.indexOf(pass2);
if (pass1Index != -1 && pass2Index != -1) {
checkState(pass1Index < pass2Index, msg);
}
}
/**
* Certain checks need to run in a particular order. For example, the PolymerPass
* will not work correctly unless it runs after the goog.provide() processing.
* This enforces those constraints.
* @param checks The list of check passes
*/
private void assertValidOrderForChecks(List<PassFactory> checks) {
assertPassOrder(
checks,
chromePass,
checkJsDocAndEs6Modules,
"The ChromePass must run before after JsDoc and Es6 module checking.");
assertPassOrder(
checks,
closureRewriteModule,
processDefines,
"Must rewrite goog.module before processing @define's, so that @defines in modules work.");
assertPassOrder(
checks,
closurePrimitives,
polymerPass,
"The Polymer pass must run after goog.provide processing.");
assertPassOrder(
checks,
chromePass,
polymerPass,
"The Polymer pass must run after ChromePass processing.");
assertPassOrder(
checks,
polymerPass,
suspiciousCode,
"The Polymer pass must run before suspiciousCode processing.");
assertPassOrder(
checks,
dartSuperAccessorsPass,
TranspilationPasses.es6ConvertSuper,
"The Dart super accessors pass must run before ES6->ES3 super lowering.");
if (checks.contains(closureGoogScopeAliases)) {
checkState(
checks.contains(checkVariableReferences),
"goog.scope processing requires variable checking");
}
assertPassOrder(
checks,
checkVariableReferences,
closureGoogScopeAliases,
"Variable checking must happen before goog.scope processing.");
assertPassOrder(
checks,
TranspilationPasses.es6ConvertSuper,
removeSuperMethodsPass,
"Super-call method removal must run after Es6 super rewriting, "
+ "because Es6 super calls are matched on their post-processed form.");
assertPassOrder(
checks,
closurePrimitives,
removeSuperMethodsPass,
"Super-call method removal must run after Es6 super rewriting, "
+ "because Closure base calls are expected to be in post-processed form.");
assertPassOrder(
checks,
closureCodeRemoval,
removeSuperMethodsPass,
"Super-call method removal must run after closure code removal, because "
+ "removing assertions may make more super calls eligible to be stripped.");
}
/**
* Certain optimizations need to run in a particular order. For example, OptimizeCalls must run
* before RemoveSuperMethodsPass, because the former can invalidate assumptions in the latter.
* This enforces those constraints.
* @param optimizations The list of optimization passes
*/
private void assertValidOrderForOptimizations(List<PassFactory> optimizations) {
assertPassOrder(optimizations, removeSuperMethodsPass, optimizeCalls,
"RemoveSuperMethodsPass must run before OptimizeCalls.");
assertPassOrder(optimizations, removeSuperMethodsPass, devirtualizePrototypeMethods,
"RemoveSuperMethodsPass must run before DevirtualizePrototypeMethods.");
}
/** Checks that all constructed classes are goog.require()d. */
private final HotSwapPassFactory checkRequires =
new HotSwapPassFactory("checkMissingAndExtraRequires") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new CheckMissingAndExtraRequires(
compiler, CheckMissingAndExtraRequires.Mode.FULL_COMPILE);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Makes sure @constructor is paired with goog.provides(). */
private final HotSwapPassFactory checkProvides =
new HotSwapPassFactory("checkProvides") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new CheckProvides(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
private static final DiagnosticType GENERATE_EXPORTS_ERROR =
DiagnosticType.error(
"JSC_GENERATE_EXPORTS_ERROR",
"Exports can only be generated if export symbol/property functions are set.");
/** Verifies JSDoc annotations are used properly and checks for ES6 modules. */
private final HotSwapPassFactory checkJsDocAndEs6Modules =
new HotSwapPassFactory("checkJsDocAndEs6Modules") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
ImmutableList.Builder<Callback> callbacks =
ImmutableList.<Callback>builder()
.add(new CheckJSDoc(compiler))
.add(new Es6CheckModule(compiler));
return combineChecks(compiler, callbacks.build());
}
@Override
protected FeatureSet featureSet() {
return FeatureSet.latest();
}
};
/** Generates exports for @export annotations. */
private final PassFactory generateExports =
new PassFactory(PassNames.GENERATE_EXPORTS, true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
CodingConvention convention = compiler.getCodingConvention();
if (convention.getExportSymbolFunction() != null
&& convention.getExportPropertyFunction() != null) {
final GenerateExports pass =
new GenerateExports(
compiler,
options.exportLocalPropertyDefinitions,
convention.getExportSymbolFunction(),
convention.getExportPropertyFunction());
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
pass.process(externs, root);
compiler.addExportedNames(pass.getExportedVariableNames());
}
};
} else {
return new ErrorPass(compiler, GENERATE_EXPORTS_ERROR);
}
}
@Override
protected FeatureSet featureSet() {
return ES8;
}
};
private final PassFactory generateIjs =
new PassFactory("generateIjs", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ConvertToTypedInterface(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Generates exports for functions associated with JsUnit. */
private final PassFactory exportTestFunctions =
new PassFactory(PassNames.EXPORT_TEST_FUNCTIONS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
CodingConvention convention = compiler.getCodingConvention();
if (convention.getExportSymbolFunction() != null) {
return new ExportTestFunctions(
compiler,
convention.getExportSymbolFunction(),
convention.getExportPropertyFunction());
} else {
return new ErrorPass(compiler, GENERATE_EXPORTS_ERROR);
}
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Raw exports processing pass. */
private final PassFactory gatherRawExports =
new PassFactory(PassNames.GATHER_RAW_EXPORTS, true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
final GatherRawExports pass = new GatherRawExports(compiler);
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
pass.process(externs, root);
compiler.addExportedNames(pass.getExportedVariableNames());
}
};
}
@Override
public FeatureSet featureSet() {
// Should be FeatureSet.latest() since it's a trivial pass, but must match "normalize"
// TODO(johnlenz): Update this and normalize to latest()
return ES8_MODULES;
}
};
/** Closure pre-processing pass. */
private final HotSwapPassFactory closurePrimitives =
new HotSwapPassFactory("closurePrimitives") {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
maybeInitializePreprocessorSymbolTable(compiler);
final ProcessClosurePrimitives pass =
new ProcessClosurePrimitives(
compiler,
preprocessorSymbolTable,
options.brokenClosureRequiresLevel,
options.shouldPreservesGoogProvidesAndRequires());
return new HotSwapCompilerPass() {
@Override
public void process(Node externs, Node root) {
pass.process(externs, root);
compiler.addExportedNames(pass.getExportedVariableNames());
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
pass.hotSwapScript(scriptRoot, originalRoot);
}
};
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Process AngularJS-specific annotations. */
private final HotSwapPassFactory angularPass =
new HotSwapPassFactory(PassNames.ANGULAR_PASS) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new AngularPass(compiler);
}
@Override
public FeatureSet featureSet() {
return ES8_MODULES;
}
};
/**
* The default i18n pass. A lot of the options are not configurable, because ReplaceMessages has a
* lot of legacy logic.
*/
private final PassFactory replaceMessages =
new PassFactory(PassNames.REPLACE_MESSAGES, true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new ReplaceMessages(
compiler,
options.messageBundle,
/* warn about message dupes */
true,
/* allow messages with goog.getMsg */
JsMessage.Style.CLOSURE,
/* if we can't find a translation, don't worry about it. */
false);
}
@Override
public FeatureSet featureSet() {
return ES8_MODULES;
}
};
private final PassFactory replaceMessagesForChrome =
new PassFactory(PassNames.REPLACE_MESSAGES, true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new ReplaceMessagesForChrome(
compiler,
new GoogleJsMessageIdGenerator(options.tcProjectId),
/* warn about message dupes */
true,
/* allow messages with goog.getMsg */
JsMessage.Style.CLOSURE);
}
@Override
public FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Applies aliases and inlines goog.scope. */
private final HotSwapPassFactory closureGoogScopeAliases =
new HotSwapPassFactory("closureGoogScopeAliases") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
maybeInitializePreprocessorSymbolTable(compiler);
return new ScopedAliases(
compiler, preprocessorSymbolTable, options.getAliasTransformationHandler());
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
private final PassFactory injectRuntimeLibraries =
new PassFactory("InjectRuntimeLibraries", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new InjectRuntimeLibraries(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
private final PassFactory es6ExternsCheck =
new PassFactory("es6ExternsCheck", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new Es6ExternsCheck(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Desugars ES6_TYPED features into ES6 code. */
final HotSwapPassFactory convertEs6TypedToEs6 =
new HotSwapPassFactory("convertEs6Typed") {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new Es6TypedToEs6Converter(compiler);
}
@Override
protected FeatureSet featureSet() {
return TYPESCRIPT;
}
};
private final PassFactory convertStaticInheritance =
new PassFactory("Es6StaticInheritance", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new Es6ToEs3ClassSideInheritance(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES5;
}
};
private final PassFactory inlineTypeAliases =
new PassFactory(PassNames.INLINE_TYPE_ALIASES, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InlineAliases(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES6;
}
};
/** Inlines type aliases if they are explicitly or effectively const. */
private final PassFactory aggressiveInlineAliases =
new PassFactory("aggressiveInlineAliases", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new AggressiveInlineAliases(compiler);
}
};
private final PassFactory setFeatureSet(final FeatureSet featureSet) {
return new PassFactory("setFeatureSet:" + featureSet.version(), true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
compiler.setFeatureSet(featureSet);
}
};
}
@Override
public FeatureSet featureSet() {
return FeatureSet.latest();
}
};
}
private final PassFactory declaredGlobalExternsOnWindow =
new PassFactory(PassNames.DECLARED_GLOBAL_EXTERNS_ON_WINDOW, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new DeclaredGlobalExternsOnWindow(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Rewrites goog.defineClass */
private final HotSwapPassFactory closureRewriteClass =
new HotSwapPassFactory(PassNames.CLOSURE_REWRITE_CLASS) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new ClosureRewriteClass(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Checks of correct usage of goog.module */
private final HotSwapPassFactory closureCheckModule =
new HotSwapPassFactory("closureCheckModule") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new ClosureCheckModule(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Rewrites goog.module */
private final HotSwapPassFactory closureRewriteModule =
new HotSwapPassFactory("closureRewriteModule") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
maybeInitializePreprocessorSymbolTable(compiler);
maybeInitializeModuleRewriteState();
return new ClosureRewriteModule(compiler, preprocessorSymbolTable, moduleRewriteState);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Checks that CSS class names are wrapped in goog.getCssName */
private final PassFactory closureCheckGetCssName =
new PassFactory("closureCheckGetCssName", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CheckMissingGetCssName(
compiler,
options.checkMissingGetCssNameLevel,
options.checkMissingGetCssNameBlacklist);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/**
* Processes goog.getCssName. The cssRenamingMap is used to lookup
* replacement values for the classnames. If null, the raw class names are
* inlined.
*/
private final PassFactory closureReplaceGetCssName =
new PassFactory("closureReplaceGetCssName", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
Map<String, Integer> newCssNames = null;
if (options.gatherCssNames) {
newCssNames = new HashMap<>();
}
ReplaceCssNames pass = new ReplaceCssNames(
compiler,
newCssNames,
options.cssRenamingWhitelist);
pass.process(externs, jsRoot);
compiler.setCssNames(newCssNames);
}
};
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/**
* Creates synthetic blocks to prevent FoldConstants from moving code past markers in the source.
*/
private final PassFactory createSyntheticBlocks =
new PassFactory("createSyntheticBlocks", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CreateSyntheticBlocks(
compiler, options.syntheticBlockStartMarker, options.syntheticBlockEndMarker);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
private final PassFactory earlyPeepholeOptimizations =
new PassFactory("earlyPeepholeOptimizations", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
List<AbstractPeepholeOptimization> peepholeOptimizations = new ArrayList<>();
peepholeOptimizations.add(new PeepholeRemoveDeadCode());
if (compiler.getOptions().j2clPassMode.shouldAddJ2clPasses()) {
peepholeOptimizations.add(new J2clEqualitySameRewriterPass());
}
return new PeepholeOptimizationsPass(compiler, getName(), peepholeOptimizations);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
private final PassFactory earlyInlineVariables =
new PassFactory("earlyInlineVariables", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
InlineVariables.Mode mode;
if (options.inlineVariables) {
mode = InlineVariables.Mode.ALL;
} else if (options.inlineLocalVariables) {
mode = InlineVariables.Mode.LOCALS_ONLY;
} else {
throw new IllegalStateException("No variable inlining option set.");
}
return new InlineVariables(compiler, mode, true);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Various peephole optimizations. */
private static CompilerPass createPeepholeOptimizationsPass(
AbstractCompiler compiler, String passName) {
final boolean late = false;
final boolean useTypesForOptimization = compiler.getOptions().useTypesForLocalOptimization;
List<AbstractPeepholeOptimization> optimizations = new ArrayList<>();
optimizations.add(new MinimizeExitPoints(compiler));
optimizations.add(new PeepholeMinimizeConditions(late, useTypesForOptimization));
optimizations.add(new PeepholeSubstituteAlternateSyntax(late));
optimizations.add(new PeepholeReplaceKnownMethods(late, useTypesForOptimization));
optimizations.add(new PeepholeRemoveDeadCode());
if (compiler.getOptions().j2clPassMode.shouldAddJ2clPasses()) {
optimizations.add(new J2clEqualitySameRewriterPass());
}
optimizations.add(new PeepholeFoldConstants(late, useTypesForOptimization));
optimizations.add(new PeepholeCollectPropertyAssignments());
return new PeepholeOptimizationsPass(compiler, passName, optimizations);
}
/** Various peephole optimizations. */
private final PassFactory peepholeOptimizations =
new PassFactory(PassNames.PEEPHOLE_OPTIMIZATIONS, false /* oneTimePass */) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return createPeepholeOptimizationsPass(compiler, getName());
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Various peephole optimizations. */
private final PassFactory peepholeOptimizationsOnce =
new PassFactory(PassNames.PEEPHOLE_OPTIMIZATIONS, true /* oneTimePass */) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return createPeepholeOptimizationsPass(compiler, getName());
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Same as peepholeOptimizations but aggressively merges code together */
private final PassFactory latePeepholeOptimizations =
new PassFactory("latePeepholeOptimizations", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
final boolean late = true;
final boolean useTypesForOptimization = options.useTypesForLocalOptimization;
return new PeepholeOptimizationsPass(
compiler,
getName(),
new StatementFusion(options.aggressiveFusion),
new PeepholeRemoveDeadCode(),
new PeepholeMinimizeConditions(late, useTypesForOptimization),
new PeepholeSubstituteAlternateSyntax(late),
new PeepholeReplaceKnownMethods(late, useTypesForOptimization),
new PeepholeFoldConstants(late, useTypesForOptimization),
new PeepholeReorderConstantExpression());
}
};
/** Checks that all variables are defined. */
private final HotSwapPassFactory checkVars =
new HotSwapPassFactory(PassNames.CHECK_VARS) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new VarCheck(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Infers constants. */
private final PassFactory inferConsts =
new PassFactory(PassNames.INFER_CONSTS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InferConsts(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Checks for RegExp references. */
private final PassFactory checkRegExp =
new PassFactory(PassNames.CHECK_REG_EXP, true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
final CheckRegExp pass = new CheckRegExp(compiler);
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
pass.process(externs, root);
compiler.setHasRegExpGlobalReferences(pass.isGlobalRegExpPropertiesUsed());
}
};
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Checks that references to variables look reasonable. */
private final HotSwapPassFactory checkVariableReferencesForTranspileOnly =
new HotSwapPassFactory(PassNames.CHECK_VARIABLE_REFERENCES) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new VariableReferenceCheck(compiler, true);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Checks that references to variables look reasonable. */
private final HotSwapPassFactory checkVariableReferences =
new HotSwapPassFactory(PassNames.CHECK_VARIABLE_REFERENCES) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new VariableReferenceCheck(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Checks that references to variables look reasonable. */
private final HotSwapPassFactory checkMissingSuper =
new HotSwapPassFactory("checkMissingSuper") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new CheckMissingSuper(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Pre-process goog.testing.ObjectPropertyString. */
private final PassFactory objectPropertyStringPreprocess =
new PassFactory("ObjectPropertyStringPreprocess", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ObjectPropertyStringPreprocess(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Creates a typed scope and adds types to the type registry. */
final HotSwapPassFactory resolveTypes =
new HotSwapPassFactory(PassNames.RESOLVE_TYPES) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new GlobalTypeResolver(compiler);
}
};
/** Clears the typed scope when we're done. */
private final PassFactory clearTypedScopePass =
new PassFactory("clearTypedScopePass", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ClearTypedScope();
}
@Override
protected FeatureSet featureSet() {
return FeatureSet.latest();
}
};
/** Runs type inference. */
final HotSwapPassFactory inferTypes =
new HotSwapPassFactory(PassNames.INFER_TYPES) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new HotSwapCompilerPass() {
@Override
public void process(Node externs, Node root) {
checkNotNull(topScope);
checkNotNull(getTypedScopeCreator());
makeTypeInference(compiler).process(externs, root);
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
makeTypeInference(compiler).inferAllScopes(scriptRoot);
}
};
}
};
private final PassFactory symbolTableForNewTypeInference =
new PassFactory("GlobalTypeInfo", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new GlobalTypeInfoCollector(compiler);
}
@Override
protected FeatureSet featureSet() {
return FeatureSet.NTI_SUPPORTED;
}
};
private final PassFactory newTypeInference =
new PassFactory("NewTypeInference", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new NewTypeInference(compiler);
}
@Override
protected FeatureSet featureSet() {
return FeatureSet.NTI_SUPPORTED;
}
};
private final HotSwapPassFactory inferJsDocInfo =
new HotSwapPassFactory("inferJsDocInfo") {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new HotSwapCompilerPass() {
@Override
public void process(Node externs, Node root) {
checkNotNull(topScope);
checkNotNull(getTypedScopeCreator());
makeInferJsDocInfo(compiler).process(externs, root);
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
makeInferJsDocInfo(compiler).hotSwapScript(scriptRoot, originalRoot);
}
};
}
};
/** Checks type usage */
private final HotSwapPassFactory checkTypes =
new HotSwapPassFactory(PassNames.CHECK_TYPES) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new HotSwapCompilerPass() {
@Override
public void process(Node externs, Node root) {
checkNotNull(topScope);
checkNotNull(getTypedScopeCreator());
TypeCheck check = makeTypeCheck(compiler);
check.process(externs, root);
compiler.getErrorManager().setTypedPercent(check.getTypedPercent());
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
makeTypeCheck(compiler).check(scriptRoot, false);
}
};
}
};
/**
* Checks possible execution paths of the program for problems: missing return
* statements and dead code.
*/
private final HotSwapPassFactory checkControlFlow =
new HotSwapPassFactory("checkControlFlow") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
List<Callback> callbacks = new ArrayList<>();
if (!options.disables(DiagnosticGroups.CHECK_USELESS_CODE)) {
callbacks.add(new CheckUnreachableCode(compiler));
}
if (!options.getNewTypeInference() && !options.disables(DiagnosticGroups.MISSING_RETURN)) {
callbacks.add(new CheckMissingReturn(compiler));
}
return combineChecks(compiler, callbacks);
}
@Override
public FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Checks access controls. Depends on type-inference. */
private final HotSwapPassFactory checkAccessControls =
new HotSwapPassFactory("checkAccessControls") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new CheckAccessControls(
compiler, options.enforceAccessControlCodingConventions);
}
};
private final HotSwapPassFactory lintChecks =
new HotSwapPassFactory(PassNames.LINT_CHECKS) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
ImmutableList.Builder<Callback> callbacks =
ImmutableList.<Callback>builder()
.add(new CheckEmptyStatements(compiler))
.add(new CheckEnums(compiler))
.add(new CheckInterfaces(compiler))
.add(new CheckJSDocStyle(compiler))
.add(new CheckMissingSemicolon(compiler))
.add(new CheckPrimitiveAsObject(compiler))
.add(new CheckPrototypeProperties(compiler))
.add(new CheckUnusedLabels(compiler))
.add(new CheckUselessBlocks(compiler));
return combineChecks(compiler, callbacks.build());
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
private final HotSwapPassFactory analyzerChecks =
new HotSwapPassFactory(PassNames.ANALYZER_CHECKS) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
ImmutableList.Builder<Callback> callbacks = ImmutableList.<Callback>builder();
if (options.enables(DiagnosticGroups.ANALYZER_CHECKS_INTERNAL)) {
callbacks
.add(new CheckNullableReturn(compiler))
.add(new CheckArrayWithGoogObject(compiler))
.add(new ImplicitNullabilityCheck(compiler));
}
// These are grouped together for better execution efficiency.
if (options.enables(DiagnosticGroups.UNUSED_PRIVATE_PROPERTY)) {
callbacks.add(new CheckUnusedPrivateProperties(compiler));
}
return combineChecks(compiler, callbacks.build());
}
};
private final HotSwapPassFactory checkRequiresAndProvidesSorted =
new HotSwapPassFactory("checkRequiresAndProvidesSorted") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new CheckRequiresAndProvidesSorted(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Executes the given callbacks with a {@link CombinedCompilerPass}. */
private static HotSwapCompilerPass combineChecks(AbstractCompiler compiler,
List<Callback> callbacks) {
checkArgument(!callbacks.isEmpty());
return new CombinedCompilerPass(compiler, callbacks);
}
/** A compiler pass that resolves types in the global scope. */
class GlobalTypeResolver implements HotSwapCompilerPass {
private final AbstractCompiler compiler;
GlobalTypeResolver(AbstractCompiler compiler) {
this.compiler = compiler;
}
@Override
public void process(Node externs, Node root) {
// If NTI is enabled, erase the NTI types from the AST before adding the old types.
if (this.compiler.getOptions().getNewTypeInference()) {
NodeTraversal.traverseEs6(
this.compiler, root,
new NodeTraversal.AbstractPostOrderCallback(){
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
n.setTypeI(null);
}
});
this.compiler.clearTypeIRegistry();
}
this.compiler.setMostRecentTypechecker(MostRecentTypechecker.OTI);
if (topScope == null) {
regenerateGlobalTypedScope(compiler, root.getParent());
} else {
compiler.getTypeRegistry().resolveTypesInScope(topScope);
}
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
patchGlobalTypedScope(compiler, scriptRoot);
}
}
/** A compiler pass that clears the global scope. */
class ClearTypedScope implements CompilerPass {
@Override
public void process(Node externs, Node root) {
clearTypedScope();
}
}
/** Checks global name usage. */
private final PassFactory checkGlobalNames =
new PassFactory("checkGlobalNames", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
// Create a global namespace for analysis by check passes.
// Note that this class does all heavy computation lazily,
// so it's OK to create it here.
namespaceForChecks = new GlobalNamespace(compiler, externs, jsRoot);
new CheckGlobalNames(compiler, options.checkGlobalNamesLevel)
.injectNamespace(namespaceForChecks).process(externs, jsRoot);
}
};
}
};
/** Checks that the code is ES5 strict compliant. */
private final PassFactory checkStrictMode =
new PassFactory("checkStrictMode", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new StrictModeCheck(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Process goog.tweak.getTweak() calls. */
private final PassFactory processTweaks = new PassFactory("processTweaks", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
new ProcessTweaks(compiler,
options.getTweakProcessing().shouldStrip(),
options.getTweakReplacements()).process(externs, jsRoot);
}
};
}
};
/** Override @define-annotated constants. */
private final PassFactory processDefines = new PassFactory("processDefines", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
HashMap<String, Node> replacements = new HashMap<>();
replacements.putAll(compiler.getDefaultDefineValues());
replacements.putAll(getAdditionalReplacements(options));
replacements.putAll(options.getDefineReplacements());
new ProcessDefines(compiler, ImmutableMap.copyOf(replacements), !options.checksOnly)
.injectNamespace(namespaceForChecks).process(externs, jsRoot);
}
};
}
@Override
public FeatureSet featureSet() {
return ES8_MODULES;
}
};
/**
* Strips code for smaller compiled code. This is useful for removing debug
* statements to prevent leaking them publicly.
*/
private final PassFactory stripCode = new PassFactory("stripCode", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
CompilerOptions options = compiler.getOptions();
StripCode pass = new StripCode(compiler, options.stripTypes, options.stripNameSuffixes,
options.stripTypePrefixes, options.stripNamePrefixes);
if (options.getTweakProcessing().shouldStrip()) {
pass.enableTweakStripping();
}
pass.process(externs, jsRoot);
}
};
}
};
/** Release references to data that is only needed during checks. */
final PassFactory garbageCollectChecks =
new HotSwapPassFactory("garbageCollectChecks") {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new HotSwapCompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
// Kill the global namespace so that it can be garbage collected
// after all passes are through with it.
namespaceForChecks = null;
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
process(null, null);
}
};
}
@Override
public FeatureSet featureSet() {
return FeatureSet.latest();
}
};
/** Checks that all constants are not modified */
private final PassFactory checkConsts = new PassFactory("checkConsts", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ConstCheck(compiler);
}
@Override
public FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Checks that the arguments are constants */
private final PassFactory checkConstParams =
new PassFactory(PassNames.CHECK_CONST_PARAMS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ConstParamCheck(compiler);
}
@Override
public FeatureSet featureSet() {
return ES5;
}
};
/** Computes the names of functions for later analysis. */
private final PassFactory computeFunctionNames =
new PassFactory("computeFunctionNames", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
CollectFunctionNames pass = new CollectFunctionNames(compiler);
pass.process(externs, root);
compiler.setFunctionNames(pass.getFunctionNames());
}
};
}
@Override
public FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Inserts run-time type assertions for debugging. */
private final PassFactory runtimeTypeCheck =
new PassFactory(PassNames.RUNTIME_TYPE_CHECK, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new RuntimeTypeCheck(compiler, options.runtimeTypeCheckLogFunction);
}
};
/** Generates unique ids. */
private final PassFactory replaceIdGenerators =
new PassFactory(PassNames.REPLACE_ID_GENERATORS, true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
ReplaceIdGenerators pass =
new ReplaceIdGenerators(
compiler,
options.idGenerators,
options.generatePseudoNames,
options.idGeneratorsMapSerialized,
options.xidHashFunction);
pass.process(externs, root);
compiler.setIdGeneratorMap(pass.getSerializedIdMappings());
}
};
}
};
/** Replace strings. */
private final PassFactory replaceStrings = new PassFactory("replaceStrings", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
ReplaceStrings pass = new ReplaceStrings(
compiler,
options.replaceStringsPlaceholderToken,
options.replaceStringsFunctionDescriptions,
options.replaceStringsReservedStrings,
options.replaceStringsInputMap);
pass.process(externs, root);
compiler.setStringMap(pass.getStringMap());
}
};
}
};
/** Optimizes the "arguments" array. */
private final PassFactory optimizeArgumentsArray =
new PassFactory(PassNames.OPTIMIZE_ARGUMENTS_ARRAY, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new OptimizeArgumentsArray(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Remove variables set to goog.abstractMethod. */
private final PassFactory closureCodeRemoval =
new PassFactory("closureCodeRemoval", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new ClosureCodeRemoval(compiler, options.removeAbstractMethods,
options.removeClosureAsserts);
}
};
/** Special case optimizations for closure functions. */
private final PassFactory closureOptimizePrimitives =
new PassFactory("closureOptimizePrimitives", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new ClosureOptimizePrimitives(
compiler,
compiler.getOptions().propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED,
compiler.getOptions().getLanguageOut().toFeatureSet().contains(FeatureSet.ES6));
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Puts global symbols into a single object. */
private final PassFactory rescopeGlobalSymbols =
new PassFactory("rescopeGlobalSymbols", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new RescopeGlobalSymbols(
compiler,
options.renamePrefixNamespace,
options.renamePrefixNamespaceAssumeCrossModuleNames);
}
};
/** Collapses names in the global scope. */
private final PassFactory collapseProperties =
new PassFactory(PassNames.COLLAPSE_PROPERTIES, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CollapseProperties(compiler);
}
};
/** Rewrite properties as variables. */
private final PassFactory collapseObjectLiterals =
new PassFactory(PassNames.COLLAPSE_OBJECT_LITERALS, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InlineObjectLiterals(compiler, compiler.getUniqueNameIdSupplier());
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Disambiguate property names based on the coding convention. */
private final PassFactory disambiguatePrivateProperties =
new PassFactory(PassNames.DISAMBIGUATE_PRIVATE_PROPERTIES, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new DisambiguatePrivateProperties(compiler);
}
};
/** Disambiguate property names based on type information. */
private final PassFactory disambiguateProperties =
new PassFactory(PassNames.DISAMBIGUATE_PROPERTIES, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new DisambiguateProperties(compiler, options.propertyInvalidationErrors);
}
};
/** Chain calls to functions that return this. */
private final PassFactory chainCalls =
new PassFactory(PassNames.CHAIN_CALLS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ChainCalls(compiler);
}
};
/** Rewrite instance methods as static methods, to make them easier to inline. */
private final PassFactory devirtualizePrototypeMethods =
new PassFactory(PassNames.DEVIRTUALIZE_PROTOTYPE_METHODS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new DevirtualizePrototypeMethods(compiler);
}
};
/**
* Optimizes unused function arguments, unused return values, and inlines constant parameters.
* Also runs RemoveUnusedVars.
*/
private final PassFactory optimizeCalls =
new PassFactory(PassNames.OPTIMIZE_CALLS, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
OptimizeCalls passes = new OptimizeCalls(compiler);
if (options.optimizeReturns) {
// Remove unused return values.
passes.addPass(new OptimizeReturns(compiler));
}
if (options.optimizeParameters) {
// Remove all parameters that are constants or unused.
passes.addPass(new OptimizeParameters(compiler));
}
return passes;
}
};
/**
* Look for function calls that are pure, and annotate them
* that way.
*/
private final PassFactory markPureFunctions =
new PassFactory("markPureFunctions", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new PureFunctionIdentifier.Driver(
compiler, options.debugFunctionSideEffectsPath);
}
};
/** Look for function calls that have no side effects, and annotate them that way. */
private final PassFactory markNoSideEffectCalls =
new PassFactory(PassNames.MARK_NO_SIDE_EFFECT_CALLS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new MarkNoSideEffectCalls(compiler);
}
};
/** Inlines variables heuristically. */
private final PassFactory inlineVariables =
new PassFactory(PassNames.INLINE_VARIABLES, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
InlineVariables.Mode mode;
if (options.inlineVariables) {
mode = InlineVariables.Mode.ALL;
} else if (options.inlineLocalVariables) {
mode = InlineVariables.Mode.LOCALS_ONLY;
} else {
throw new IllegalStateException("No variable inlining option set.");
}
return new InlineVariables(compiler, mode, true);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Inlines variables that are marked as constants. */
private final PassFactory inlineConstants =
new PassFactory("inlineConstants", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InlineVariables(compiler, InlineVariables.Mode.CONSTANTS_ONLY, true);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Use data flow analysis to remove dead branches. */
private final PassFactory removeUnreachableCode =
new PassFactory(PassNames.REMOVE_UNREACHABLE_CODE, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new UnreachableCodeElimination(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8;
}
};
/**
* Use data flow analysis to remove dead branches.
*/
private final PassFactory removeUnusedPolyfills =
new PassFactory("removeUnusedPolyfills", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new RemoveUnusedPolyfills(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Remove prototype properties that do not appear to be used. */
private final PassFactory removeUnusedPrototypeProperties =
new PassFactory(PassNames.REMOVE_UNUSED_PROTOTYPE_PROPERTIES, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new RemoveUnusedPrototypeProperties(
compiler,
options.removeUnusedPrototypePropertiesInExterns,
!options.removeUnusedVars);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Remove prototype properties that do not appear to be used. */
private final PassFactory removeUnusedClassProperties =
new PassFactory(PassNames.REMOVE_UNUSED_CLASS_PROPERTIES, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new RemoveUnusedClassProperties(
compiler, options.removeUnusedConstructorProperties);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
private final PassFactory initNameAnalyzeReport = new PassFactory("initNameAnalyzeReport", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
NameAnalyzer.createEmptyReport(compiler, options.reportPath);
}
};
}
@Override
protected FeatureSet featureSet() {
return FeatureSet.latest();
}
};
/**
* Process smart name processing - removes unused classes and does referencing starting with
* minimum set of names.
*/
private final PassFactory extraSmartNamePass =
new PassFactory(PassNames.SMART_NAME_PASS, true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new NameAnalyzer(compiler, true, options.reportPath);
}
@Override
public FeatureSet featureSet() {
return ES5;
}
};
private final PassFactory smartNamePass =
new PassFactory(PassNames.SMART_NAME_PASS, true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new NameAnalyzer(compiler, true, options.reportPath);
}
@Override
public FeatureSet featureSet() {
return ES5;
}
};
private final PassFactory smartNamePass2 =
new PassFactory(PassNames.SMART_NAME_PASS, true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new NameAnalyzer(compiler, true, null);
}
@Override
public FeatureSet featureSet() {
return ES5;
}
};
/** Inlines simple methods, like getters */
private final PassFactory inlineSimpleMethods =
new PassFactory("inlineSimpleMethods", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InlineSimpleMethods(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES5;
}
};
/** Kills dead assignments. */
private final PassFactory deadAssignmentsElimination =
new PassFactory(PassNames.DEAD_ASSIGNMENT_ELIMINATION, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new DeadAssignmentsElimination(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Kills dead property assignments. */
private final PassFactory deadPropertyAssignmentElimination =
new PassFactory("deadPropertyAssignmentElimination", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new DeadPropertyAssignmentElimination(compiler);
}
@Override
public FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Inlines function calls. */
private final PassFactory inlineFunctions =
new PassFactory(PassNames.INLINE_FUNCTIONS, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InlineFunctions(
compiler,
compiler.getUniqueNameIdSupplier(),
options.inlineFunctions,
options.inlineLocalFunctions,
true,
options.assumeStrictThis() || options.expectStrictModeInput(),
options.assumeClosuresOnlyCaptureReferences,
options.maxFunctionSizeAfterInlining);
}
@Override
public FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Inlines constant properties. */
private final PassFactory inlineProperties =
new PassFactory(PassNames.INLINE_PROPERTIES, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InlineProperties(compiler);
}
};
private PassFactory getRemoveUnusedVars(String name, final boolean modifyCallSites) {
return getRemoveUnusedVars(name, modifyCallSites, false /* isOneTimePass */);
}
private PassFactory lastRemoveUnusedVars() {
return getRemoveUnusedVars(PassNames.REMOVE_UNUSED_VARS, false, true /* isOneTimePass */);
}
private PassFactory getRemoveUnusedVars(
String name, final boolean modifyCallSites, boolean isOneTimePass) {
/** Removes variables that are never used. */
return new PassFactory(name, isOneTimePass) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
boolean removeOnlyLocals = options.removeUnusedLocalVars && !options.removeUnusedVars;
boolean preserveAnonymousFunctionNames =
options.anonymousFunctionNaming != AnonymousFunctionNamingPolicy.OFF;
return new RemoveUnusedVars(
compiler,
!removeOnlyLocals,
preserveAnonymousFunctionNames,
modifyCallSites);
}
@Override
public FeatureSet featureSet() {
return ES5;
}
};
}
/** Move global symbols to a deeper common module */
private final PassFactory crossModuleCodeMotion =
new PassFactory(PassNames.CROSS_MODULE_CODE_MOTION, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CrossModuleCodeMotion(
compiler,
compiler.getModuleGraph(),
options.parentModuleCanSeeSymbolsDeclaredInChildren);
}
};
/** Move methods to a deeper common module */
private final PassFactory crossModuleMethodMotion =
new PassFactory(PassNames.CROSS_MODULE_METHOD_MOTION, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CrossModuleMethodMotion(
compiler,
compiler.getCrossModuleIdGenerator(),
// Only move properties in externs if we're not treating
// them as exports.
options.removeUnusedPrototypePropertiesInExterns,
options.crossModuleCodeMotionNoStubMethods);
}
};
/** A data-flow based variable inliner. */
private final PassFactory flowSensitiveInlineVariables =
new PassFactory(PassNames.FLOW_SENSITIVE_INLINE_VARIABLES, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new FlowSensitiveInlineVariables(compiler);
}
@Override
public FeatureSet featureSet() {
return ES5;
}
};
/** Uses register-allocation algorithms to use fewer variables. */
private final PassFactory coalesceVariableNames =
new PassFactory(PassNames.COALESCE_VARIABLE_NAMES, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CoalesceVariableNames(compiler, options.generatePseudoNames);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Some simple, local collapses (e.g., {@code var x; var y;} becomes {@code var x,y;}. */
private final PassFactory exploitAssign =
new PassFactory(PassNames.EXPLOIT_ASSIGN, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new PeepholeOptimizationsPass(compiler, getName(), new ExploitAssigns());
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Some simple, local collapses (e.g., {@code var x; var y;} becomes {@code var x,y;}. */
private final PassFactory collapseVariableDeclarations =
new PassFactory(PassNames.COLLAPSE_VARIABLE_DECLARATIONS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CollapseVariableDeclarations(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Extracts common sub-expressions. */
private final PassFactory extractPrototypeMemberDeclarations =
new PassFactory(PassNames.EXTRACT_PROTOTYPE_MEMBER_DECLARATIONS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
Pattern pattern;
switch (options.extractPrototypeMemberDeclarations) {
case USE_GLOBAL_TEMP:
pattern = Pattern.USE_GLOBAL_TEMP;
break;
case USE_IIFE:
pattern = Pattern.USE_IIFE;
break;
default:
throw new IllegalStateException("unexpected");
}
return new ExtractPrototypeMemberDeclarations(compiler, pattern);
}
};
/** Rewrites common function definitions to be more compact. */
private final PassFactory rewriteFunctionExpressions =
new PassFactory(PassNames.REWRITE_FUNCTION_EXPRESSIONS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new FunctionRewriter(compiler);
}
@Override
protected FeatureSet featureSet() {
return FeatureSet.latest();
}
};
/** Collapses functions to not use the VAR keyword. */
private final PassFactory collapseAnonymousFunctions =
new PassFactory(PassNames.COLLAPSE_ANONYMOUS_FUNCTIONS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CollapseAnonymousFunctions(compiler);
}
};
/** Moves function declarations to the top, to simulate actual hoisting. */
private final PassFactory moveFunctionDeclarations =
new PassFactory(PassNames.MOVE_FUNCTION_DECLARATIONS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new MoveFunctionDeclarations(compiler);
}
};
private final PassFactory nameUnmappedAnonymousFunctions =
new PassFactory(PassNames.NAME_ANONYMOUS_FUNCTIONS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new NameAnonymousFunctions(compiler);
}
};
private final PassFactory nameMappedAnonymousFunctions =
new PassFactory(PassNames.NAME_ANONYMOUS_FUNCTIONS, true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
NameAnonymousFunctionsMapped naf =
new NameAnonymousFunctionsMapped(
compiler, options.inputAnonymousFunctionNamingMap);
naf.process(externs, root);
compiler.setAnonymousFunctionNameMap(naf.getFunctionMap());
}
};
}
};
/**
* Alias string literals with global variables, to avoid creating lots of
* transient objects.
*/
private final PassFactory aliasStrings = new PassFactory("aliasStrings", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new AliasStrings(
compiler,
compiler.getModuleGraph(),
options.aliasAllStrings ? null : options.aliasableStrings,
options.aliasStringsBlacklist,
options.outputJsStringUsage);
}
};
/** Handling for the ObjectPropertyString primitive. */
private final PassFactory objectPropertyStringPostprocess =
new PassFactory("ObjectPropertyStringPostprocess", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ObjectPropertyStringPostprocess(compiler);
}
};
/**
* Renames properties so that the two properties that never appear on the same object get the same
* name.
*/
private final PassFactory ambiguateProperties =
new PassFactory(PassNames.AMBIGUATE_PROPERTIES, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new AmbiguateProperties(
compiler,
options.getPropertyReservedNamingFirstChars(),
options.getPropertyReservedNamingNonFirstChars());
}
};
/** Mark the point at which the normalized AST assumptions no longer hold. */
private final PassFactory markUnnormalized =
new PassFactory("markUnnormalized", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
compiler.setLifeCycleStage(LifeCycleStage.RAW);
}
};
}
@Override
protected FeatureSet featureSet() {
return FeatureSet.latest();
}
};
private final PassFactory normalize =
new PassFactory(PassNames.NORMALIZE, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new Normalize(compiler, false);
}
@Override
protected FeatureSet featureSet() {
// TODO(johnlenz): Update this and gatherRawExports to latest()
return ES8_MODULES;
}
};
private final PassFactory externExports =
new PassFactory(PassNames.EXTERN_EXPORTS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ExternExportsPass(compiler);
}
};
/** Denormalize the AST for code generation. */
private final PassFactory denormalize = new PassFactory("denormalize", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new Denormalize(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Inverting name normalization. */
private final PassFactory invertContextualRenaming =
new PassFactory("invertContextualRenaming", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return MakeDeclaredNamesUnique.getContextualRenameInverter(compiler);
}
};
/** Renames properties. */
private final PassFactory renameProperties =
new PassFactory("renameProperties", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
checkState(options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED);
final VariableMap prevPropertyMap = options.inputPropertyMap;
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
RenameProperties rprop =
new RenameProperties(
compiler,
options.generatePseudoNames,
prevPropertyMap,
options.getPropertyReservedNamingFirstChars(),
options.getPropertyReservedNamingNonFirstChars(),
options.nameGenerator);
rprop.process(externs, root);
compiler.setPropertyMap(rprop.getPropertyMap());
}
};
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Renames variables. */
private final PassFactory renameVars = new PassFactory("renameVars", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
final VariableMap prevVariableMap = options.inputVariableMap;
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
compiler.setVariableMap(runVariableRenaming(
compiler, prevVariableMap, externs, root));
}
};
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
private VariableMap runVariableRenaming(
AbstractCompiler compiler, VariableMap prevVariableMap,
Node externs, Node root) {
char[] reservedChars =
options.anonymousFunctionNaming.getReservedCharacters();
boolean preserveAnonymousFunctionNames =
options.anonymousFunctionNaming != AnonymousFunctionNamingPolicy.OFF;
Set<String> reservedNames = new HashSet<>();
if (options.renamePrefixNamespace != null) {
// don't use the prefix name as a global symbol.
reservedNames.add(options.renamePrefixNamespace);
}
reservedNames.addAll(compiler.getExportedNames());
reservedNames.addAll(ParserRunner.getReservedVars());
RenameVars rn = new RenameVars(
compiler,
options.renamePrefix,
options.variableRenaming == VariableRenamingPolicy.LOCAL,
preserveAnonymousFunctionNames,
options.generatePseudoNames,
options.shadowVariables,
options.preferStableNames,
prevVariableMap,
reservedChars,
reservedNames,
options.nameGenerator);
rn.process(externs, root);
return rn.getVariableMap();
}
/** Renames labels */
private final PassFactory renameLabels =
new PassFactory("renameLabels", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new RenameLabels(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Convert bracket access to dot access */
private final PassFactory convertToDottedProperties =
new PassFactory(PassNames.CONVERT_TO_DOTTED_PROPERTIES, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ConvertToDottedProperties(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
private final PassFactory checkAstValidity =
new PassFactory("checkAstValidity", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new AstValidator(compiler);
}
@Override
protected FeatureSet featureSet() {
return FeatureSet.latest();
}
};
/** Checks that all variables are defined. */
private final PassFactory varCheckValidity =
new PassFactory("varCheckValidity", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new VarCheck(compiler, true);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Adds instrumentations according to an instrumentation template. */
private final PassFactory instrumentFunctions =
new PassFactory("instrumentFunctions", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new InstrumentFunctions(
compiler, compiler.getFunctionNames(),
options.instrumentationTemplate, options.appNameStr);
}
};
private final PassFactory instrumentForCodeCoverage =
new PassFactory("instrumentForCodeCoverage", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
// TODO(johnlenz): make global instrumentation an option
if (options.instrumentBranchCoverage) {
return new CoverageInstrumentationPass(
compiler, CoverageReach.CONDITIONAL, InstrumentOption.BRANCH_ONLY);
} else {
return new CoverageInstrumentationPass(compiler, CoverageReach.CONDITIONAL);
}
}
};
/** Extern property names gathering pass. */
private final PassFactory gatherExternProperties =
new PassFactory("gatherExternProperties", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new GatherExternProperties(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/**
* Runs custom passes that are designated to run at a particular time.
*/
private PassFactory getCustomPasses(
final CustomPassExecutionTime executionTime) {
return new PassFactory("runCustomPasses", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return runInSerial(options.customPasses.get(executionTime));
}
};
}
/** Create a compiler pass that runs the given passes in serial. */
private static CompilerPass runInSerial(
final Collection<CompilerPass> passes) {
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
for (CompilerPass pass : passes) {
pass.process(externs, root);
}
}
};
}
@VisibleForTesting
static Map<String, Node> getAdditionalReplacements(
CompilerOptions options) {
Map<String, Node> additionalReplacements = new HashMap<>();
if (options.markAsCompiled || options.closurePass) {
additionalReplacements.put(COMPILED_CONSTANT_NAME, IR.trueNode());
}
if (options.closurePass && options.locale != null) {
additionalReplacements.put(CLOSURE_LOCALE_CONSTANT_NAME,
IR.string(options.locale));
}
return additionalReplacements;
}
/** Rewrites Polymer({}) */
private final HotSwapPassFactory polymerPass =
new HotSwapPassFactory("polymerPass") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new PolymerPass(
compiler,
compiler.getOptions().polymerVersion,
compiler.getOptions().propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
private final PassFactory chromePass = new PassFactory("chromePass", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ChromePass(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Rewrites the super accessors calls to support Dart Dev Compiler output. */
private final HotSwapPassFactory dartSuperAccessorsPass =
new HotSwapPassFactory("dartSuperAccessorsPass") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new DartSuperAccessorsPass(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Rewrites J2CL constructs to be more optimizable. */
private final PassFactory j2clConstantHoisterPass =
new PassFactory("j2clConstantHoisterPass", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new J2clConstantHoisterPass(compiler);
}
};
/** Optimizes J2CL clinit methods. */
private final PassFactory j2clClinitPass =
new PassFactory("j2clClinitPass", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
List<Node> changedScopeNodes = compiler.getChangedScopeNodesForPass(getName());
return new J2clClinitPrunerPass(compiler, changedScopeNodes);
}
};
/** Rewrites J2CL constructs to be more optimizable. */
private final PassFactory j2clPropertyInlinerPass =
new PassFactory("j2clES6Pass", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new J2clPropertyInlinerPass(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Rewrites J2CL constructs to be more optimizable. */
private final PassFactory j2clPass =
new PassFactory("j2clPass", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new J2clPass(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
private final PassFactory j2clAssertRemovalPass =
new PassFactory("j2clAssertRemovalPass", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new J2clAssertRemovalPass(compiler);
}
};
private final PassFactory j2clSourceFileChecker =
new PassFactory("j2clSourceFileChecker", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new J2clSourceFileChecker(compiler);
}
@Override
protected FeatureSet featureSet() {
return FeatureSet.latest();
}
};
private final PassFactory j2clChecksPass =
new PassFactory("j2clChecksPass", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new J2clChecksPass(compiler);
}
};
private final PassFactory checkConformance =
new PassFactory("checkConformance", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CheckConformance(
compiler, ImmutableList.copyOf(options.getConformanceConfigs()));
}
};
/** Optimizations that output ES6 features. */
private final PassFactory optimizeToEs6 =
new PassFactory("optimizeToEs6", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new SubstituteEs6Syntax(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Rewrites goog.module in whitespace only mode */
private final HotSwapPassFactory whitespaceWrapGoogModules =
new HotSwapPassFactory("whitespaceWrapGoogModules") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new WhitespaceWrapGoogModules(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
private final PassFactory removeSuperMethodsPass =
new PassFactory(PassNames.REMOVE_SUPER_METHODS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new RemoveSuperMethodsPass(compiler);
}
};
}
| src/com/google/javascript/jscomp/DefaultPassConfig.java | /*
* Copyright 2009 The Closure Compiler 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.javascript.jscomp;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.javascript.jscomp.PassFactory.createEmptyPass;
import static com.google.javascript.jscomp.parsing.parser.FeatureSet.ES5;
import static com.google.javascript.jscomp.parsing.parser.FeatureSet.ES6;
import static com.google.javascript.jscomp.parsing.parser.FeatureSet.ES7;
import static com.google.javascript.jscomp.parsing.parser.FeatureSet.ES8;
import static com.google.javascript.jscomp.parsing.parser.FeatureSet.ES8_MODULES;
import static com.google.javascript.jscomp.parsing.parser.FeatureSet.TYPESCRIPT;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage;
import com.google.javascript.jscomp.AbstractCompiler.MostRecentTypechecker;
import com.google.javascript.jscomp.CompilerOptions.ExtractPrototypeMemberDeclarationsMode;
import com.google.javascript.jscomp.CoverageInstrumentationPass.CoverageReach;
import com.google.javascript.jscomp.CoverageInstrumentationPass.InstrumentOption;
import com.google.javascript.jscomp.ExtractPrototypeMemberDeclarations.Pattern;
import com.google.javascript.jscomp.NodeTraversal.Callback;
import com.google.javascript.jscomp.PassFactory.HotSwapPassFactory;
import com.google.javascript.jscomp.lint.CheckArrayWithGoogObject;
import com.google.javascript.jscomp.lint.CheckDuplicateCase;
import com.google.javascript.jscomp.lint.CheckEmptyStatements;
import com.google.javascript.jscomp.lint.CheckEnums;
import com.google.javascript.jscomp.lint.CheckInterfaces;
import com.google.javascript.jscomp.lint.CheckJSDocStyle;
import com.google.javascript.jscomp.lint.CheckMissingSemicolon;
import com.google.javascript.jscomp.lint.CheckNullableReturn;
import com.google.javascript.jscomp.lint.CheckPrimitiveAsObject;
import com.google.javascript.jscomp.lint.CheckPrototypeProperties;
import com.google.javascript.jscomp.lint.CheckRequiresAndProvidesSorted;
import com.google.javascript.jscomp.lint.CheckUnusedLabels;
import com.google.javascript.jscomp.lint.CheckUselessBlocks;
import com.google.javascript.jscomp.parsing.ParserRunner;
import com.google.javascript.jscomp.parsing.parser.FeatureSet;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.Node;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Pass factories and meta-data for native JSCompiler passes.
*
* @author [email protected] (Nick Santos)
*
* NOTE(dimvar): this needs some non-trivial refactoring. The pass config should
* use as little state as possible. The recommended way for a pass to leave
* behind some state for a subsequent pass is through the compiler object.
* Any other state remaining here should only be used when the pass config is
* creating the list of checks and optimizations, not after passes have started
* executing. For example, the field namespaceForChecks should be in Compiler.
*/
public final class DefaultPassConfig extends PassConfig {
/* For the --mark-as-compiled pass */
private static final String COMPILED_CONSTANT_NAME = "COMPILED";
/* Constant name for Closure's locale */
private static final String CLOSURE_LOCALE_CONSTANT_NAME = "goog.LOCALE";
static final DiagnosticType CANNOT_USE_PROTOTYPE_AND_VAR =
DiagnosticType.error("JSC_CANNOT_USE_PROTOTYPE_AND_VAR",
"Rename prototypes and inline variables cannot be used together.");
// Miscellaneous errors.
private static final java.util.regex.Pattern GLOBAL_SYMBOL_NAMESPACE_PATTERN =
java.util.regex.Pattern.compile("^[a-zA-Z0-9$_]+$");
/**
* A global namespace to share across checking passes.
*/
private GlobalNamespace namespaceForChecks = null;
/**
* A symbol table for registering references that get removed during
* preprocessing.
*/
private PreprocessorSymbolTable preprocessorSymbolTable = null;
/**
* Global state necessary for doing hotswap recompilation of files with references to
* processed goog.modules.
*/
private ClosureRewriteModule.GlobalRewriteState moduleRewriteState = null;
/**
* Whether to protect "hidden" side-effects.
* @see CheckSideEffects
*/
private final boolean protectHiddenSideEffects;
public DefaultPassConfig(CompilerOptions options) {
super(options);
// The current approach to protecting "hidden" side-effects is to
// wrap them in a function call that is stripped later, this shouldn't
// be done in IDE mode where AST changes may be unexpected.
protectHiddenSideEffects = options != null && options.shouldProtectHiddenSideEffects();
}
GlobalNamespace getGlobalNamespace() {
return namespaceForChecks;
}
PreprocessorSymbolTable getPreprocessorSymbolTable() {
return preprocessorSymbolTable;
}
void maybeInitializePreprocessorSymbolTable(AbstractCompiler compiler) {
if (options.preservesDetailedSourceInfo()) {
Node root = compiler.getRoot();
if (preprocessorSymbolTable == null || preprocessorSymbolTable.getRootNode() != root) {
preprocessorSymbolTable = new PreprocessorSymbolTable(root);
}
}
}
void maybeInitializeModuleRewriteState() {
if (options.allowsHotswapReplaceScript() && this.moduleRewriteState == null) {
this.moduleRewriteState = new ClosureRewriteModule.GlobalRewriteState();
}
}
@Override
protected List<PassFactory> getTranspileOnlyPasses() {
List<PassFactory> passes = new ArrayList<>();
if (options.needsTranspilationFrom(TYPESCRIPT)) {
passes.add(convertEs6TypedToEs6);
}
if (options.needsTranspilationOf(FeatureSet.Feature.MODULES)) {
TranspilationPasses.addEs6ModulePass(passes);
}
passes.add(checkMissingSuper);
passes.add(checkVariableReferencesForTranspileOnly);
// It's important that the Dart super accessors pass run *before* es6ConvertSuper,
// which is a "late" ES6 pass. This is enforced in the assertValidOrder method.
if (options.dartPass && options.needsTranspilationFrom(ES6)) {
passes.add(dartSuperAccessorsPass);
}
if (options.needsTranspilationFrom(ES8)) {
TranspilationPasses.addEs2017Passes(passes);
passes.add(setFeatureSet(ES7));
}
if (options.needsTranspilationFrom(ES7)) {
TranspilationPasses.addEs2016Passes(passes);
passes.add(setFeatureSet(ES6));
}
// If the user has specified an input language of ES7 and an output language of ES6 or lower,
// we still need to run these "ES6" passes, because they do the transpilation of the ES7 **
// operator. If we split that into its own pass then the needsTranspilationFrom(ES7) call here
// can be removed.
if (options.needsTranspilationFrom(ES6) || options.needsTranspilationFrom(ES7)) {
TranspilationPasses.addEs6EarlyPasses(passes);
TranspilationPasses.addEs6LatePasses(passes);
TranspilationPasses.addPostCheckPasses(passes);
if (options.rewritePolyfills) {
TranspilationPasses.addRewritePolyfillPass(passes);
}
passes.add(setFeatureSet(options.getLanguageOut().toFeatureSet()));
}
if (!options.forceLibraryInjection.isEmpty()) {
passes.add(injectRuntimeLibraries);
}
assertAllOneTimePasses(passes);
assertValidOrderForChecks(passes);
return passes;
}
@Override
protected List<PassFactory> getWhitespaceOnlyPasses() {
List<PassFactory> passes = new ArrayList<>();
if (options.wrapGoogModulesForWhitespaceOnly) {
passes.add(whitespaceWrapGoogModules);
}
return passes;
}
private void addNewTypeCheckerPasses(List<PassFactory> checks, CompilerOptions options) {
if (options.getNewTypeInference()) {
checks.add(symbolTableForNewTypeInference);
checks.add(newTypeInference);
}
}
private void addOldTypeCheckerPasses(List<PassFactory> checks, CompilerOptions options) {
if (!options.allowsHotswapReplaceScript()) {
checks.add(inlineTypeAliases);
}
if (options.checkTypes || options.inferTypes) {
checks.add(resolveTypes);
checks.add(inferTypes);
if (options.checkTypes) {
checks.add(checkTypes);
} else {
checks.add(inferJsDocInfo);
}
// We assume that only clients who are going to re-compile, or do in-depth static analysis,
// will need the typed scope creator after the compile job.
if (!options.preservesDetailedSourceInfo() && !options.allowsHotswapReplaceScript()) {
checks.add(clearTypedScopePass);
}
}
}
@Override
protected List<PassFactory> getChecks() {
List<PassFactory> checks = new ArrayList<>();
if (options.shouldGenerateTypedExterns()) {
checks.add(closureGoogScopeAliases);
checks.add(closureRewriteClass);
checks.add(generateIjs);
checks.add(whitespaceWrapGoogModules);
return checks;
}
checks.add(createEmptyPass("beforeStandardChecks"));
// Note: ChromePass can rewrite invalid @type annotations into valid ones, so should run before
// JsDoc checks.
if (options.isChromePassEnabled()) {
checks.add(chromePass);
}
// Verify JsDoc annotations and check ES6 modules
checks.add(checkJsDocAndEs6Modules);
if (options.needsTranspilationFrom(TYPESCRIPT)) {
checks.add(convertEs6TypedToEs6);
}
if (options.enables(DiagnosticGroups.LINT_CHECKS)) {
checks.add(lintChecks);
}
if (options.closurePass && options.enables(DiagnosticGroups.LINT_CHECKS)) {
checks.add(checkRequiresAndProvidesSorted);
}
if (options.enables(DiagnosticGroups.MISSING_REQUIRE)
|| options.enables(DiagnosticGroups.STRICT_MISSING_REQUIRE)
|| options.enables(DiagnosticGroups.EXTRA_REQUIRE)) {
checks.add(checkRequires);
}
if (options.needsTranspilationOf(FeatureSet.Feature.MODULES)) {
TranspilationPasses.addEs6ModulePass(checks);
}
checks.add(checkVariableReferences);
checks.add(checkStrictMode);
if (options.closurePass) {
checks.add(closureCheckModule);
checks.add(closureRewriteModule);
}
if (options.declaredGlobalExternsOnWindow) {
checks.add(declaredGlobalExternsOnWindow);
}
checks.add(checkMissingSuper);
if (options.closurePass) {
checks.add(closureGoogScopeAliases);
checks.add(closureRewriteClass);
}
checks.add(checkSideEffects);
if (options.enables(DiagnosticGroups.MISSING_PROVIDE)) {
checks.add(checkProvides);
}
if (options.angularPass) {
checks.add(angularPass);
}
if (!options.generateExportsAfterTypeChecking && options.generateExports) {
checks.add(generateExports);
}
if (options.exportTestFunctions) {
checks.add(exportTestFunctions);
}
if (options.closurePass) {
checks.add(closurePrimitives);
}
// It's important that the PolymerPass run *after* the ClosurePrimitives and ChromePass rewrites
// and *before* the suspicious code checks. This is enforced in the assertValidOrder method.
if (options.polymerVersion != null) {
checks.add(polymerPass);
}
if (options.checkSuspiciousCode
|| options.enables(DiagnosticGroups.GLOBAL_THIS)
|| options.enables(DiagnosticGroups.DEBUGGER_STATEMENT_PRESENT)) {
checks.add(suspiciousCode);
}
if (options.closurePass && options.checkMissingGetCssNameLevel.isOn()) {
checks.add(closureCheckGetCssName);
}
if (options.syntheticBlockStartMarker != null) {
// This pass must run before the first fold constants pass.
checks.add(createSyntheticBlocks);
}
checks.add(checkVars);
if (options.inferConsts) {
checks.add(inferConsts);
}
if (options.computeFunctionSideEffects) {
checks.add(checkRegExp);
}
// This pass should run before types are assigned.
if (options.processObjectPropertyString) {
checks.add(objectPropertyStringPreprocess);
}
// It's important that the Dart super accessors pass run *before* es6ConvertSuper,
// which is a "late" ES6 pass. This is enforced in the assertValidOrder method.
if (options.dartPass && !options.getLanguageOut().toFeatureSet().contains(FeatureSet.ES6)) {
checks.add(dartSuperAccessorsPass);
}
if (options.needsTranspilationFrom(ES8)) {
TranspilationPasses.addEs2017Passes(checks);
checks.add(setFeatureSet(ES7));
}
if (options.needsTranspilationFrom(ES7) && !options.getTypeCheckEs6Natively()) {
TranspilationPasses.addEs2016Passes(checks);
checks.add(setFeatureSet(ES6));
}
if (options.needsTranspilationFrom(ES6)) {
checks.add(es6ExternsCheck);
TranspilationPasses.addEs6EarlyPasses(checks);
}
if (options.needsTranspilationFrom(ES6)) {
if (options.getTypeCheckEs6Natively()) {
TranspilationPasses.addEs6PassesBeforeNTI(checks);
} else {
TranspilationPasses.addEs6LatePasses(checks);
}
}
if (options.rewritePolyfills) {
TranspilationPasses.addRewritePolyfillPass(checks);
}
if (options.needsTranspilationFrom(ES6)) {
if (options.getTypeCheckEs6Natively()) {
checks.add(setFeatureSet(FeatureSet.NTI_SUPPORTED));
} else {
// TODO(bradfordcsmith): This marking is really about how variable scoping is handled during
// type checking. It should really be handled in a more direct fashion.
checks.add(setFeatureSet(options.getLanguageOut().toFeatureSet()));
}
}
if (!options.forceLibraryInjection.isEmpty()) {
checks.add(injectRuntimeLibraries);
}
if (options.needsTranspilationFrom(ES6)) {
checks.add(convertStaticInheritance);
}
// End of ES6 transpilation passes before NTI.
if (options.getTypeCheckEs6Natively()) {
if (!options.skipNonTranspilationPasses) {
checks.add(createEmptyPass(PassNames.BEFORE_TYPE_CHECKING));
addNewTypeCheckerPasses(checks, options);
}
if (options.needsTranspilationFrom(ES7)) {
TranspilationPasses.addEs2016Passes(checks);
checks.add(setFeatureSet(ES6));
}
if (options.needsTranspilationFrom(ES6)) {
TranspilationPasses.addEs6PassesAfterNTI(checks);
checks.add(setFeatureSet(options.getLanguageOut().toFeatureSet()));
}
}
if (!options.skipNonTranspilationPasses) {
addNonTranspilationCheckPasses(checks);
}
if (options.needsTranspilationFrom(ES6) && !options.inIncrementalCheckMode()) {
TranspilationPasses.addPostCheckPasses(checks);
}
// NOTE(dimvar): Tried to move this into the optimizations, but had to back off
// because the very first pass, normalization, rewrites the code in a way that
// causes loss of type information.
// So, I will convert the remaining optimizations to use TypeI and test that only
// in unit tests, not full builds. Once all passes are converted, then
// drop the OTI-after-NTI altogether.
// In addition, I will probably have a local edit of the repo that retains both
// types on Nodes, so I can test full builds on my machine. We can't check in such
// a change because it would greatly increase memory usage.
if (options.getNewTypeInference() && options.getRunOTIafterNTI()) {
addOldTypeCheckerPasses(checks, options);
}
// When options.generateExportsAfterTypeChecking is true, run GenerateExports after
// both type checkers, not just after NTI.
if (options.generateExportsAfterTypeChecking && options.generateExports) {
checks.add(generateExports);
}
checks.add(createEmptyPass(PassNames.AFTER_STANDARD_CHECKS));
assertAllOneTimePasses(checks);
assertValidOrderForChecks(checks);
return checks;
}
private void addNonTranspilationCheckPasses(List<PassFactory> checks) {
if (!options.getTypeCheckEs6Natively()) {
checks.add(createEmptyPass(PassNames.BEFORE_TYPE_CHECKING));
addNewTypeCheckerPasses(checks, options);
}
if (options.j2clPassMode.shouldAddJ2clPasses()) {
checks.add(j2clSourceFileChecker);
}
if (!options.getNewTypeInference()) {
addOldTypeCheckerPasses(checks, options);
}
if (!options.disables(DiagnosticGroups.CHECK_USELESS_CODE)
|| (!options.getNewTypeInference() && !options.disables(DiagnosticGroups.MISSING_RETURN))) {
checks.add(checkControlFlow);
}
// CheckAccessControls only works if check types is on.
if (options.isTypecheckingEnabled()
&& (!options.disables(DiagnosticGroups.ACCESS_CONTROLS)
|| options.enables(DiagnosticGroups.CONSTANT_PROPERTY))) {
checks.add(checkAccessControls);
}
if (!options.getNewTypeInference()) {
// NTI performs this check already
checks.add(checkConsts);
}
// Analyzer checks must be run after typechecking.
if (options.enables(DiagnosticGroups.ANALYZER_CHECKS) && options.isTypecheckingEnabled()) {
checks.add(analyzerChecks);
}
if (options.checkGlobalNamesLevel.isOn()) {
checks.add(checkGlobalNames);
}
if (!options.getConformanceConfigs().isEmpty()) {
checks.add(checkConformance);
}
// Replace 'goog.getCssName' before processing defines but after the
// other checks have been done.
if (options.closurePass) {
checks.add(closureReplaceGetCssName);
}
if (options.getTweakProcessing().isOn()) {
checks.add(processTweaks);
}
if (options.instrumentationTemplate != null || options.recordFunctionInformation) {
checks.add(computeFunctionNames);
}
if (options.checksOnly) {
// Run process defines here so that warnings/errors from that pass are emitted as part of
// checks.
// TODO(rluble): Split process defines into two stages, one that performs only checks to be
// run here, and the one that actually changes the AST that would run in the optimization
// phase.
checks.add(processDefines);
}
if (options.j2clPassMode.shouldAddJ2clPasses()) {
checks.add(j2clChecksPass);
}
}
@Override
protected List<PassFactory> getOptimizations() {
List<PassFactory> passes = new ArrayList<>();
if (options.skipNonTranspilationPasses) {
return passes;
}
passes.add(garbageCollectChecks);
// i18n
// If you want to customize the compiler to use a different i18n pass,
// you can create a PassConfig that calls replacePassFactory
// to replace this.
if (options.replaceMessagesWithChromeI18n) {
passes.add(replaceMessagesForChrome);
} else if (options.messageBundle != null) {
passes.add(replaceMessages);
}
// Defines in code always need to be processed.
passes.add(processDefines);
if (options.getTweakProcessing().shouldStrip()
|| !options.stripTypes.isEmpty()
|| !options.stripNameSuffixes.isEmpty()
|| !options.stripTypePrefixes.isEmpty()
|| !options.stripNamePrefixes.isEmpty()) {
passes.add(stripCode);
}
passes.add(normalize);
// Create extern exports after the normalize because externExports depends on unique names.
if (options.isExternExportsEnabled() || options.externExportsPath != null) {
passes.add(externExports);
}
// Gather property names in externs so they can be queried by the
// optimizing passes.
passes.add(gatherExternProperties);
if (options.instrumentForCoverage) {
passes.add(instrumentForCodeCoverage);
}
// TODO(dimvar): convert this pass to use NTI. Low priority since it's
// mostly unused. Converting it shouldn't block switching to NTI.
if (options.runtimeTypeCheck && !options.getNewTypeInference()) {
passes.add(runtimeTypeCheck);
}
// Inlines functions that perform dynamic accesses to static properties of parameters that are
// typed as {Function}. This turns a dynamic access to a static property of a class definition
// into a fully qualified access and in so doing enables better dead code stripping.
if (options.j2clPassMode.shouldAddJ2clPasses()) {
passes.add(j2clPass);
}
passes.add(createEmptyPass(PassNames.BEFORE_STANDARD_OPTIMIZATIONS));
if (options.replaceIdGenerators) {
passes.add(replaceIdGenerators);
}
// Optimizes references to the arguments variable.
if (options.optimizeArgumentsArray) {
passes.add(optimizeArgumentsArray);
}
// Abstract method removal works best on minimally modified code, and also
// only needs to run once.
if (options.closurePass && (options.removeAbstractMethods || options.removeClosureAsserts)) {
passes.add(closureCodeRemoval);
}
if (options.removeJ2clAsserts) {
passes.add(j2clAssertRemovalPass);
}
// Property disambiguation should only run once and needs to be done
// soon after type checking, both so that it can make use of type
// information and so that other passes can take advantage of the renamed
// properties.
if (options.disambiguatePrivateProperties) {
passes.add(disambiguatePrivateProperties);
}
assertAllOneTimePasses(passes);
// Inline aliases so that following optimizations don't have to understand alias chains.
if (options.collapseProperties) {
passes.add(aggressiveInlineAliases);
}
// Inline getters/setters in J2CL classes so that Object.defineProperties() calls (resulting
// from desugaring) don't block class stripping.
if (options.j2clPassMode.shouldAddJ2clPasses() && options.collapseProperties) {
// Relies on collapseProperties-triggered aggressive alias inlining.
passes.add(j2clPropertyInlinerPass);
}
// Collapsing properties can undo constant inlining, so we do this before
// the main optimization loop.
if (options.collapseProperties) {
passes.add(collapseProperties);
}
if (options.inferConsts) {
passes.add(inferConsts);
}
if (options.reportPath != null && options.smartNameRemoval) {
passes.add(initNameAnalyzeReport);
}
// TODO(mlourenco): Ideally this would be in getChecks() instead of getOptimizations(). But
// for that it needs to understand constant properties as well. See b/31301233#10.
// Needs to happen after inferConsts and collapseProperties. Detects whether invocations of
// the method goog.string.Const.from are done with an argument which is a string literal.
passes.add(checkConstParams);
// Running smart name removal before disambiguate properties allows disambiguate properties
// to be more effective if code that would prevent disambiguation can be removed.
if (options.extraSmartNameRemoval && options.smartNameRemoval) {
// These passes remove code that is dead because of define flags.
// If the dead code is weakly typed, running these passes before property
// disambiguation results in more code removal.
// The passes are one-time on purpose. (The later runs are loopable.)
if (options.foldConstants && (options.inlineVariables || options.inlineLocalVariables)) {
passes.add(earlyInlineVariables);
passes.add(earlyPeepholeOptimizations);
}
passes.add(extraSmartNamePass);
}
// RewritePolyfills is overly generous in the polyfills it adds. After type
// checking and early smart name removal, we can use the new type information
// to figure out which polyfilled prototype methods are actually called, and
// which were "false alarms" (i.e. calling a method of the same name on a
// user-provided class). We also remove any polyfills added by code that
// was smart-name-removed. This is a one-time pass, since it does not work
// after inlining - we do not attempt to aggressively remove polyfills used
// by code that is only flow-sensitively dead.
if (options.rewritePolyfills) {
passes.add(removeUnusedPolyfills);
}
// Property disambiguation should only run once and needs to be done
// soon after type checking, both so that it can make use of type
// information and so that other passes can take advantage of the renamed
// properties.
if (options.shouldDisambiguateProperties() && options.isTypecheckingEnabled()) {
passes.add(disambiguateProperties);
}
if (options.computeFunctionSideEffects) {
passes.add(markPureFunctions);
} else if (options.markNoSideEffectCalls) {
// TODO(user) The properties that this pass adds to CALL and NEW
// AST nodes increase the AST's in-memory size. Given that we are
// already running close to our memory limits, we could run into
// trouble if we end up using the @nosideeffects annotation a lot
// or compute @nosideeffects annotations by looking at function
// bodies. It should be easy to propagate @nosideeffects
// annotations as part of passes that depend on this property and
// store the result outside the AST (which would allow garbage
// collection once the pass is done).
passes.add(markNoSideEffectCalls);
}
if (options.chainCalls) {
passes.add(chainCalls);
}
if (options.smartNameRemoval || options.reportPath != null) {
passes.addAll(getCodeRemovingPasses());
passes.add(smartNamePass);
}
// This needs to come after the inline constants pass, which is run within
// the code removing passes.
if (options.closurePass) {
passes.add(closureOptimizePrimitives);
}
// ReplaceStrings runs after CollapseProperties in order to simplify
// pulling in values of constants defined in enums structures. It also runs
// after disambiguate properties and smart name removal so that it can
// correctly identify logging types and can replace references to string
// expressions.
if (!options.replaceStringsFunctionDescriptions.isEmpty()) {
passes.add(replaceStrings);
}
// TODO(user): This forces a first crack at crossModuleCodeMotion
// before devirtualization. Once certain functions are devirtualized,
// it confuses crossModuleCodeMotion ability to recognized that
// it is recursive.
// TODO(user): This is meant for a temporary quick win.
// In the future, we might want to improve our analysis in
// CrossModuleCodeMotion so we don't need to do this.
if (options.crossModuleCodeMotion) {
passes.add(crossModuleCodeMotion);
}
// Must run after ProcessClosurePrimitives, Es6ConvertSuper, and assertion removals, but
// before OptimizeCalls (specifically, OptimizeParameters) and DevirtualizePrototypeMethods.
if (options.removeSuperMethods) {
passes.add(removeSuperMethodsPass);
}
// Method devirtualization benefits from property disambiguation so
// it should run after that pass but before passes that do
// optimizations based on global names (like cross module code motion
// and inline functions). Smart Name Removal does better if run before
// this pass.
if (options.devirtualizePrototypeMethods) {
passes.add(devirtualizePrototypeMethods);
}
if (options.customPasses != null) {
passes.add(getCustomPasses(
CustomPassExecutionTime.BEFORE_OPTIMIZATION_LOOP));
}
passes.add(createEmptyPass(PassNames.BEFORE_MAIN_OPTIMIZATIONS));
// Because FlowSensitiveInlineVariables does not operate on the global scope due to compilation
// time, we need to run it once before InlineFunctions so that we don't miss inlining
// opportunities when a function will be inlined into the global scope.
if (options.inlineVariables || options.inlineLocalVariables) {
passes.add(flowSensitiveInlineVariables);
}
passes.addAll(getMainOptimizationLoop());
passes.add(createEmptyPass(PassNames.AFTER_MAIN_OPTIMIZATIONS));
passes.add(createEmptyPass("beforeModuleMotion"));
if (options.crossModuleCodeMotion) {
passes.add(crossModuleCodeMotion);
}
if (options.crossModuleMethodMotion) {
passes.add(crossModuleMethodMotion);
}
passes.add(createEmptyPass("afterModuleMotion"));
// Some optimizations belong outside the loop because running them more
// than once would either have no benefit or be incorrect.
if (options.customPasses != null) {
passes.add(getCustomPasses(
CustomPassExecutionTime.AFTER_OPTIMIZATION_LOOP));
}
if (options.inlineVariables || options.inlineLocalVariables) {
passes.add(flowSensitiveInlineVariables);
// After inlining some of the variable uses, some variables are unused.
// Re-run remove unused vars to clean it up.
if (options.removeUnusedVars || options.removeUnusedLocalVars) {
passes.add(lastRemoveUnusedVars());
}
}
// Running this pass again is required to have goog.events compile down to
// nothing when compiled on its own.
if (options.smartNameRemoval) {
passes.add(smartNamePass2);
}
if (options.collapseAnonymousFunctions) {
passes.add(collapseAnonymousFunctions);
}
// Move functions before extracting prototype member declarations.
if (options.moveFunctionDeclarations
// renamePrefixNamescape relies on moveFunctionDeclarations
// to preserve semantics.
|| options.renamePrefixNamespace != null) {
passes.add(moveFunctionDeclarations);
}
if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.MAPPED) {
passes.add(nameMappedAnonymousFunctions);
}
// The mapped name anonymous function pass makes use of information that
// the extract prototype member declarations pass removes so the former
// happens before the latter.
if (options.extractPrototypeMemberDeclarations != ExtractPrototypeMemberDeclarationsMode.OFF) {
passes.add(extractPrototypeMemberDeclarations);
}
if (options.shouldAmbiguateProperties()
&& options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED
&& options.isTypecheckingEnabled()) {
passes.add(ambiguateProperties);
}
if (options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED) {
passes.add(renameProperties);
}
// Reserve global names added to the "windows" object.
if (options.reserveRawExports) {
passes.add(gatherRawExports);
}
// This comes after property renaming because quoted property names must
// not be renamed.
if (options.convertToDottedProperties) {
passes.add(convertToDottedProperties);
}
// Property renaming must happen before this pass runs since this
// pass may convert dotted properties into quoted properties. It
// is beneficial to run before alias strings, alias keywords and
// variable renaming.
if (options.rewriteFunctionExpressions) {
passes.add(rewriteFunctionExpressions);
}
// This comes after converting quoted property accesses to dotted property
// accesses in order to avoid aliasing property names.
if (!options.aliasableStrings.isEmpty() || options.aliasAllStrings) {
passes.add(aliasStrings);
}
if (options.coalesceVariableNames) {
// Passes after this point can no longer depend on normalized AST
// assumptions because the code is marked as un-normalized
passes.add(coalesceVariableNames);
// coalesceVariables creates identity assignments and more redundant code
// that can be removed, rerun the peephole optimizations to clean them
// up.
if (options.foldConstants) {
passes.add(peepholeOptimizationsOnce);
}
}
// Passes after this point can no longer depend on normalized AST assumptions.
passes.add(markUnnormalized);
if (options.collapseVariableDeclarations) {
passes.add(exploitAssign);
passes.add(collapseVariableDeclarations);
}
// This pass works best after collapseVariableDeclarations.
passes.add(denormalize);
if (options.instrumentationTemplate != null) {
passes.add(instrumentFunctions);
}
if (options.variableRenaming != VariableRenamingPolicy.ALL) {
// If we're leaving some (or all) variables with their old names,
// then we need to undo any of the markers we added for distinguishing
// local variables ("x" -> "x$jscomp$1").
passes.add(invertContextualRenaming);
}
if (options.variableRenaming != VariableRenamingPolicy.OFF) {
passes.add(renameVars);
}
// This pass should run after names stop changing.
if (options.processObjectPropertyString) {
passes.add(objectPropertyStringPostprocess);
}
if (options.labelRenaming) {
passes.add(renameLabels);
}
if (options.foldConstants) {
passes.add(latePeepholeOptimizations);
}
if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.UNMAPPED) {
passes.add(nameUnmappedAnonymousFunctions);
}
if (protectHiddenSideEffects) {
passes.add(stripSideEffectProtection);
}
if (options.renamePrefixNamespace != null) {
if (!GLOBAL_SYMBOL_NAMESPACE_PATTERN.matcher(
options.renamePrefixNamespace).matches()) {
throw new IllegalArgumentException(
"Illegal character in renamePrefixNamespace name: "
+ options.renamePrefixNamespace);
}
passes.add(rescopeGlobalSymbols);
}
// Safety checks
passes.add(checkAstValidity);
passes.add(varCheckValidity);
// Raise to ES6, if allowed
if (options.getLanguageOut().toFeatureSet().contains(FeatureSet.ES6)) {
passes.add(optimizeToEs6);
}
assertValidOrderForOptimizations(passes);
return passes;
}
/** Creates the passes for the main optimization loop. */
private List<PassFactory> getMainOptimizationLoop() {
List<PassFactory> passes = new ArrayList<>();
if (options.inlineGetters) {
passes.add(inlineSimpleMethods);
}
passes.addAll(getCodeRemovingPasses());
if (options.inlineFunctions || options.inlineLocalFunctions) {
passes.add(inlineFunctions);
}
if (options.shouldInlineProperties() && options.isTypecheckingEnabled()) {
passes.add(inlineProperties);
}
boolean runOptimizeCalls = options.optimizeCalls
|| options.optimizeParameters
|| options.optimizeReturns;
if (options.removeUnusedVars || options.removeUnusedLocalVars) {
if (options.deadAssignmentElimination) {
passes.add(deadAssignmentsElimination);
// The Polymer source is usually not included in the compilation, but it creates
// getters/setters for many properties in compiled code. Dead property assignment
// elimination is only safe when it knows about getters/setters. Therefore, we skip
// it if the polymer pass is enabled.
if (options.polymerVersion == null) {
passes.add(deadPropertyAssignmentElimination);
}
}
if (!runOptimizeCalls) {
passes.add(getRemoveUnusedVars(PassNames.REMOVE_UNUSED_VARS, false));
}
}
if (runOptimizeCalls) {
passes.add(optimizeCalls);
// RemoveUnusedVars cleans up after optimizeCalls, so we run it here.
// It has a special name because otherwise PhaseOptimizer would change its
// position in the optimization loop.
if (options.optimizeCalls) {
passes.add(getRemoveUnusedVars("removeUnusedVars_afterOptimizeCalls", true));
}
}
if (options.j2clPassMode.shouldAddJ2clPasses()) {
passes.add(j2clConstantHoisterPass);
passes.add(j2clClinitPass);
}
assertAllLoopablePasses(passes);
return passes;
}
/** Creates several passes aimed at removing code. */
private List<PassFactory> getCodeRemovingPasses() {
List<PassFactory> passes = new ArrayList<>();
if (options.collapseObjectLiterals) {
passes.add(collapseObjectLiterals);
}
if (options.inlineVariables || options.inlineLocalVariables) {
passes.add(inlineVariables);
} else if (options.inlineConstantVars) {
passes.add(inlineConstants);
}
if (options.foldConstants) {
passes.add(peepholeOptimizations);
}
if (options.removeDeadCode) {
passes.add(removeUnreachableCode);
}
if (options.removeUnusedPrototypeProperties) {
passes.add(removeUnusedPrototypeProperties);
}
if (options.removeUnusedClassProperties) {
passes.add(removeUnusedClassProperties);
}
assertAllLoopablePasses(passes);
return passes;
}
private final HotSwapPassFactory checkSideEffects =
new HotSwapPassFactory("checkSideEffects") {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new CheckSideEffects(
compiler, options.checkSuspiciousCode, protectHiddenSideEffects);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Removes the "protector" functions that were added by CheckSideEffects. */
private final PassFactory stripSideEffectProtection =
new PassFactory(PassNames.STRIP_SIDE_EFFECT_PROTECTION, true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CheckSideEffects.StripProtection(compiler);
}
@Override
public FeatureSet featureSet() {
return FeatureSet.latest();
}
};
/** Checks for code that is probably wrong (such as stray expressions). */
private final HotSwapPassFactory suspiciousCode =
new HotSwapPassFactory("suspiciousCode") {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
List<Callback> sharedCallbacks = new ArrayList<>();
if (options.checkSuspiciousCode) {
sharedCallbacks.add(new CheckSuspiciousCode());
sharedCallbacks.add(new CheckDuplicateCase(compiler));
}
if (options.enables(DiagnosticGroups.GLOBAL_THIS)) {
sharedCallbacks.add(new CheckGlobalThis(compiler));
}
if (options.enables(DiagnosticGroups.DEBUGGER_STATEMENT_PRESENT)) {
sharedCallbacks.add(new CheckDebuggerStatement(compiler));
}
return combineChecks(compiler, sharedCallbacks);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Verify that all the passes are one-time passes. */
private static void assertAllOneTimePasses(List<PassFactory> passes) {
for (PassFactory pass : passes) {
checkState(pass.isOneTimePass());
}
}
/** Verify that all the passes are multi-run passes. */
private static void assertAllLoopablePasses(List<PassFactory> passes) {
for (PassFactory pass : passes) {
checkState(!pass.isOneTimePass());
}
}
/**
* Checks that {@code pass1} comes before {@code pass2} in {@code passList}, if both are present.
*/
private void assertPassOrder(
List<PassFactory> passList, PassFactory pass1, PassFactory pass2, String msg) {
int pass1Index = passList.indexOf(pass1);
int pass2Index = passList.indexOf(pass2);
if (pass1Index != -1 && pass2Index != -1) {
checkState(pass1Index < pass2Index, msg);
}
}
/**
* Certain checks need to run in a particular order. For example, the PolymerPass
* will not work correctly unless it runs after the goog.provide() processing.
* This enforces those constraints.
* @param checks The list of check passes
*/
private void assertValidOrderForChecks(List<PassFactory> checks) {
assertPassOrder(
checks,
chromePass,
checkJsDocAndEs6Modules,
"The ChromePass must run before after JsDoc and Es6 module checking.");
assertPassOrder(
checks,
closureRewriteModule,
processDefines,
"Must rewrite goog.module before processing @define's, so that @defines in modules work.");
assertPassOrder(
checks,
closurePrimitives,
polymerPass,
"The Polymer pass must run after goog.provide processing.");
assertPassOrder(
checks,
chromePass,
polymerPass,
"The Polymer pass must run after ChromePass processing.");
assertPassOrder(
checks,
polymerPass,
suspiciousCode,
"The Polymer pass must run before suspiciousCode processing.");
assertPassOrder(
checks,
dartSuperAccessorsPass,
TranspilationPasses.es6ConvertSuper,
"The Dart super accessors pass must run before ES6->ES3 super lowering.");
if (checks.contains(closureGoogScopeAliases)) {
checkState(
checks.contains(checkVariableReferences),
"goog.scope processing requires variable checking");
}
assertPassOrder(
checks,
checkVariableReferences,
closureGoogScopeAliases,
"Variable checking must happen before goog.scope processing.");
assertPassOrder(
checks,
TranspilationPasses.es6ConvertSuper,
removeSuperMethodsPass,
"Super-call method removal must run after Es6 super rewriting, "
+ "because Es6 super calls are matched on their post-processed form.");
assertPassOrder(
checks,
closurePrimitives,
removeSuperMethodsPass,
"Super-call method removal must run after Es6 super rewriting, "
+ "because Closure base calls are expected to be in post-processed form.");
assertPassOrder(
checks,
closureCodeRemoval,
removeSuperMethodsPass,
"Super-call method removal must run after closure code removal, because "
+ "removing assertions may make more super calls eligible to be stripped.");
}
/**
* Certain optimizations need to run in a particular order. For example, OptimizeCalls must run
* before RemoveSuperMethodsPass, because the former can invalidate assumptions in the latter.
* This enforces those constraints.
* @param optimizations The list of optimization passes
*/
private void assertValidOrderForOptimizations(List<PassFactory> optimizations) {
assertPassOrder(optimizations, removeSuperMethodsPass, optimizeCalls,
"RemoveSuperMethodsPass must run before OptimizeCalls.");
assertPassOrder(optimizations, removeSuperMethodsPass, devirtualizePrototypeMethods,
"RemoveSuperMethodsPass must run before DevirtualizePrototypeMethods.");
}
/** Checks that all constructed classes are goog.require()d. */
private final HotSwapPassFactory checkRequires =
new HotSwapPassFactory("checkMissingAndExtraRequires") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new CheckMissingAndExtraRequires(
compiler, CheckMissingAndExtraRequires.Mode.FULL_COMPILE);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Makes sure @constructor is paired with goog.provides(). */
private final HotSwapPassFactory checkProvides =
new HotSwapPassFactory("checkProvides") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new CheckProvides(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
private static final DiagnosticType GENERATE_EXPORTS_ERROR =
DiagnosticType.error(
"JSC_GENERATE_EXPORTS_ERROR",
"Exports can only be generated if export symbol/property functions are set.");
/** Verifies JSDoc annotations are used properly and checks for ES6 modules. */
private final HotSwapPassFactory checkJsDocAndEs6Modules =
new HotSwapPassFactory("checkJsDocAndEs6Modules") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
ImmutableList.Builder<Callback> callbacks =
ImmutableList.<Callback>builder()
.add(new CheckJSDoc(compiler))
.add(new Es6CheckModule(compiler));
return combineChecks(compiler, callbacks.build());
}
@Override
protected FeatureSet featureSet() {
return FeatureSet.latest();
}
};
/** Generates exports for @export annotations. */
private final PassFactory generateExports =
new PassFactory(PassNames.GENERATE_EXPORTS, true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
CodingConvention convention = compiler.getCodingConvention();
if (convention.getExportSymbolFunction() != null
&& convention.getExportPropertyFunction() != null) {
final GenerateExports pass =
new GenerateExports(
compiler,
options.exportLocalPropertyDefinitions,
convention.getExportSymbolFunction(),
convention.getExportPropertyFunction());
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
pass.process(externs, root);
compiler.addExportedNames(pass.getExportedVariableNames());
}
};
} else {
return new ErrorPass(compiler, GENERATE_EXPORTS_ERROR);
}
}
@Override
protected FeatureSet featureSet() {
return ES8;
}
};
private final PassFactory generateIjs =
new PassFactory("generateIjs", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ConvertToTypedInterface(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Generates exports for functions associated with JsUnit. */
private final PassFactory exportTestFunctions =
new PassFactory(PassNames.EXPORT_TEST_FUNCTIONS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
CodingConvention convention = compiler.getCodingConvention();
if (convention.getExportSymbolFunction() != null) {
return new ExportTestFunctions(
compiler,
convention.getExportSymbolFunction(),
convention.getExportPropertyFunction());
} else {
return new ErrorPass(compiler, GENERATE_EXPORTS_ERROR);
}
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Raw exports processing pass. */
private final PassFactory gatherRawExports =
new PassFactory(PassNames.GATHER_RAW_EXPORTS, true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
final GatherRawExports pass = new GatherRawExports(compiler);
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
pass.process(externs, root);
compiler.addExportedNames(pass.getExportedVariableNames());
}
};
}
@Override
public FeatureSet featureSet() {
// Should be FeatureSet.latest() since it's a trivial pass, but must match "normalize"
// TODO(johnlenz): Update this and normalize to latest()
return ES8_MODULES;
}
};
/** Closure pre-processing pass. */
private final HotSwapPassFactory closurePrimitives =
new HotSwapPassFactory("closurePrimitives") {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
maybeInitializePreprocessorSymbolTable(compiler);
final ProcessClosurePrimitives pass =
new ProcessClosurePrimitives(
compiler,
preprocessorSymbolTable,
options.brokenClosureRequiresLevel,
options.shouldPreservesGoogProvidesAndRequires());
return new HotSwapCompilerPass() {
@Override
public void process(Node externs, Node root) {
pass.process(externs, root);
compiler.addExportedNames(pass.getExportedVariableNames());
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
pass.hotSwapScript(scriptRoot, originalRoot);
}
};
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Process AngularJS-specific annotations. */
private final HotSwapPassFactory angularPass =
new HotSwapPassFactory(PassNames.ANGULAR_PASS) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new AngularPass(compiler);
}
@Override
public FeatureSet featureSet() {
return ES8_MODULES;
}
};
/**
* The default i18n pass. A lot of the options are not configurable, because ReplaceMessages has a
* lot of legacy logic.
*/
private final PassFactory replaceMessages =
new PassFactory(PassNames.REPLACE_MESSAGES, true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new ReplaceMessages(
compiler,
options.messageBundle,
/* warn about message dupes */
true,
/* allow messages with goog.getMsg */
JsMessage.Style.CLOSURE,
/* if we can't find a translation, don't worry about it. */
false);
}
@Override
public FeatureSet featureSet() {
return ES8_MODULES;
}
};
private final PassFactory replaceMessagesForChrome =
new PassFactory(PassNames.REPLACE_MESSAGES, true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new ReplaceMessagesForChrome(
compiler,
new GoogleJsMessageIdGenerator(options.tcProjectId),
/* warn about message dupes */
true,
/* allow messages with goog.getMsg */
JsMessage.Style.CLOSURE);
}
@Override
public FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Applies aliases and inlines goog.scope. */
private final HotSwapPassFactory closureGoogScopeAliases =
new HotSwapPassFactory("closureGoogScopeAliases") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
maybeInitializePreprocessorSymbolTable(compiler);
return new ScopedAliases(
compiler, preprocessorSymbolTable, options.getAliasTransformationHandler());
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
private final PassFactory injectRuntimeLibraries =
new PassFactory("InjectRuntimeLibraries", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new InjectRuntimeLibraries(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
private final PassFactory es6ExternsCheck =
new PassFactory("es6ExternsCheck", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new Es6ExternsCheck(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Desugars ES6_TYPED features into ES6 code. */
final HotSwapPassFactory convertEs6TypedToEs6 =
new HotSwapPassFactory("convertEs6Typed") {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new Es6TypedToEs6Converter(compiler);
}
@Override
protected FeatureSet featureSet() {
return TYPESCRIPT;
}
};
private final PassFactory convertStaticInheritance =
new PassFactory("Es6StaticInheritance", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new Es6ToEs3ClassSideInheritance(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES5;
}
};
private final PassFactory inlineTypeAliases =
new PassFactory(PassNames.INLINE_TYPE_ALIASES, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InlineAliases(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES6;
}
};
/** Inlines type aliases if they are explicitly or effectively const. */
private final PassFactory aggressiveInlineAliases =
new PassFactory("aggressiveInlineAliases", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new AggressiveInlineAliases(compiler);
}
};
private final PassFactory setFeatureSet(final FeatureSet featureSet) {
return new PassFactory("setFeatureSet:" + featureSet.version(), true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
compiler.setFeatureSet(featureSet);
}
};
}
@Override
public FeatureSet featureSet() {
return FeatureSet.latest();
}
};
}
private final PassFactory declaredGlobalExternsOnWindow =
new PassFactory(PassNames.DECLARED_GLOBAL_EXTERNS_ON_WINDOW, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new DeclaredGlobalExternsOnWindow(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Rewrites goog.defineClass */
private final HotSwapPassFactory closureRewriteClass =
new HotSwapPassFactory(PassNames.CLOSURE_REWRITE_CLASS) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new ClosureRewriteClass(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Checks of correct usage of goog.module */
private final HotSwapPassFactory closureCheckModule =
new HotSwapPassFactory("closureCheckModule") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new ClosureCheckModule(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Rewrites goog.module */
private final HotSwapPassFactory closureRewriteModule =
new HotSwapPassFactory("closureRewriteModule") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
maybeInitializePreprocessorSymbolTable(compiler);
maybeInitializeModuleRewriteState();
return new ClosureRewriteModule(compiler, preprocessorSymbolTable, moduleRewriteState);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Checks that CSS class names are wrapped in goog.getCssName */
private final PassFactory closureCheckGetCssName =
new PassFactory("closureCheckGetCssName", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CheckMissingGetCssName(
compiler,
options.checkMissingGetCssNameLevel,
options.checkMissingGetCssNameBlacklist);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/**
* Processes goog.getCssName. The cssRenamingMap is used to lookup
* replacement values for the classnames. If null, the raw class names are
* inlined.
*/
private final PassFactory closureReplaceGetCssName =
new PassFactory("closureReplaceGetCssName", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
Map<String, Integer> newCssNames = null;
if (options.gatherCssNames) {
newCssNames = new HashMap<>();
}
ReplaceCssNames pass = new ReplaceCssNames(
compiler,
newCssNames,
options.cssRenamingWhitelist);
pass.process(externs, jsRoot);
compiler.setCssNames(newCssNames);
}
};
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/**
* Creates synthetic blocks to prevent FoldConstants from moving code past markers in the source.
*/
private final PassFactory createSyntheticBlocks =
new PassFactory("createSyntheticBlocks", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CreateSyntheticBlocks(
compiler, options.syntheticBlockStartMarker, options.syntheticBlockEndMarker);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
private final PassFactory earlyPeepholeOptimizations =
new PassFactory("earlyPeepholeOptimizations", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
List<AbstractPeepholeOptimization> peepholeOptimizations = new ArrayList<>();
peepholeOptimizations.add(new PeepholeRemoveDeadCode());
if (compiler.getOptions().j2clPassMode.shouldAddJ2clPasses()) {
peepholeOptimizations.add(new J2clEqualitySameRewriterPass());
}
return new PeepholeOptimizationsPass(compiler, getName(), peepholeOptimizations);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
private final PassFactory earlyInlineVariables =
new PassFactory("earlyInlineVariables", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
InlineVariables.Mode mode;
if (options.inlineVariables) {
mode = InlineVariables.Mode.ALL;
} else if (options.inlineLocalVariables) {
mode = InlineVariables.Mode.LOCALS_ONLY;
} else {
throw new IllegalStateException("No variable inlining option set.");
}
return new InlineVariables(compiler, mode, true);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Various peephole optimizations. */
private static CompilerPass createPeepholeOptimizationsPass(
AbstractCompiler compiler, String passName) {
final boolean late = false;
final boolean useTypesForOptimization = compiler.getOptions().useTypesForLocalOptimization;
List<AbstractPeepholeOptimization> optimizations = new ArrayList<>();
optimizations.add(new MinimizeExitPoints(compiler));
optimizations.add(new PeepholeMinimizeConditions(late, useTypesForOptimization));
optimizations.add(new PeepholeSubstituteAlternateSyntax(late));
optimizations.add(new PeepholeReplaceKnownMethods(late, useTypesForOptimization));
optimizations.add(new PeepholeRemoveDeadCode());
if (compiler.getOptions().j2clPassMode.shouldAddJ2clPasses()) {
optimizations.add(new J2clEqualitySameRewriterPass());
}
optimizations.add(new PeepholeFoldConstants(late, useTypesForOptimization));
optimizations.add(new PeepholeCollectPropertyAssignments());
return new PeepholeOptimizationsPass(compiler, passName, optimizations);
}
/** Various peephole optimizations. */
private final PassFactory peepholeOptimizations =
new PassFactory(PassNames.PEEPHOLE_OPTIMIZATIONS, false /* oneTimePass */) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return createPeepholeOptimizationsPass(compiler, getName());
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Various peephole optimizations. */
private final PassFactory peepholeOptimizationsOnce =
new PassFactory(PassNames.PEEPHOLE_OPTIMIZATIONS, true /* oneTimePass */) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return createPeepholeOptimizationsPass(compiler, getName());
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Same as peepholeOptimizations but aggressively merges code together */
private final PassFactory latePeepholeOptimizations =
new PassFactory("latePeepholeOptimizations", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
final boolean late = true;
final boolean useTypesForOptimization = options.useTypesForLocalOptimization;
return new PeepholeOptimizationsPass(
compiler,
getName(),
new StatementFusion(options.aggressiveFusion),
new PeepholeRemoveDeadCode(),
new PeepholeMinimizeConditions(late, useTypesForOptimization),
new PeepholeSubstituteAlternateSyntax(late),
new PeepholeReplaceKnownMethods(late, useTypesForOptimization),
new PeepholeFoldConstants(late, useTypesForOptimization),
new PeepholeReorderConstantExpression());
}
};
/** Checks that all variables are defined. */
private final HotSwapPassFactory checkVars =
new HotSwapPassFactory(PassNames.CHECK_VARS) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new VarCheck(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Infers constants. */
private final PassFactory inferConsts =
new PassFactory(PassNames.INFER_CONSTS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InferConsts(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Checks for RegExp references. */
private final PassFactory checkRegExp =
new PassFactory(PassNames.CHECK_REG_EXP, true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
final CheckRegExp pass = new CheckRegExp(compiler);
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
pass.process(externs, root);
compiler.setHasRegExpGlobalReferences(pass.isGlobalRegExpPropertiesUsed());
}
};
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Checks that references to variables look reasonable. */
private final HotSwapPassFactory checkVariableReferencesForTranspileOnly =
new HotSwapPassFactory(PassNames.CHECK_VARIABLE_REFERENCES) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new VariableReferenceCheck(compiler, true);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Checks that references to variables look reasonable. */
private final HotSwapPassFactory checkVariableReferences =
new HotSwapPassFactory(PassNames.CHECK_VARIABLE_REFERENCES) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new VariableReferenceCheck(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Checks that references to variables look reasonable. */
private final HotSwapPassFactory checkMissingSuper =
new HotSwapPassFactory("checkMissingSuper") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new CheckMissingSuper(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Pre-process goog.testing.ObjectPropertyString. */
private final PassFactory objectPropertyStringPreprocess =
new PassFactory("ObjectPropertyStringPreprocess", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ObjectPropertyStringPreprocess(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Creates a typed scope and adds types to the type registry. */
final HotSwapPassFactory resolveTypes =
new HotSwapPassFactory(PassNames.RESOLVE_TYPES) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new GlobalTypeResolver(compiler);
}
};
/** Clears the typed scope when we're done. */
private final PassFactory clearTypedScopePass =
new PassFactory("clearTypedScopePass", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ClearTypedScope();
}
@Override
protected FeatureSet featureSet() {
return FeatureSet.latest();
}
};
/** Runs type inference. */
final HotSwapPassFactory inferTypes =
new HotSwapPassFactory(PassNames.INFER_TYPES) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new HotSwapCompilerPass() {
@Override
public void process(Node externs, Node root) {
checkNotNull(topScope);
checkNotNull(getTypedScopeCreator());
makeTypeInference(compiler).process(externs, root);
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
makeTypeInference(compiler).inferAllScopes(scriptRoot);
}
};
}
};
private final PassFactory symbolTableForNewTypeInference =
new PassFactory("GlobalTypeInfo", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new GlobalTypeInfoCollector(compiler);
}
@Override
protected FeatureSet featureSet() {
return FeatureSet.NTI_SUPPORTED;
}
};
private final PassFactory newTypeInference =
new PassFactory("NewTypeInference", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new NewTypeInference(compiler);
}
@Override
protected FeatureSet featureSet() {
return FeatureSet.NTI_SUPPORTED;
}
};
private final HotSwapPassFactory inferJsDocInfo =
new HotSwapPassFactory("inferJsDocInfo") {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new HotSwapCompilerPass() {
@Override
public void process(Node externs, Node root) {
checkNotNull(topScope);
checkNotNull(getTypedScopeCreator());
makeInferJsDocInfo(compiler).process(externs, root);
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
makeInferJsDocInfo(compiler).hotSwapScript(scriptRoot, originalRoot);
}
};
}
};
/** Checks type usage */
private final HotSwapPassFactory checkTypes =
new HotSwapPassFactory(PassNames.CHECK_TYPES) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new HotSwapCompilerPass() {
@Override
public void process(Node externs, Node root) {
checkNotNull(topScope);
checkNotNull(getTypedScopeCreator());
TypeCheck check = makeTypeCheck(compiler);
check.process(externs, root);
compiler.getErrorManager().setTypedPercent(check.getTypedPercent());
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
makeTypeCheck(compiler).check(scriptRoot, false);
}
};
}
};
/**
* Checks possible execution paths of the program for problems: missing return
* statements and dead code.
*/
private final HotSwapPassFactory checkControlFlow =
new HotSwapPassFactory("checkControlFlow") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
List<Callback> callbacks = new ArrayList<>();
if (!options.disables(DiagnosticGroups.CHECK_USELESS_CODE)) {
callbacks.add(new CheckUnreachableCode(compiler));
}
if (!options.getNewTypeInference() && !options.disables(DiagnosticGroups.MISSING_RETURN)) {
callbacks.add(new CheckMissingReturn(compiler));
}
return combineChecks(compiler, callbacks);
}
@Override
public FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Checks access controls. Depends on type-inference. */
private final HotSwapPassFactory checkAccessControls =
new HotSwapPassFactory("checkAccessControls") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new CheckAccessControls(
compiler, options.enforceAccessControlCodingConventions);
}
};
private final HotSwapPassFactory lintChecks =
new HotSwapPassFactory(PassNames.LINT_CHECKS) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
ImmutableList.Builder<Callback> callbacks =
ImmutableList.<Callback>builder()
.add(new CheckEmptyStatements(compiler))
.add(new CheckEnums(compiler))
.add(new CheckInterfaces(compiler))
.add(new CheckJSDocStyle(compiler))
.add(new CheckMissingSemicolon(compiler))
.add(new CheckPrimitiveAsObject(compiler))
.add(new CheckPrototypeProperties(compiler))
.add(new CheckUnusedLabels(compiler))
.add(new CheckUselessBlocks(compiler));
return combineChecks(compiler, callbacks.build());
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
private final HotSwapPassFactory analyzerChecks =
new HotSwapPassFactory(PassNames.ANALYZER_CHECKS) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
ImmutableList.Builder<Callback> callbacks = ImmutableList.<Callback>builder();
if (options.enables(DiagnosticGroups.ANALYZER_CHECKS_INTERNAL)) {
callbacks
.add(new CheckNullableReturn(compiler))
.add(new CheckArrayWithGoogObject(compiler))
.add(new ImplicitNullabilityCheck(compiler));
}
// These are grouped together for better execution efficiency.
if (options.enables(DiagnosticGroups.UNUSED_PRIVATE_PROPERTY)) {
callbacks.add(new CheckUnusedPrivateProperties(compiler));
}
return combineChecks(compiler, callbacks.build());
}
};
private final HotSwapPassFactory checkRequiresAndProvidesSorted =
new HotSwapPassFactory("checkRequiresAndProvidesSorted") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new CheckRequiresAndProvidesSorted(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Executes the given callbacks with a {@link CombinedCompilerPass}. */
private static HotSwapCompilerPass combineChecks(AbstractCompiler compiler,
List<Callback> callbacks) {
checkArgument(!callbacks.isEmpty());
return new CombinedCompilerPass(compiler, callbacks);
}
/** A compiler pass that resolves types in the global scope. */
class GlobalTypeResolver implements HotSwapCompilerPass {
private final AbstractCompiler compiler;
GlobalTypeResolver(AbstractCompiler compiler) {
this.compiler = compiler;
}
@Override
public void process(Node externs, Node root) {
// If NTI is enabled, erase the NTI types from the AST before adding the old types.
if (this.compiler.getOptions().getNewTypeInference()) {
NodeTraversal.traverseEs6(
this.compiler, root,
new NodeTraversal.AbstractPostOrderCallback(){
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
n.setTypeI(null);
}
});
this.compiler.clearTypeIRegistry();
}
this.compiler.setMostRecentTypechecker(MostRecentTypechecker.OTI);
if (topScope == null) {
regenerateGlobalTypedScope(compiler, root.getParent());
} else {
compiler.getTypeRegistry().resolveTypesInScope(topScope);
}
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
patchGlobalTypedScope(compiler, scriptRoot);
}
}
/** A compiler pass that clears the global scope. */
class ClearTypedScope implements CompilerPass {
@Override
public void process(Node externs, Node root) {
clearTypedScope();
}
}
/** Checks global name usage. */
private final PassFactory checkGlobalNames =
new PassFactory("checkGlobalNames", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
// Create a global namespace for analysis by check passes.
// Note that this class does all heavy computation lazily,
// so it's OK to create it here.
namespaceForChecks = new GlobalNamespace(compiler, externs, jsRoot);
new CheckGlobalNames(compiler, options.checkGlobalNamesLevel)
.injectNamespace(namespaceForChecks).process(externs, jsRoot);
}
};
}
};
/** Checks that the code is ES5 strict compliant. */
private final PassFactory checkStrictMode =
new PassFactory("checkStrictMode", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new StrictModeCheck(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Process goog.tweak.getTweak() calls. */
private final PassFactory processTweaks = new PassFactory("processTweaks", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
new ProcessTweaks(compiler,
options.getTweakProcessing().shouldStrip(),
options.getTweakReplacements()).process(externs, jsRoot);
}
};
}
};
/** Override @define-annotated constants. */
private final PassFactory processDefines = new PassFactory("processDefines", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
HashMap<String, Node> replacements = new HashMap<>();
replacements.putAll(compiler.getDefaultDefineValues());
replacements.putAll(getAdditionalReplacements(options));
replacements.putAll(options.getDefineReplacements());
new ProcessDefines(compiler, ImmutableMap.copyOf(replacements), !options.checksOnly)
.injectNamespace(namespaceForChecks).process(externs, jsRoot);
}
};
}
@Override
public FeatureSet featureSet() {
return ES8_MODULES;
}
};
/**
* Strips code for smaller compiled code. This is useful for removing debug
* statements to prevent leaking them publicly.
*/
private final PassFactory stripCode = new PassFactory("stripCode", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
CompilerOptions options = compiler.getOptions();
StripCode pass = new StripCode(compiler, options.stripTypes, options.stripNameSuffixes,
options.stripTypePrefixes, options.stripNamePrefixes);
if (options.getTweakProcessing().shouldStrip()) {
pass.enableTweakStripping();
}
pass.process(externs, jsRoot);
}
};
}
};
/** Release references to data that is only needed during checks. */
final PassFactory garbageCollectChecks =
new HotSwapPassFactory("garbageCollectChecks") {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new HotSwapCompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
// Kill the global namespace so that it can be garbage collected
// after all passes are through with it.
namespaceForChecks = null;
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
process(null, null);
}
};
}
@Override
public FeatureSet featureSet() {
return FeatureSet.latest();
}
};
/** Checks that all constants are not modified */
private final PassFactory checkConsts = new PassFactory("checkConsts", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ConstCheck(compiler);
}
@Override
public FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Checks that the arguments are constants */
private final PassFactory checkConstParams =
new PassFactory(PassNames.CHECK_CONST_PARAMS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ConstParamCheck(compiler);
}
@Override
public FeatureSet featureSet() {
return ES5;
}
};
/** Computes the names of functions for later analysis. */
private final PassFactory computeFunctionNames =
new PassFactory("computeFunctionNames", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
CollectFunctionNames pass = new CollectFunctionNames(compiler);
pass.process(externs, root);
compiler.setFunctionNames(pass.getFunctionNames());
}
};
}
@Override
public FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Inserts run-time type assertions for debugging. */
private final PassFactory runtimeTypeCheck =
new PassFactory(PassNames.RUNTIME_TYPE_CHECK, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new RuntimeTypeCheck(compiler, options.runtimeTypeCheckLogFunction);
}
};
/** Generates unique ids. */
private final PassFactory replaceIdGenerators =
new PassFactory(PassNames.REPLACE_ID_GENERATORS, true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
ReplaceIdGenerators pass =
new ReplaceIdGenerators(
compiler,
options.idGenerators,
options.generatePseudoNames,
options.idGeneratorsMapSerialized,
options.xidHashFunction);
pass.process(externs, root);
compiler.setIdGeneratorMap(pass.getSerializedIdMappings());
}
};
}
};
/** Replace strings. */
private final PassFactory replaceStrings = new PassFactory("replaceStrings", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
ReplaceStrings pass = new ReplaceStrings(
compiler,
options.replaceStringsPlaceholderToken,
options.replaceStringsFunctionDescriptions,
options.replaceStringsReservedStrings,
options.replaceStringsInputMap);
pass.process(externs, root);
compiler.setStringMap(pass.getStringMap());
}
};
}
};
/** Optimizes the "arguments" array. */
private final PassFactory optimizeArgumentsArray =
new PassFactory(PassNames.OPTIMIZE_ARGUMENTS_ARRAY, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new OptimizeArgumentsArray(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Remove variables set to goog.abstractMethod. */
private final PassFactory closureCodeRemoval =
new PassFactory("closureCodeRemoval", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new ClosureCodeRemoval(compiler, options.removeAbstractMethods,
options.removeClosureAsserts);
}
};
/** Special case optimizations for closure functions. */
private final PassFactory closureOptimizePrimitives =
new PassFactory("closureOptimizePrimitives", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new ClosureOptimizePrimitives(
compiler,
compiler.getOptions().propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED,
compiler.getOptions().getLanguageOut().toFeatureSet().contains(FeatureSet.ES6));
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Puts global symbols into a single object. */
private final PassFactory rescopeGlobalSymbols =
new PassFactory("rescopeGlobalSymbols", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new RescopeGlobalSymbols(
compiler,
options.renamePrefixNamespace,
options.renamePrefixNamespaceAssumeCrossModuleNames);
}
};
/** Collapses names in the global scope. */
private final PassFactory collapseProperties =
new PassFactory(PassNames.COLLAPSE_PROPERTIES, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CollapseProperties(compiler);
}
};
/** Rewrite properties as variables. */
private final PassFactory collapseObjectLiterals =
new PassFactory(PassNames.COLLAPSE_OBJECT_LITERALS, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InlineObjectLiterals(compiler, compiler.getUniqueNameIdSupplier());
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Disambiguate property names based on the coding convention. */
private final PassFactory disambiguatePrivateProperties =
new PassFactory(PassNames.DISAMBIGUATE_PRIVATE_PROPERTIES, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new DisambiguatePrivateProperties(compiler);
}
};
/** Disambiguate property names based on type information. */
private final PassFactory disambiguateProperties =
new PassFactory(PassNames.DISAMBIGUATE_PROPERTIES, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new DisambiguateProperties(compiler, options.propertyInvalidationErrors);
}
};
/** Chain calls to functions that return this. */
private final PassFactory chainCalls =
new PassFactory(PassNames.CHAIN_CALLS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ChainCalls(compiler);
}
};
/** Rewrite instance methods as static methods, to make them easier to inline. */
private final PassFactory devirtualizePrototypeMethods =
new PassFactory(PassNames.DEVIRTUALIZE_PROTOTYPE_METHODS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new DevirtualizePrototypeMethods(compiler);
}
};
/**
* Optimizes unused function arguments, unused return values, and inlines constant parameters.
* Also runs RemoveUnusedVars.
*/
private final PassFactory optimizeCalls =
new PassFactory(PassNames.OPTIMIZE_CALLS, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
OptimizeCalls passes = new OptimizeCalls(compiler);
if (options.optimizeReturns) {
// Remove unused return values.
passes.addPass(new OptimizeReturns(compiler));
}
if (options.optimizeParameters) {
// Remove all parameters that are constants or unused.
passes.addPass(new OptimizeParameters(compiler));
}
return passes;
}
};
/**
* Look for function calls that are pure, and annotate them
* that way.
*/
private final PassFactory markPureFunctions =
new PassFactory("markPureFunctions", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new PureFunctionIdentifier.Driver(
compiler, options.debugFunctionSideEffectsPath);
}
};
/** Look for function calls that have no side effects, and annotate them that way. */
private final PassFactory markNoSideEffectCalls =
new PassFactory(PassNames.MARK_NO_SIDE_EFFECT_CALLS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new MarkNoSideEffectCalls(compiler);
}
};
/** Inlines variables heuristically. */
private final PassFactory inlineVariables =
new PassFactory(PassNames.INLINE_VARIABLES, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
InlineVariables.Mode mode;
if (options.inlineVariables) {
mode = InlineVariables.Mode.ALL;
} else if (options.inlineLocalVariables) {
mode = InlineVariables.Mode.LOCALS_ONLY;
} else {
throw new IllegalStateException("No variable inlining option set.");
}
return new InlineVariables(compiler, mode, true);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Inlines variables that are marked as constants. */
private final PassFactory inlineConstants =
new PassFactory("inlineConstants", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InlineVariables(compiler, InlineVariables.Mode.CONSTANTS_ONLY, true);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Use data flow analysis to remove dead branches. */
private final PassFactory removeUnreachableCode =
new PassFactory(PassNames.REMOVE_UNREACHABLE_CODE, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new UnreachableCodeElimination(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8;
}
};
/**
* Use data flow analysis to remove dead branches.
*/
private final PassFactory removeUnusedPolyfills =
new PassFactory("removeUnusedPolyfills", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new RemoveUnusedPolyfills(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Remove prototype properties that do not appear to be used. */
private final PassFactory removeUnusedPrototypeProperties =
new PassFactory(PassNames.REMOVE_UNUSED_PROTOTYPE_PROPERTIES, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new RemoveUnusedPrototypeProperties(
compiler,
options.removeUnusedPrototypePropertiesInExterns,
!options.removeUnusedVars);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Remove prototype properties that do not appear to be used. */
private final PassFactory removeUnusedClassProperties =
new PassFactory(PassNames.REMOVE_UNUSED_CLASS_PROPERTIES, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new RemoveUnusedClassProperties(
compiler, options.removeUnusedConstructorProperties);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
private final PassFactory initNameAnalyzeReport = new PassFactory("initNameAnalyzeReport", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
NameAnalyzer.createEmptyReport(compiler, options.reportPath);
}
};
}
@Override
protected FeatureSet featureSet() {
return FeatureSet.latest();
}
};
/**
* Process smart name processing - removes unused classes and does referencing starting with
* minimum set of names.
*/
private final PassFactory extraSmartNamePass =
new PassFactory(PassNames.SMART_NAME_PASS, true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new NameAnalyzer(compiler, true, options.reportPath);
}
@Override
public FeatureSet featureSet() {
return ES5;
}
};
private final PassFactory smartNamePass =
new PassFactory(PassNames.SMART_NAME_PASS, true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new NameAnalyzer(compiler, true, options.reportPath);
}
@Override
public FeatureSet featureSet() {
return ES5;
}
};
private final PassFactory smartNamePass2 =
new PassFactory(PassNames.SMART_NAME_PASS, true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new NameAnalyzer(compiler, true, null);
}
@Override
public FeatureSet featureSet() {
return ES5;
}
};
/** Inlines simple methods, like getters */
private final PassFactory inlineSimpleMethods =
new PassFactory("inlineSimpleMethods", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InlineSimpleMethods(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES5;
}
};
/** Kills dead assignments. */
private final PassFactory deadAssignmentsElimination =
new PassFactory(PassNames.DEAD_ASSIGNMENT_ELIMINATION, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new DeadAssignmentsElimination(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Kills dead property assignments. */
private final PassFactory deadPropertyAssignmentElimination =
new PassFactory("deadPropertyAssignmentElimination", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new DeadPropertyAssignmentElimination(compiler);
}
@Override
public FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Inlines function calls. */
private final PassFactory inlineFunctions =
new PassFactory(PassNames.INLINE_FUNCTIONS, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InlineFunctions(
compiler,
compiler.getUniqueNameIdSupplier(),
options.inlineFunctions,
options.inlineLocalFunctions,
true,
options.assumeStrictThis() || options.expectStrictModeInput(),
options.assumeClosuresOnlyCaptureReferences,
options.maxFunctionSizeAfterInlining);
}
@Override
public FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Inlines constant properties. */
private final PassFactory inlineProperties =
new PassFactory(PassNames.INLINE_PROPERTIES, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InlineProperties(compiler);
}
};
private PassFactory getRemoveUnusedVars(String name, final boolean modifyCallSites) {
return getRemoveUnusedVars(name, modifyCallSites, false /* isOneTimePass */);
}
private PassFactory lastRemoveUnusedVars() {
return getRemoveUnusedVars(PassNames.REMOVE_UNUSED_VARS, false, true /* isOneTimePass */);
}
private PassFactory getRemoveUnusedVars(
String name, final boolean modifyCallSites, boolean isOneTimePass) {
/** Removes variables that are never used. */
return new PassFactory(name, isOneTimePass) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
boolean removeOnlyLocals = options.removeUnusedLocalVars && !options.removeUnusedVars;
boolean preserveAnonymousFunctionNames =
options.anonymousFunctionNaming != AnonymousFunctionNamingPolicy.OFF;
return new RemoveUnusedVars(
compiler,
!removeOnlyLocals,
preserveAnonymousFunctionNames,
modifyCallSites);
}
@Override
public FeatureSet featureSet() {
return ES5;
}
};
}
/** Move global symbols to a deeper common module */
private final PassFactory crossModuleCodeMotion =
new PassFactory(PassNames.CROSS_MODULE_CODE_MOTION, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CrossModuleCodeMotion(
compiler,
compiler.getModuleGraph(),
options.parentModuleCanSeeSymbolsDeclaredInChildren);
}
};
/** Move methods to a deeper common module */
private final PassFactory crossModuleMethodMotion =
new PassFactory(PassNames.CROSS_MODULE_METHOD_MOTION, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CrossModuleMethodMotion(
compiler,
compiler.getCrossModuleIdGenerator(),
// Only move properties in externs if we're not treating
// them as exports.
options.removeUnusedPrototypePropertiesInExterns,
options.crossModuleCodeMotionNoStubMethods);
}
};
/** A data-flow based variable inliner. */
private final PassFactory flowSensitiveInlineVariables =
new PassFactory(PassNames.FLOW_SENSITIVE_INLINE_VARIABLES, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new FlowSensitiveInlineVariables(compiler);
}
@Override
public FeatureSet featureSet() {
return ES5;
}
};
/** Uses register-allocation algorithms to use fewer variables. */
private final PassFactory coalesceVariableNames =
new PassFactory(PassNames.COALESCE_VARIABLE_NAMES, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CoalesceVariableNames(compiler, options.generatePseudoNames);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Some simple, local collapses (e.g., {@code var x; var y;} becomes {@code var x,y;}. */
private final PassFactory exploitAssign =
new PassFactory(PassNames.EXPLOIT_ASSIGN, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new PeepholeOptimizationsPass(compiler, getName(), new ExploitAssigns());
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Some simple, local collapses (e.g., {@code var x; var y;} becomes {@code var x,y;}. */
private final PassFactory collapseVariableDeclarations =
new PassFactory(PassNames.COLLAPSE_VARIABLE_DECLARATIONS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CollapseVariableDeclarations(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Extracts common sub-expressions. */
private final PassFactory extractPrototypeMemberDeclarations =
new PassFactory(PassNames.EXTRACT_PROTOTYPE_MEMBER_DECLARATIONS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
Pattern pattern;
switch (options.extractPrototypeMemberDeclarations) {
case USE_GLOBAL_TEMP:
pattern = Pattern.USE_GLOBAL_TEMP;
break;
case USE_IIFE:
pattern = Pattern.USE_IIFE;
break;
default:
throw new IllegalStateException("unexpected");
}
return new ExtractPrototypeMemberDeclarations(compiler, pattern);
}
};
/** Rewrites common function definitions to be more compact. */
private final PassFactory rewriteFunctionExpressions =
new PassFactory(PassNames.REWRITE_FUNCTION_EXPRESSIONS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new FunctionRewriter(compiler);
}
};
/** Collapses functions to not use the VAR keyword. */
private final PassFactory collapseAnonymousFunctions =
new PassFactory(PassNames.COLLAPSE_ANONYMOUS_FUNCTIONS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CollapseAnonymousFunctions(compiler);
}
};
/** Moves function declarations to the top, to simulate actual hoisting. */
private final PassFactory moveFunctionDeclarations =
new PassFactory(PassNames.MOVE_FUNCTION_DECLARATIONS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new MoveFunctionDeclarations(compiler);
}
};
private final PassFactory nameUnmappedAnonymousFunctions =
new PassFactory(PassNames.NAME_ANONYMOUS_FUNCTIONS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new NameAnonymousFunctions(compiler);
}
};
private final PassFactory nameMappedAnonymousFunctions =
new PassFactory(PassNames.NAME_ANONYMOUS_FUNCTIONS, true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
NameAnonymousFunctionsMapped naf =
new NameAnonymousFunctionsMapped(
compiler, options.inputAnonymousFunctionNamingMap);
naf.process(externs, root);
compiler.setAnonymousFunctionNameMap(naf.getFunctionMap());
}
};
}
};
/**
* Alias string literals with global variables, to avoid creating lots of
* transient objects.
*/
private final PassFactory aliasStrings = new PassFactory("aliasStrings", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new AliasStrings(
compiler,
compiler.getModuleGraph(),
options.aliasAllStrings ? null : options.aliasableStrings,
options.aliasStringsBlacklist,
options.outputJsStringUsage);
}
};
/** Handling for the ObjectPropertyString primitive. */
private final PassFactory objectPropertyStringPostprocess =
new PassFactory("ObjectPropertyStringPostprocess", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ObjectPropertyStringPostprocess(compiler);
}
};
/**
* Renames properties so that the two properties that never appear on the same object get the same
* name.
*/
private final PassFactory ambiguateProperties =
new PassFactory(PassNames.AMBIGUATE_PROPERTIES, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new AmbiguateProperties(
compiler,
options.getPropertyReservedNamingFirstChars(),
options.getPropertyReservedNamingNonFirstChars());
}
};
/** Mark the point at which the normalized AST assumptions no longer hold. */
private final PassFactory markUnnormalized =
new PassFactory("markUnnormalized", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
compiler.setLifeCycleStage(LifeCycleStage.RAW);
}
};
}
@Override
protected FeatureSet featureSet() {
return FeatureSet.latest();
}
};
private final PassFactory normalize =
new PassFactory(PassNames.NORMALIZE, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new Normalize(compiler, false);
}
@Override
protected FeatureSet featureSet() {
// TODO(johnlenz): Update this and gatherRawExports to latest()
return ES8_MODULES;
}
};
private final PassFactory externExports =
new PassFactory(PassNames.EXTERN_EXPORTS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ExternExportsPass(compiler);
}
};
/** Denormalize the AST for code generation. */
private final PassFactory denormalize = new PassFactory("denormalize", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new Denormalize(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Inverting name normalization. */
private final PassFactory invertContextualRenaming =
new PassFactory("invertContextualRenaming", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return MakeDeclaredNamesUnique.getContextualRenameInverter(compiler);
}
};
/** Renames properties. */
private final PassFactory renameProperties =
new PassFactory("renameProperties", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
checkState(options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED);
final VariableMap prevPropertyMap = options.inputPropertyMap;
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
RenameProperties rprop =
new RenameProperties(
compiler,
options.generatePseudoNames,
prevPropertyMap,
options.getPropertyReservedNamingFirstChars(),
options.getPropertyReservedNamingNonFirstChars(),
options.nameGenerator);
rprop.process(externs, root);
compiler.setPropertyMap(rprop.getPropertyMap());
}
};
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Renames variables. */
private final PassFactory renameVars = new PassFactory("renameVars", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
final VariableMap prevVariableMap = options.inputVariableMap;
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
compiler.setVariableMap(runVariableRenaming(
compiler, prevVariableMap, externs, root));
}
};
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
private VariableMap runVariableRenaming(
AbstractCompiler compiler, VariableMap prevVariableMap,
Node externs, Node root) {
char[] reservedChars =
options.anonymousFunctionNaming.getReservedCharacters();
boolean preserveAnonymousFunctionNames =
options.anonymousFunctionNaming != AnonymousFunctionNamingPolicy.OFF;
Set<String> reservedNames = new HashSet<>();
if (options.renamePrefixNamespace != null) {
// don't use the prefix name as a global symbol.
reservedNames.add(options.renamePrefixNamespace);
}
reservedNames.addAll(compiler.getExportedNames());
reservedNames.addAll(ParserRunner.getReservedVars());
RenameVars rn = new RenameVars(
compiler,
options.renamePrefix,
options.variableRenaming == VariableRenamingPolicy.LOCAL,
preserveAnonymousFunctionNames,
options.generatePseudoNames,
options.shadowVariables,
options.preferStableNames,
prevVariableMap,
reservedChars,
reservedNames,
options.nameGenerator);
rn.process(externs, root);
return rn.getVariableMap();
}
/** Renames labels */
private final PassFactory renameLabels =
new PassFactory("renameLabels", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new RenameLabels(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Convert bracket access to dot access */
private final PassFactory convertToDottedProperties =
new PassFactory(PassNames.CONVERT_TO_DOTTED_PROPERTIES, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ConvertToDottedProperties(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
private final PassFactory checkAstValidity =
new PassFactory("checkAstValidity", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new AstValidator(compiler);
}
@Override
protected FeatureSet featureSet() {
return FeatureSet.latest();
}
};
/** Checks that all variables are defined. */
private final PassFactory varCheckValidity =
new PassFactory("varCheckValidity", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new VarCheck(compiler, true);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Adds instrumentations according to an instrumentation template. */
private final PassFactory instrumentFunctions =
new PassFactory("instrumentFunctions", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new InstrumentFunctions(
compiler, compiler.getFunctionNames(),
options.instrumentationTemplate, options.appNameStr);
}
};
private final PassFactory instrumentForCodeCoverage =
new PassFactory("instrumentForCodeCoverage", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
// TODO(johnlenz): make global instrumentation an option
if (options.instrumentBranchCoverage) {
return new CoverageInstrumentationPass(
compiler, CoverageReach.CONDITIONAL, InstrumentOption.BRANCH_ONLY);
} else {
return new CoverageInstrumentationPass(compiler, CoverageReach.CONDITIONAL);
}
}
};
/** Extern property names gathering pass. */
private final PassFactory gatherExternProperties =
new PassFactory("gatherExternProperties", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new GatherExternProperties(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/**
* Runs custom passes that are designated to run at a particular time.
*/
private PassFactory getCustomPasses(
final CustomPassExecutionTime executionTime) {
return new PassFactory("runCustomPasses", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return runInSerial(options.customPasses.get(executionTime));
}
};
}
/** Create a compiler pass that runs the given passes in serial. */
private static CompilerPass runInSerial(
final Collection<CompilerPass> passes) {
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
for (CompilerPass pass : passes) {
pass.process(externs, root);
}
}
};
}
@VisibleForTesting
static Map<String, Node> getAdditionalReplacements(
CompilerOptions options) {
Map<String, Node> additionalReplacements = new HashMap<>();
if (options.markAsCompiled || options.closurePass) {
additionalReplacements.put(COMPILED_CONSTANT_NAME, IR.trueNode());
}
if (options.closurePass && options.locale != null) {
additionalReplacements.put(CLOSURE_LOCALE_CONSTANT_NAME,
IR.string(options.locale));
}
return additionalReplacements;
}
/** Rewrites Polymer({}) */
private final HotSwapPassFactory polymerPass =
new HotSwapPassFactory("polymerPass") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new PolymerPass(
compiler,
compiler.getOptions().polymerVersion,
compiler.getOptions().propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
private final PassFactory chromePass = new PassFactory("chromePass", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ChromePass(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Rewrites the super accessors calls to support Dart Dev Compiler output. */
private final HotSwapPassFactory dartSuperAccessorsPass =
new HotSwapPassFactory("dartSuperAccessorsPass") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new DartSuperAccessorsPass(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Rewrites J2CL constructs to be more optimizable. */
private final PassFactory j2clConstantHoisterPass =
new PassFactory("j2clConstantHoisterPass", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new J2clConstantHoisterPass(compiler);
}
};
/** Optimizes J2CL clinit methods. */
private final PassFactory j2clClinitPass =
new PassFactory("j2clClinitPass", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
List<Node> changedScopeNodes = compiler.getChangedScopeNodesForPass(getName());
return new J2clClinitPrunerPass(compiler, changedScopeNodes);
}
};
/** Rewrites J2CL constructs to be more optimizable. */
private final PassFactory j2clPropertyInlinerPass =
new PassFactory("j2clES6Pass", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new J2clPropertyInlinerPass(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Rewrites J2CL constructs to be more optimizable. */
private final PassFactory j2clPass =
new PassFactory("j2clPass", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new J2clPass(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
private final PassFactory j2clAssertRemovalPass =
new PassFactory("j2clAssertRemovalPass", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new J2clAssertRemovalPass(compiler);
}
};
private final PassFactory j2clSourceFileChecker =
new PassFactory("j2clSourceFileChecker", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new J2clSourceFileChecker(compiler);
}
@Override
protected FeatureSet featureSet() {
return FeatureSet.latest();
}
};
private final PassFactory j2clChecksPass =
new PassFactory("j2clChecksPass", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new J2clChecksPass(compiler);
}
};
private final PassFactory checkConformance =
new PassFactory("checkConformance", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CheckConformance(
compiler, ImmutableList.copyOf(options.getConformanceConfigs()));
}
};
/** Optimizations that output ES6 features. */
private final PassFactory optimizeToEs6 =
new PassFactory("optimizeToEs6", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new SubstituteEs6Syntax(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
/** Rewrites goog.module in whitespace only mode */
private final HotSwapPassFactory whitespaceWrapGoogModules =
new HotSwapPassFactory("whitespaceWrapGoogModules") {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new WhitespaceWrapGoogModules(compiler);
}
@Override
protected FeatureSet featureSet() {
return ES8_MODULES;
}
};
private final PassFactory removeSuperMethodsPass =
new PassFactory(PassNames.REMOVE_SUPER_METHODS, true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new RemoveSuperMethodsPass(compiler);
}
};
}
| Enable rewriteFunctionExpressions for ES6 output.
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=172526935
| src/com/google/javascript/jscomp/DefaultPassConfig.java | Enable rewriteFunctionExpressions for ES6 output. |
|
Java | apache-2.0 | 377784c2d39f07a969107fb29818ffe5a8e57783 | 0 | andriell/craftyfox,andriell/craftyfox,andriell/craftyfox | package com.github.andriell.processor;
import org.springframework.beans.factory.InitializingBean;
import java.util.concurrent.*;
/**
* Created by Андрей on 04.02.2016
*/
public abstract class Manager implements ManagerInterface, InitializingBean {
private BlockingQueue<DataInterface> dataQueue;
private RunnableLimiter runnableLimiter;
private RunnableListenerInterface runnableListener;
private int capacity;
private boolean fair;
public abstract ProcessInterface getProcess();
public void addData(DataInterface task) {
dataQueue.add(task);
}
public DataInterface pullTask() {
return dataQueue.poll();
}
public void run() {
synchronized (this) {
while (true) {
DataInterface data = pullTask();
if (data == null) {
break;
}
ProcessInterface process = getProcess();
process.setData(data);
RunnableAdapter runnableAdapter = RunnableAdapter.envelop(process);
runnableAdapter.addListenerEnd(runnableListener); // листенер должен выполняться после листенера RunnableLimiter
if (!runnableLimiter.start(runnableAdapter)) {
addData(data);
break;
}
}
}
}
public RunnableLimiter getRunnableLimiter() {
return runnableLimiter;
}
public void setRunnableLimiter(RunnableLimiter runnableLimiter) {
this.runnableLimiter = runnableLimiter;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
public void setFair(boolean fair) {
this.fair = fair;
}
public void afterPropertiesSet() throws Exception {
runnableListener = new RunnableListenerInterface() {
public void onStart(Runnable r) {
}
public void onException(Runnable r, Exception e) {
run();
}
public void onComplete(Runnable r) {
run();
}
};
dataQueue = new ArrayBlockingQueue<DataInterface>(capacity, fair);
}
}
| src/main/java/com/github/andriell/processor/Manager.java | package com.github.andriell.processor;
import org.springframework.beans.factory.InitializingBean;
import java.util.concurrent.*;
/**
* Created by Андрей on 04.02.2016
*/
public abstract class Manager implements ManagerInterface, InitializingBean {
private BlockingQueue<DataInterface> dataQueue;
private RunnableLimiter runnableLimiter;
private RunnableListenerInterface runnableListener;
private int capacity;
private boolean fair;
public abstract ProcessInterface getProcess();
public void addData(DataInterface task) {
dataQueue.add(task);
}
public DataInterface pullTask() {
return dataQueue.poll();
}
public void run() {
while (true) {
DataInterface data = pullTask();
if (data == null) {
break;
}
ProcessInterface process = getProcess();
process.setData(data);
RunnableAdapter runnableAdapter = RunnableAdapter.envelop(process);
runnableAdapter.addListenerEnd(runnableListener); // листенер должен выполняться после листенера RunnableLimiter
if (!runnableLimiter.start(runnableAdapter)) {
addData(data);
break;
}
}
}
public RunnableLimiter getRunnableLimiter() {
return runnableLimiter;
}
public void setRunnableLimiter(RunnableLimiter runnableLimiter) {
this.runnableLimiter = runnableLimiter;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
public void setFair(boolean fair) {
this.fair = fair;
}
public void afterPropertiesSet() throws Exception {
runnableListener = new RunnableListenerInterface() {
public void onStart(Runnable r) {
}
public void onException(Runnable r, Exception e) {
run();
}
public void onComplete(Runnable r) {
run();
}
};
dataQueue = new ArrayBlockingQueue<DataInterface>(capacity, fair);
}
}
| Start
| src/main/java/com/github/andriell/processor/Manager.java | Start |
|
Java | apache-2.0 | 993e9afe3ddcaf90900a4108545796ddb737d28c | 0 | phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida | package ca.corefacility.bioinformatics.irida.repositories.remote.impl;
import java.util.List;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import ca.corefacility.bioinformatics.irida.model.IridaResourceSupport;
import ca.corefacility.bioinformatics.irida.model.RemoteAPI;
import ca.corefacility.bioinformatics.irida.model.remote.RemoteStatus;
import ca.corefacility.bioinformatics.irida.model.remote.resource.ListResourceWrapper;
import ca.corefacility.bioinformatics.irida.model.remote.resource.ResourceWrapper;
import ca.corefacility.bioinformatics.irida.model.user.User;
import ca.corefacility.bioinformatics.irida.repositories.remote.RemoteRepository;
import ca.corefacility.bioinformatics.irida.repositories.remote.resttemplate.OAuthTokenRestTemplate;
import ca.corefacility.bioinformatics.irida.service.RemoteAPITokenService;
/**
* Remote repository to request from remote IRIDA instances using
* {@link OAuthTokenRestTemplate}s
*
*
* @param <Type>
* The type of object to be stored in this repository (extends
* {@link IridaResourceSupport})
*/
public abstract class RemoteRepositoryImpl<Type extends IridaResourceSupport> implements RemoteRepository<Type> {
// service storing api tokens for communication with the remote services
private RemoteAPITokenService tokenService;
// type references for the resources being read by this repository
final protected ParameterizedTypeReference<ListResourceWrapper<Type>> listTypeReference;
final protected ParameterizedTypeReference<ResourceWrapper<Type>> objectTypeReference;
/**
* Create a new repository with the given rest template and object params
*
* @param tokenService
* service storing api tokens for communication with the remote
* APIs
* @param listTypeReference
* A {@link ParameterizedTypeReference} for objects listed by the
* rest template
* @param objectTypeReference
* A {@link ParameterizedTypeReference} for individual resources
* read by the rest template
*/
public RemoteRepositoryImpl(RemoteAPITokenService tokenService,
ParameterizedTypeReference<ListResourceWrapper<Type>> listTypeReference,
ParameterizedTypeReference<ResourceWrapper<Type>> objectTypeReference) {
this.tokenService = tokenService;
this.listTypeReference = listTypeReference;
this.objectTypeReference = objectTypeReference;
}
/**
* {@inheritDoc}
*/
@Override
public Type read(String uri, RemoteAPI remoteAPI) {
OAuthTokenRestTemplate restTemplate = new OAuthTokenRestTemplate(tokenService, remoteAPI);
ResponseEntity<ResourceWrapper<Type>> exchange = restTemplate.exchange(uri, HttpMethod.GET, HttpEntity.EMPTY,
objectTypeReference);
Type resource = exchange.getBody().getResource();
resource.setRemoteAPI(remoteAPI);
resource = setRemoteStatus(resource, remoteAPI);
return resource;
}
/**
* {@inheritDoc}
*/
@Override
public List<Type> list(String uri, RemoteAPI remoteAPI) {
OAuthTokenRestTemplate restTemplate = new OAuthTokenRestTemplate(tokenService, remoteAPI);
ResponseEntity<ListResourceWrapper<Type>> exchange = restTemplate.exchange(uri, HttpMethod.GET,
HttpEntity.EMPTY, listTypeReference);
List<Type> resources = exchange.getBody().getResource().getResources();
for (Type r : resources) {
r.setRemoteAPI(remoteAPI);
r = setRemoteStatus(r, remoteAPI);
}
return resources;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getServiceStatus(RemoteAPI remoteAPI) {
OAuthTokenRestTemplate restTemplate = new OAuthTokenRestTemplate(tokenService, remoteAPI);
ResponseEntity<String> forEntity = restTemplate.getForEntity(remoteAPI.getServiceURI(), String.class);
return forEntity.getStatusCode() == HttpStatus.OK;
}
/**
* Set the {@link RemoteStatus} of a read remote entity
*
* @param entity
* The entity to set the remote status on
* @return the enhanced entity
*/
protected <T extends IridaResourceSupport> T setRemoteStatus(T entity, RemoteAPI api) {
String selfHref = entity.getSelfHref();
// Get the logged in user and set them in the remote status object
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
RemoteStatus remoteStatus = new RemoteStatus(selfHref, api);
if (principal instanceof User) {
remoteStatus.setReadBy((User) principal);
}
remoteStatus.setRemoteHashCode(entity.hashCode());
entity.setRemoteStatus(remoteStatus);
return entity;
}
}
| src/main/java/ca/corefacility/bioinformatics/irida/repositories/remote/impl/RemoteRepositoryImpl.java | package ca.corefacility.bioinformatics.irida.repositories.remote.impl;
import java.util.List;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import ca.corefacility.bioinformatics.irida.model.IridaResourceSupport;
import ca.corefacility.bioinformatics.irida.model.RemoteAPI;
import ca.corefacility.bioinformatics.irida.model.remote.RemoteStatus;
import ca.corefacility.bioinformatics.irida.model.remote.resource.ListResourceWrapper;
import ca.corefacility.bioinformatics.irida.model.remote.resource.ResourceWrapper;
import ca.corefacility.bioinformatics.irida.model.user.User;
import ca.corefacility.bioinformatics.irida.repositories.remote.RemoteRepository;
import ca.corefacility.bioinformatics.irida.repositories.remote.resttemplate.OAuthTokenRestTemplate;
import ca.corefacility.bioinformatics.irida.service.RemoteAPITokenService;
/**
* Remote repository to request from remote IRIDA instances using
* {@link OAuthTokenRestTemplate}s
*
*
* @param <Type>
* The type of object to be stored in this repository (extends
* {@link IridaResourceSupport})
*/
public abstract class RemoteRepositoryImpl<Type extends IridaResourceSupport> implements RemoteRepository<Type> {
// service storing api tokens for communication with the remote services
private RemoteAPITokenService tokenService;
// type references for the resources being read by this repository
final protected ParameterizedTypeReference<ListResourceWrapper<Type>> listTypeReference;
final protected ParameterizedTypeReference<ResourceWrapper<Type>> objectTypeReference;
/**
* Create a new repository with the given rest template and object params
*
* @param tokenService
* service storing api tokens for communication with the remote
* APIs
* @param listTypeReference
* A {@link ParameterizedTypeReference} for objects listed by the
* rest template
* @param objectTypeReference
* A {@link ParameterizedTypeReference} for individual resources
* read by the rest template
*/
public RemoteRepositoryImpl(RemoteAPITokenService tokenService,
ParameterizedTypeReference<ListResourceWrapper<Type>> listTypeReference,
ParameterizedTypeReference<ResourceWrapper<Type>> objectTypeReference) {
this.tokenService = tokenService;
this.listTypeReference = listTypeReference;
this.objectTypeReference = objectTypeReference;
}
/**
* {@inheritDoc}
*/
@Override
public Type read(String uri, RemoteAPI remoteAPI) {
OAuthTokenRestTemplate restTemplate = new OAuthTokenRestTemplate(tokenService, remoteAPI);
ResponseEntity<ResourceWrapper<Type>> exchange = restTemplate.exchange(uri, HttpMethod.GET, HttpEntity.EMPTY,
objectTypeReference);
Type resource = exchange.getBody().getResource();
resource.setRemoteAPI(remoteAPI);
resource = setRemoteStatus(resource, remoteAPI);
return resource;
}
/**
* {@inheritDoc}
*/
@Override
public List<Type> list(String uri, RemoteAPI remoteAPI) {
OAuthTokenRestTemplate restTemplate = new OAuthTokenRestTemplate(tokenService, remoteAPI);
ResponseEntity<ListResourceWrapper<Type>> exchange = restTemplate.exchange(uri, HttpMethod.GET,
HttpEntity.EMPTY, listTypeReference);
List<Type> resources = exchange.getBody().getResource().getResources();
for (Type r : resources) {
r.setRemoteAPI(remoteAPI);
r = setRemoteStatus(r, remoteAPI);
}
return resources;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getServiceStatus(RemoteAPI remoteAPI) {
OAuthTokenRestTemplate restTemplate = new OAuthTokenRestTemplate(tokenService, remoteAPI);
ResponseEntity<String> forEntity = restTemplate.getForEntity(remoteAPI.getServiceURI(), String.class);
return forEntity.getStatusCode() == HttpStatus.OK;
}
/**
* Set the {@link RemoteStatus} of a read remote entity
*
* @param entity
* The entity to set the remote status on
* @return the enhanced entity
*/
protected <T extends IridaResourceSupport> T setRemoteStatus(T entity, RemoteAPI api) {
String selfHref = entity.getSelfHref();
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
RemoteStatus remoteStatus = new RemoteStatus(selfHref, api);
if(principal instanceof User){
remoteStatus.setReadBy((User) principal);
}
remoteStatus.setRemoteHashCode(entity.hashCode());
entity.setRemoteStatus(remoteStatus);
return entity;
}
}
| comment and formatting
| src/main/java/ca/corefacility/bioinformatics/irida/repositories/remote/impl/RemoteRepositoryImpl.java | comment and formatting |
|
Java | apache-2.0 | f91bd45b7ec5cea5a3d578794c9eeaa0d9e0cd7f | 0 | BroadleafCommerce/blc-authorizenet | /*
* #%L
* BroadleafCommerce Authorize.net
* %%
* Copyright (C) 2009 - 2014 Broadleaf Commerce
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.broadleafcommerce.payment.service.gateway;
import org.broadleafcommerce.common.money.Money;
import org.broadleafcommerce.common.payment.PaymentTransactionType;
import org.broadleafcommerce.common.payment.PaymentType;
import org.broadleafcommerce.common.payment.dto.PaymentRequestDTO;
import org.broadleafcommerce.common.payment.dto.PaymentResponseDTO;
import org.broadleafcommerce.common.payment.service.PaymentGatewayTransactionService;
import org.broadleafcommerce.common.time.SystemTime;
import org.broadleafcommerce.common.vendor.service.exception.PaymentException;
import org.broadleafcommerce.vendor.authorizenet.service.payment.AuthorizeNetGatewayType;
import org.broadleafcommerce.vendor.authorizenet.service.payment.type.MessageConstants;
import org.broadleafcommerce.vendor.authorizenet.util.AuthorizeNetUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import java.math.BigDecimal;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.Resource;
import net.authorize.AuthNetField;
import net.authorize.Environment;
import net.authorize.Merchant;
import net.authorize.ResponseField;
import net.authorize.TransactionType;
import net.authorize.aim.Result;
import net.authorize.aim.Transaction;
import net.authorize.data.Order;
import net.authorize.data.ShippingCharges;
import net.authorize.data.cim.PaymentTransaction;
import net.authorize.data.creditcard.CreditCard;
@Service("blAuthorizeNetTransactionService")
public class AuthorizeNetTransactionServiceImpl implements PaymentGatewayTransactionService {
@Resource(name = "blAuthorizeNetConfiguration")
protected AuthorizeNetConfiguration configuration;
@Resource
protected AuthorizeNetUtil util;
@Override
public PaymentResponseDTO authorize(PaymentRequestDTO paymentRequestDTO) throws PaymentException {
return common(paymentRequestDTO, TransactionType.AUTH_ONLY, PaymentTransactionType.AUTHORIZE);
}
@Override
public PaymentResponseDTO capture(PaymentRequestDTO paymentRequestDTO) throws PaymentException {
Assert.isTrue(paymentRequestDTO.getAdditionalFields().containsKey(ResponseField.TRANSACTION_ID.getFieldName()),
"Must pass 'x_trans_id' value on the additionalFields of the Payment Request DTO");
Assert.isTrue(paymentRequestDTO.getTransactionTotal() != null,
"The Transaction Total must not be null on the Payment Request DTO");
return common(paymentRequestDTO, TransactionType.PRIOR_AUTH_CAPTURE, PaymentTransactionType.CAPTURE);
}
@Override
public PaymentResponseDTO authorizeAndCapture(PaymentRequestDTO paymentRequestDTO) throws PaymentException {
return common(paymentRequestDTO, TransactionType.AUTH_CAPTURE, PaymentTransactionType.AUTHORIZE_AND_CAPTURE);
}
@Override
public PaymentResponseDTO reverseAuthorize(PaymentRequestDTO paymentRequestDTO) throws PaymentException {
return voidPayment(paymentRequestDTO);
}
@Override
public PaymentResponseDTO refund(PaymentRequestDTO paymentRequestDTO) throws PaymentException {
Assert.isTrue(paymentRequestDTO.getAdditionalFields().containsKey(AuthNetField.X_TRANS_ID.getFieldName()),
"Must pass 'x_trans_id' value on the additionalFields of the Payment Request DTO");
Assert.isTrue(paymentRequestDTO.getTransactionTotal() != null,
"The Transaction Total must not be null on the Payment Request DTO");
Boolean cardNumOrLastFourPopulated = paymentRequestDTO.creditCardPopulated() &&
(paymentRequestDTO.getCreditCard().getCreditCardLastFour() != null || paymentRequestDTO.getCreditCard().getCreditCardNum() != null);
Assert.isTrue(cardNumOrLastFourPopulated || (paymentRequestDTO.getAdditionalFields().get(AuthNetField.X_CARD_NUM.getFieldName()) != null),
"Must pass the Last four card number digits on the credit card of the Payment Request DTO");
return common(paymentRequestDTO, TransactionType.CREDIT, PaymentTransactionType.REFUND);
}
@Override
public PaymentResponseDTO voidPayment(PaymentRequestDTO paymentRequestDTO) throws PaymentException {
Assert.isTrue(paymentRequestDTO.getAdditionalFields().containsKey(AuthNetField.X_TRANS_ID.getFieldName()),
"Must pass 'x_trans_id' value on the additionalFields of the Payment Request DTO");
return common(paymentRequestDTO, TransactionType.VOID, PaymentTransactionType.VOID);
}
private PaymentResponseDTO common(PaymentRequestDTO paymentRequestDTO, TransactionType transactionType, PaymentTransactionType paymentTransactionType) {
Environment e = Environment.createEnvironment(configuration.getServerUrl(), configuration.getXMLBaseUrl());
Merchant merchant = Merchant.createMerchant(e, configuration.getLoginId(), configuration.getTransactionKey());
PaymentResponseDTO responseDTO = new PaymentResponseDTO(PaymentType.CREDIT_CARD, AuthorizeNetGatewayType.AUTHORIZENET);
parseOutConsolidatedTokenField(paymentRequestDTO);
// Use the CIM API to send this transaction using the saved information
if (paymentRequestDTO.getAdditionalFields().containsKey(MessageConstants.CUSTOMER_PROFILE_ID)
&& paymentRequestDTO.getAdditionalFields().containsKey(MessageConstants.PAYMENT_PROFILE_ID)) {
net.authorize.cim.Transaction transaction = merchant.createCIMTransaction(net.authorize.cim.TransactionType.CREATE_CUSTOMER_PROFILE_TRANSACTION);
transaction.setCustomerProfileId((String) paymentRequestDTO.getAdditionalFields().get(MessageConstants.CUSTOMER_PROFILE_ID));
PaymentTransaction paymentTransaction = PaymentTransaction.createPaymentTransaction();
transaction.setPaymentTransaction(paymentTransaction);
paymentTransaction.setTransactionType(transactionType);
paymentTransaction.setCustomerPaymentProfileId((String) paymentRequestDTO.getAdditionalFields().get(MessageConstants.PAYMENT_PROFILE_ID));
Order order = Order.createOrder();
paymentTransaction.setOrder(order);
order.setTotalAmount(new BigDecimal(paymentRequestDTO.getTransactionTotal()));
order.setInvoiceNumber(System.currentTimeMillis() + "");
ShippingCharges shipping = ShippingCharges.createShippingCharges();
order.setShippingCharges(shipping);
shipping.setFreightAmount(paymentRequestDTO.getShippingTotal());
shipping.setTaxAmount(paymentRequestDTO.getTaxTotal());
// Submit the transaction
net.authorize.cim.Result<net.authorize.cim.Transaction> gatewayResult =
(net.authorize.cim.Result<net.authorize.cim.Transaction>)merchant.postTransaction(transaction);
responseDTO.successful(gatewayResult.isOk());
responseDTO.rawResponse(gatewayResult.getTarget().getCurrentResponse().dump());
responseDTO.orderId(paymentRequestDTO.getOrderId());
Map<ResponseField, String> responseMap = gatewayResult.getDirectResponseList().get(0).getDirectResponseMap();
responseDTO.creditCard()
.creditCardLastFour(responseMap.get(ResponseField.ACCOUNT_NUMBER))
.creditCardType(responseMap.get(ResponseField.CARD_TYPE));
responseDTO.amount(new Money(responseMap.get(ResponseField.AMOUNT)));
responseDTO.customer().email(responseMap.get(ResponseField.EMAIL_ADDRESS));
responseDTO.paymentTransactionType(paymentTransactionType);
} else {
Transaction transaction = merchant.createAIMTransaction(transactionType, new BigDecimal(paymentRequestDTO.getTransactionTotal()));
transaction.getRequestMap().put(AuthNetField.X_TEST_REQUEST.getFieldName(), configuration.getXTestRequest());
transaction.setMerchantDefinedField(MessageConstants.BLC_OID, paymentRequestDTO.getOrderId());
for (Entry<String, Object> field : paymentRequestDTO.getAdditionalFields().entrySet()) {
if (field.getValue() != null) {
// do not send any fields that are null or the Auth net API flips out
transaction.setMerchantDefinedField(field.getKey(), (String) field.getValue());
}
}
transaction.setTransactionId((String) paymentRequestDTO.getAdditionalFields().get(AuthNetField.X_TRANS_ID.getFieldName()));
if (transactionType.equals(TransactionType.AUTH_CAPTURE) || transactionType.equals(TransactionType.AUTH_ONLY)) {
CreditCard creditCard = CreditCard.createCreditCard();
creditCard.setCreditCardNumber(paymentRequestDTO.getCreditCard().getCreditCardNum());
creditCard.setExpirationMonth(paymentRequestDTO.getCreditCard().getCreditCardExpMonth());
creditCard.setExpirationYear(paymentRequestDTO.getCreditCard().getCreditCardExpYear());
transaction.setCreditCard(creditCard);
}
if (transactionType.equals(TransactionType.CREDIT)) {
String cardNumOrLastFour = null;
if (paymentRequestDTO.creditCardPopulated()) {
cardNumOrLastFour = paymentRequestDTO.getCreditCard().getCreditCardLastFour();
}
if (cardNumOrLastFour == null && ((String) paymentRequestDTO.getAdditionalFields().get(AuthNetField.X_CARD_NUM.getFieldName())).length() == 4) {
cardNumOrLastFour = (String) paymentRequestDTO.getAdditionalFields().get(AuthNetField.X_CARD_NUM.getFieldName());
}
if (cardNumOrLastFour == null && paymentRequestDTO.creditCardPopulated()) {
cardNumOrLastFour = paymentRequestDTO.getCreditCard().getCreditCardNum();
}
CreditCard creditCard = CreditCard.createCreditCard();
creditCard.setCreditCardNumber(cardNumOrLastFour);
transaction.setCreditCard(creditCard);
}
Result<Transaction> result = (Result<Transaction>) merchant.postTransaction(transaction);
responseDTO.paymentTransactionType(paymentTransactionType);
responseDTO.rawResponse(result.getTarget().toNVPString());
if (result.getTarget().getResponseField(ResponseField.AMOUNT) != null) {
responseDTO.amount(new Money(result.getTarget().getResponseField(ResponseField.AMOUNT)));
}
responseDTO.orderId(result.getTarget().getMerchantDefinedField(MessageConstants.BLC_OID));
responseDTO.responseMap(MessageConstants.TRANSACTION_TIME, SystemTime.asDate().toString());
responseDTO.responseMap(ResponseField.RESPONSE_CODE.getFieldName(), "" + result.getResponseCode().getCode());
responseDTO.responseMap(ResponseField.RESPONSE_REASON_CODE.getFieldName(), "" + result.getReasonResponseCode().getResponseReasonCode());
responseDTO.responseMap(ResponseField.RESPONSE_REASON_TEXT.getFieldName(), result.getResponseText());
responseDTO.responseMap(ResponseField.TRANSACTION_TYPE.getFieldName(), result.getTarget().getTransactionType().getValue());
responseDTO.responseMap(ResponseField.AMOUNT.getFieldName(), result.getTarget().getResponseField(ResponseField.AMOUNT));
responseDTO.responseMap(ResponseField.AUTHORIZATION_CODE.getFieldName(), result.getTarget().getAuthorizationCode());
responseDTO.successful(result.isApproved());
if (result.isError()) {
responseDTO.valid(false);
responseDTO.completeCheckoutOnCallback(false);
}
for (String fieldKey : result.getTarget().getMerchantDefinedMap().keySet()) {
responseDTO.responseMap(fieldKey, result.getTarget().getMerchantDefinedField(fieldKey));
}
}
return responseDTO;
}
/**
* Takes a "TOKEN" field from the given <b>paymentRequestDTO</b> and parses that into distinct parts of
* {@link MessageConstants#CUSTOMER_PROFILE_ID} and {@link MessageConstants#PAYMENT_PROFILE_ID} and puts each of those
* into the given {@link PaymentRequestDTO#getAdditionalFields()}
*
* @param paymentRequestDTO
*
*/
protected void parseOutConsolidatedTokenField(PaymentRequestDTO paymentRequestDTO) {
// NOTE: in Broadleaf 4.0.5+ the "TOKEN" field is an enum in PaymentAdditionalFieldType.TOKEN. This string is hardcoded
// manually to keep backwards compatibility
String consolidatedToken = (String) paymentRequestDTO.getAdditionalFields().get("TOKEN");
if (consolidatedToken != null) {
String[] profileIdPaymentId = util.parseConsolidatedPaymentToken(consolidatedToken);
paymentRequestDTO.getAdditionalFields().put(MessageConstants.CUSTOMER_PROFILE_ID, profileIdPaymentId[0]);
paymentRequestDTO.getAdditionalFields().put(MessageConstants.PAYMENT_PROFILE_ID, profileIdPaymentId[1]);
}
}
}
| src/main/java/org/broadleafcommerce/payment/service/gateway/AuthorizeNetTransactionServiceImpl.java | /*
* #%L
* BroadleafCommerce Authorize.net
* %%
* Copyright (C) 2009 - 2014 Broadleaf Commerce
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.broadleafcommerce.payment.service.gateway;
import org.broadleafcommerce.common.money.Money;
import org.broadleafcommerce.common.payment.PaymentTransactionType;
import org.broadleafcommerce.common.payment.PaymentType;
import org.broadleafcommerce.common.payment.dto.PaymentRequestDTO;
import org.broadleafcommerce.common.payment.dto.PaymentResponseDTO;
import org.broadleafcommerce.common.payment.service.PaymentGatewayTransactionService;
import org.broadleafcommerce.common.time.SystemTime;
import org.broadleafcommerce.common.vendor.service.exception.PaymentException;
import org.broadleafcommerce.vendor.authorizenet.service.payment.AuthorizeNetGatewayType;
import org.broadleafcommerce.vendor.authorizenet.service.payment.type.MessageConstants;
import org.broadleafcommerce.vendor.authorizenet.util.AuthorizeNetUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import java.math.BigDecimal;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.Resource;
import net.authorize.AuthNetField;
import net.authorize.Environment;
import net.authorize.Merchant;
import net.authorize.ResponseField;
import net.authorize.TransactionType;
import net.authorize.aim.Result;
import net.authorize.aim.Transaction;
import net.authorize.data.Order;
import net.authorize.data.ShippingCharges;
import net.authorize.data.cim.PaymentTransaction;
import net.authorize.data.creditcard.CreditCard;
@Service("blAuthorizeNetTransactionService")
public class AuthorizeNetTransactionServiceImpl implements PaymentGatewayTransactionService {
@Resource(name = "blAuthorizeNetConfiguration")
protected AuthorizeNetConfiguration configuration;
@Resource
protected AuthorizeNetUtil util;
@Override
public PaymentResponseDTO authorize(PaymentRequestDTO paymentRequestDTO) throws PaymentException {
return common(paymentRequestDTO, TransactionType.AUTH_ONLY, PaymentTransactionType.AUTHORIZE);
}
@Override
public PaymentResponseDTO capture(PaymentRequestDTO paymentRequestDTO) throws PaymentException {
Assert.isTrue(paymentRequestDTO.getAdditionalFields().containsKey(ResponseField.TRANSACTION_ID.getFieldName()),
"Must pass 'x_trans_id' value on the additionalFields of the Payment Request DTO");
Assert.isTrue(paymentRequestDTO.getTransactionTotal() != null,
"The Transaction Total must not be null on the Payment Request DTO");
return common(paymentRequestDTO, TransactionType.PRIOR_AUTH_CAPTURE, PaymentTransactionType.CAPTURE);
}
@Override
public PaymentResponseDTO authorizeAndCapture(PaymentRequestDTO paymentRequestDTO) throws PaymentException {
return common(paymentRequestDTO, TransactionType.AUTH_CAPTURE, PaymentTransactionType.AUTHORIZE_AND_CAPTURE);
}
@Override
public PaymentResponseDTO reverseAuthorize(PaymentRequestDTO paymentRequestDTO) throws PaymentException {
return voidPayment(paymentRequestDTO);
}
@Override
public PaymentResponseDTO refund(PaymentRequestDTO paymentRequestDTO) throws PaymentException {
Assert.isTrue(paymentRequestDTO.getAdditionalFields().containsKey(AuthNetField.X_TRANS_ID.getFieldName()),
"Must pass 'x_trans_id' value on the additionalFields of the Payment Request DTO");
Assert.isTrue(paymentRequestDTO.getTransactionTotal() != null,
"The Transaction Total must not be null on the Payment Request DTO");
Boolean cardNumOrLastFourPopulated = paymentRequestDTO.creditCardPopulated() &&
(paymentRequestDTO.getCreditCard().getCreditCardLastFour() != null || paymentRequestDTO.getCreditCard().getCreditCardNum() != null);
Assert.isTrue(cardNumOrLastFourPopulated || (paymentRequestDTO.getAdditionalFields().get(AuthNetField.X_CARD_NUM.getFieldName()) != null),
"Must pass the Last four card number digits on the credit card of the Payment Request DTO");
return common(paymentRequestDTO, TransactionType.CREDIT, PaymentTransactionType.REFUND);
}
@Override
public PaymentResponseDTO voidPayment(PaymentRequestDTO paymentRequestDTO) throws PaymentException {
Assert.isTrue(paymentRequestDTO.getAdditionalFields().containsKey(AuthNetField.X_TRANS_ID.getFieldName()),
"Must pass 'x_trans_id' value on the additionalFields of the Payment Request DTO");
return common(paymentRequestDTO, TransactionType.VOID, PaymentTransactionType.VOID);
}
private PaymentResponseDTO common(PaymentRequestDTO paymentRequestDTO, TransactionType transactionType, PaymentTransactionType paymentTransactionType) {
Environment e = Environment.createEnvironment(configuration.getServerUrl(), configuration.getXMLBaseUrl());
Merchant merchant = Merchant.createMerchant(e, configuration.getLoginId(), configuration.getTransactionKey());
PaymentResponseDTO responseDTO = new PaymentResponseDTO(PaymentType.CREDIT_CARD, AuthorizeNetGatewayType.AUTHORIZENET);
parseOutConsolidatedTokenField(paymentRequestDTO);
// Use the CIM API to send this transaction using the saved information
if (paymentRequestDTO.getAdditionalFields().containsKey(MessageConstants.CUSTOMER_PROFILE_ID)
&& paymentRequestDTO.getAdditionalFields().containsKey(MessageConstants.PAYMENT_PROFILE_ID)) {
net.authorize.cim.Transaction transaction = merchant.createCIMTransaction(net.authorize.cim.TransactionType.CREATE_CUSTOMER_PROFILE_TRANSACTION);
transaction.setCustomerProfileId((String) paymentRequestDTO.getAdditionalFields().get(MessageConstants.CUSTOMER_PROFILE_ID));
PaymentTransaction paymentTransaction = PaymentTransaction.createPaymentTransaction();
transaction.setPaymentTransaction(paymentTransaction);
paymentTransaction.setTransactionType(transactionType);
paymentTransaction.setCustomerPaymentProfileId((String) paymentRequestDTO.getAdditionalFields().get(MessageConstants.PAYMENT_PROFILE_ID));
Order order = Order.createOrder();
paymentTransaction.setOrder(order);
order.setTotalAmount(new BigDecimal(paymentRequestDTO.getTransactionTotal()));
order.setInvoiceNumber(System.currentTimeMillis() + "");
ShippingCharges shipping = ShippingCharges.createShippingCharges();
order.setShippingCharges(shipping);
shipping.setFreightAmount(paymentRequestDTO.getShippingTotal());
shipping.setTaxAmount(paymentRequestDTO.getTaxTotal());
// Submit the transaction
net.authorize.cim.Result<net.authorize.cim.Transaction> gatewayResult =
(net.authorize.cim.Result<net.authorize.cim.Transaction>)merchant.postTransaction(transaction);
responseDTO.successful(gatewayResult.isOk());
responseDTO.rawResponse(gatewayResult.getTarget().getCurrentResponse().dump());
responseDTO.orderId(paymentRequestDTO.getOrderId());
Map<ResponseField, String> responseMap = gatewayResult.getDirectResponseList().get(0).getDirectResponseMap();
responseDTO.creditCard()
.creditCardLastFour(responseMap.get(ResponseField.ACCOUNT_NUMBER))
.creditCardType(responseMap.get(ResponseField.CARD_TYPE));
responseDTO.amount(new Money(responseMap.get(ResponseField.AMOUNT)));
responseDTO.customer().email(responseMap.get(ResponseField.EMAIL_ADDRESS));
responseDTO.paymentTransactionType(paymentTransactionType);
} else {
Transaction transaction = merchant.createAIMTransaction(transactionType, new BigDecimal(paymentRequestDTO.getTransactionTotal()));
transaction.setMerchantDefinedField(MessageConstants.BLC_OID, paymentRequestDTO.getOrderId());
for (Entry<String, Object> field : paymentRequestDTO.getAdditionalFields().entrySet()) {
if (field.getValue() != null) {
// do not send any fields that are null or the Auth net API flips out
transaction.setMerchantDefinedField(field.getKey(), (String) field.getValue());
}
}
transaction.setTransactionId((String) paymentRequestDTO.getAdditionalFields().get(AuthNetField.X_TRANS_ID.getFieldName()));
if (transactionType.equals(TransactionType.AUTH_CAPTURE) || transactionType.equals(TransactionType.AUTH_ONLY)) {
CreditCard creditCard = CreditCard.createCreditCard();
creditCard.setCreditCardNumber(paymentRequestDTO.getCreditCard().getCreditCardNum());
creditCard.setExpirationMonth(paymentRequestDTO.getCreditCard().getCreditCardExpMonth());
creditCard.setExpirationYear(paymentRequestDTO.getCreditCard().getCreditCardExpYear());
transaction.setCreditCard(creditCard);
}
if (transactionType.equals(TransactionType.CREDIT)) {
String cardNumOrLastFour = null;
if (paymentRequestDTO.creditCardPopulated()) {
cardNumOrLastFour = paymentRequestDTO.getCreditCard().getCreditCardLastFour();
}
if (cardNumOrLastFour == null && ((String) paymentRequestDTO.getAdditionalFields().get(AuthNetField.X_CARD_NUM.getFieldName())).length() == 4) {
cardNumOrLastFour = (String) paymentRequestDTO.getAdditionalFields().get(AuthNetField.X_CARD_NUM.getFieldName());
}
if (cardNumOrLastFour == null && paymentRequestDTO.creditCardPopulated()) {
cardNumOrLastFour = paymentRequestDTO.getCreditCard().getCreditCardNum();
}
CreditCard creditCard = CreditCard.createCreditCard();
creditCard.setCreditCardNumber(cardNumOrLastFour);
transaction.setCreditCard(creditCard);
}
Result<Transaction> result = (Result<Transaction>) merchant.postTransaction(transaction);
responseDTO.paymentTransactionType(paymentTransactionType);
responseDTO.rawResponse(result.getTarget().toNVPString());
if (result.getTarget().getResponseField(ResponseField.AMOUNT) != null) {
responseDTO.amount(new Money(result.getTarget().getResponseField(ResponseField.AMOUNT)));
}
responseDTO.orderId(result.getTarget().getMerchantDefinedField(MessageConstants.BLC_OID));
responseDTO.responseMap(MessageConstants.TRANSACTION_TIME, SystemTime.asDate().toString());
responseDTO.responseMap(ResponseField.RESPONSE_CODE.getFieldName(), "" + result.getResponseCode().getCode());
responseDTO.responseMap(ResponseField.RESPONSE_REASON_CODE.getFieldName(), "" + result.getReasonResponseCode().getResponseReasonCode());
responseDTO.responseMap(ResponseField.RESPONSE_REASON_TEXT.getFieldName(), result.getResponseText());
responseDTO.responseMap(ResponseField.TRANSACTION_TYPE.getFieldName(), result.getTarget().getTransactionType().getValue());
responseDTO.responseMap(ResponseField.AMOUNT.getFieldName(), result.getTarget().getResponseField(ResponseField.AMOUNT));
responseDTO.responseMap(ResponseField.AUTHORIZATION_CODE.getFieldName(), result.getTarget().getAuthorizationCode());
responseDTO.successful(result.isApproved());
if (result.isError()) {
responseDTO.valid(false);
responseDTO.completeCheckoutOnCallback(false);
}
for (String fieldKey : result.getTarget().getMerchantDefinedMap().keySet()) {
responseDTO.responseMap(fieldKey, result.getTarget().getMerchantDefinedField(fieldKey));
}
}
return responseDTO;
}
/**
* Takes a "TOKEN" field from the given <b>paymentRequestDTO</b> and parses that into distinct parts of
* {@link MessageConstants#CUSTOMER_PROFILE_ID} and {@link MessageConstants#PAYMENT_PROFILE_ID} and puts each of those
* into the given {@link PaymentRequestDTO#getAdditionalFields()}
*
* @param paymentRequestDTO
*
*/
protected void parseOutConsolidatedTokenField(PaymentRequestDTO paymentRequestDTO) {
// NOTE: in Broadleaf 4.0.5+ the "TOKEN" field is an enum in PaymentAdditionalFieldType.TOKEN. This string is hardcoded
// manually to keep backwards compatibility
String consolidatedToken = (String) paymentRequestDTO.getAdditionalFields().get("TOKEN");
if (consolidatedToken != null) {
String[] profileIdPaymentId = util.parseConsolidatedPaymentToken(consolidatedToken);
paymentRequestDTO.getAdditionalFields().put(MessageConstants.CUSTOMER_PROFILE_ID, profileIdPaymentId[0]);
paymentRequestDTO.getAdditionalFields().put(MessageConstants.PAYMENT_PROFILE_ID, profileIdPaymentId[1]);
}
}
}
| Set X_TEST_REQUEST using "gateway.authorizenet.xTestRequest" property
- Addresses BroadleafCommerce/QA#2098
| src/main/java/org/broadleafcommerce/payment/service/gateway/AuthorizeNetTransactionServiceImpl.java | Set X_TEST_REQUEST using "gateway.authorizenet.xTestRequest" property |
|
Java | apache-2.0 | b48918ff07bd8f7eddff6ebc9241066641e0e749 | 0 | cnapagoda/carbon-governance,jranabahu/carbon-governance,isuruwan/carbon-governance,laki88/carbon-governance,thushara35/carbon-governance,isuruwan/carbon-governance,thushara35/carbon-governance,prasa7/carbon-governance,sameerak/carbon-governance,denuwanthi/carbon-governance,wso2/carbon-governance,maheshika/carbon-governance,prasa7/carbon-governance,thushara35/carbon-governance,denuwanthi/carbon-governance,maheshika/carbon-governance,cnapagoda/carbon-governance,daneshk/carbon-governance,denuwanthi/carbon-governance,laki88/carbon-governance,jranabahu/carbon-governance,Rajith90/carbon-governance,wso2/carbon-governance,maheshika/carbon-governance,prasa7/carbon-governance,cnapagoda/carbon-governance,prasa7/carbon-governance,thushara35/carbon-governance,sameerak/carbon-governance,wso2/carbon-governance,isuruwan/carbon-governance,Rajith90/carbon-governance,daneshk/carbon-governance,Rajith90/carbon-governance,cnapagoda/carbon-governance,jranabahu/carbon-governance,laki88/carbon-governance,Rajith90/carbon-governance,daneshk/carbon-governance,jranabahu/carbon-governance,isuruwan/carbon-governance,daneshk/carbon-governance,sameerak/carbon-governance,maheshika/carbon-governance,wso2/carbon-governance,denuwanthi/carbon-governance,sameerak/carbon-governance,laki88/carbon-governance | /*
* Copyright (c) 2005-2009, 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.governance.generic.ui.utils;
import org.wso2.carbon.registry.core.Registry;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
/**
* By implementing this interface, you can get data to be automatically populated for a drop down
* field.
*/
public interface DropDownDataPopulator {
/**
* Method to obtain the list of strings to be displayed in ascending order.
*
* @param request The HTTP request that was made.
* @param config The HTTP servlet configuration.
* @return the list of strings.
*/
public String[] getList(HttpServletRequest request, ServletConfig config);
/**
* Method to obtain the list of strings to be displayed in ascending order.
*
* @param uuid UUID of the resource
* @param path path of the resource
* @param registry Registry instance.
* @return the list of strings.
*/
public String[] getList(String uuid, String path, Registry registry);
}
| components/governance/org.wso2.carbon.governance.generic.ui/src/main/java/org/wso2/carbon/governance/generic/ui/utils/DropDownDataPopulator.java | /*
* Copyright (c) 2005-2009, 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.governance.generic.ui.utils;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
/**
* By implementing this interface, you can get data to be automatically populated for a drop down
* field.
*/
public interface DropDownDataPopulator {
/**
* Method to obtain the list of strings to be displayed in ascending order.
*
* @param request The HTTP request that was made.
* @param config The HTTP servlet configuration.
* @return the list of strings.
*/
public String[] getList(HttpServletRequest request, ServletConfig config);
}
| Add publihser getList method into DataPopulator interface
| components/governance/org.wso2.carbon.governance.generic.ui/src/main/java/org/wso2/carbon/governance/generic/ui/utils/DropDownDataPopulator.java | Add publihser getList method into DataPopulator interface |
|
Java | bsd-2-clause | 1b7340f341a22d80de4bac5618da3cf8d1fe8981 | 0 | runelite/runelite,Sethtroll/runelite,Sethtroll/runelite,runelite/runelite,runelite/runelite,l2-/runelite,l2-/runelite | /*
* Copyright (c) 2019, Twiglet1022 <https://github.com/Twiglet1022>
* 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.
*
* 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 net.runelite.client.plugins.cluescrolls.clues;
import com.google.common.collect.ImmutableList;
import java.awt.Color;
import java.awt.Graphics2D;
import java.util.List;
import javax.annotation.Nonnull;
import lombok.Getter;
import net.runelite.api.Item;
import static net.runelite.api.ItemID.ARMADYL_HELMET;
import static net.runelite.api.ItemID.BARRELCHEST_ANCHOR;
import static net.runelite.api.ItemID.BARROWS_GLOVES;
import static net.runelite.api.ItemID.BASALT;
import static net.runelite.api.ItemID.BOOK_OF_BALANCE;
import static net.runelite.api.ItemID.BOOK_OF_DARKNESS;
import static net.runelite.api.ItemID.BOOK_OF_LAW;
import static net.runelite.api.ItemID.BOOK_OF_WAR;
import static net.runelite.api.ItemID.COOKING_GAUNTLETS;
import static net.runelite.api.ItemID.CRYSTAL_BOW_110;
import static net.runelite.api.ItemID.CRYSTAL_BOW_110_I;
import static net.runelite.api.ItemID.DRAGON_DEFENDER;
import static net.runelite.api.ItemID.DRAGON_SCIMITAR;
import static net.runelite.api.ItemID.FIGHTER_TORSO;
import static net.runelite.api.ItemID.GREENMANS_ALEM;
import static net.runelite.api.ItemID.HOLY_BOOK;
import static net.runelite.api.ItemID.INFERNAL_AXE;
import static net.runelite.api.ItemID.IVANDIS_FLAIL;
import static net.runelite.api.ItemID.LAVA_DRAGON_BONES;
import static net.runelite.api.ItemID.MARK_OF_GRACE;
import static net.runelite.api.ItemID.NEW_CRYSTAL_BOW;
import static net.runelite.api.ItemID.NEW_CRYSTAL_BOW_I;
import static net.runelite.api.ItemID.NUMULITE;
import static net.runelite.api.ItemID.ROD_OF_IVANDIS_1;
import static net.runelite.api.ItemID.ROD_OF_IVANDIS_10;
import static net.runelite.api.ItemID.RUNE_PLATEBODY;
import static net.runelite.api.ItemID.TZHAARKETOM;
import static net.runelite.api.ItemID.UNHOLY_BOOK;
import static net.runelite.api.ItemID.WARRIOR_GUILD_TOKEN;
import net.runelite.api.NPC;
import net.runelite.api.coords.WorldPoint;
import static net.runelite.client.plugins.cluescrolls.ClueScrollOverlay.TITLED_CONTENT_COLOR;
import net.runelite.client.plugins.cluescrolls.ClueScrollPlugin;
import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.IMAGE_Z_OFFSET;
import net.runelite.client.plugins.cluescrolls.clues.emote.AnyRequirementCollection;
import net.runelite.client.plugins.cluescrolls.clues.emote.ItemRequirement;
import net.runelite.client.plugins.cluescrolls.clues.emote.RangeItemRequirement;
import net.runelite.client.plugins.cluescrolls.clues.emote.SingleItemRequirement;
import net.runelite.client.ui.overlay.OverlayUtil;
import net.runelite.client.ui.overlay.components.LineComponent;
import net.runelite.client.ui.overlay.components.PanelComponent;
import net.runelite.client.ui.overlay.components.TitleComponent;
@Getter
public class FaloTheBardClue extends ClueScroll implements TextClueScroll, NpcClueScroll
{
private static final List<FaloTheBardClue> CLUES = ImmutableList.of(
new FaloTheBardClue("A blood red weapon, a strong curved sword, found on the island of primate lords.", item(DRAGON_SCIMITAR)),
new FaloTheBardClue("A book that preaches of some great figure, lending strength, might, and vigour.", any("Any god book (must be complete)", item(HOLY_BOOK), item(BOOK_OF_BALANCE), item(UNHOLY_BOOK), item(BOOK_OF_LAW), item(BOOK_OF_WAR), item(BOOK_OF_DARKNESS))),
new FaloTheBardClue("A bow of elven craft was made, it shimmers bright, but will soon fade.", any("Crystal Bow", range(NEW_CRYSTAL_BOW, CRYSTAL_BOW_110), range(NEW_CRYSTAL_BOW_I, CRYSTAL_BOW_110_I))),
new FaloTheBardClue("A fiery axe of great inferno, when you use it, you'll wonder where the logs go.", item(INFERNAL_AXE)),
new FaloTheBardClue("A mark used to increase one's grace, found atop a seer's place.", item(MARK_OF_GRACE)),
new FaloTheBardClue("A molten beast with fiery breath, you acquire these with its death.", item(LAVA_DRAGON_BONES)),
new FaloTheBardClue("A shiny helmet of flight, to obtain this with melee, struggle you might.", item(ARMADYL_HELMET)),
// The wiki doesn't specify whether the trimmed dragon defender will work so I've assumed that it doesn't
new FaloTheBardClue("A sword held in the other hand, red its colour, Cyclops strength you must withstand.", item(DRAGON_DEFENDER)),
new FaloTheBardClue("A token used to kill mythical beasts, in hopes of a blade or just for an xp feast.", item(WARRIOR_GUILD_TOKEN)),
new FaloTheBardClue("Green is my favorite, mature ale I do love, this takes your herblore above.", item(GREENMANS_ALEM)),
new FaloTheBardClue("It can hold down a boat or crush a goat, this object, you see, is quite heavy.", item(BARRELCHEST_ANCHOR)),
new FaloTheBardClue("It comes from the ground, underneath the snowy plain. Trolls aplenty, with what looks like a mane.", item(BASALT)),
new FaloTheBardClue("No attack to wield, only strength is required, made of obsidian but with no room for a shield.", item(TZHAARKETOM)),
new FaloTheBardClue("Penance healers runners and more, obtaining this body often gives much deplore.", item(FIGHTER_TORSO)),
new FaloTheBardClue("Strangely found in a chest, many believe these gloves are the best.", item(BARROWS_GLOVES)),
new FaloTheBardClue("These gloves of white won't help you fight, but aid in cooking, they just might.", item(COOKING_GAUNTLETS)),
new FaloTheBardClue("They come from some time ago, from a land unto the east. Fossilised they have become, this small and gentle beast.", item(NUMULITE)),
new FaloTheBardClue("To slay a dragon you must first do, before this chest piece can be put on you.", item(RUNE_PLATEBODY)),
new FaloTheBardClue("Vampyres are agile opponents, damaged best with a weapon of many components.", any("Rod of Ivandis or Ivandis flail", range(ROD_OF_IVANDIS_10, ROD_OF_IVANDIS_1), item(IVANDIS_FLAIL)))
);
private static final WorldPoint LOCATION = new WorldPoint(2689, 3550, 0);
private static final String FALO_THE_BARD = "Falo the Bard";
private static SingleItemRequirement item(int itemId)
{
return new SingleItemRequirement(itemId);
}
private static AnyRequirementCollection any(String name, ItemRequirement... requirements)
{
return new AnyRequirementCollection(name, requirements);
}
private static RangeItemRequirement range(int startItemId, int endItemId)
{
return range(null, startItemId, endItemId);
}
private static RangeItemRequirement range(String name, int startItemId, int endItemId)
{
return new RangeItemRequirement(name, startItemId, endItemId);
}
private final String text;
@Nonnull
private final ItemRequirement[] itemRequirements;
private FaloTheBardClue(String text, @Nonnull ItemRequirement... itemRequirements)
{
this.text = text;
this.itemRequirements = itemRequirements;
}
@Override
public void makeOverlayHint(PanelComponent panelComponent, ClueScrollPlugin plugin)
{
panelComponent.getChildren().add(TitleComponent.builder().text("Falo the Bard Clue").build());
panelComponent.getChildren().add(LineComponent.builder().left("NPC:").build());
panelComponent.getChildren().add(LineComponent.builder()
.left(FALO_THE_BARD)
.leftColor(TITLED_CONTENT_COLOR)
.build());
panelComponent.getChildren().add(LineComponent.builder().left("Item:").build());
Item[] inventory = plugin.getInventoryItems();
// If inventory is null, the player has nothing in their inventory
if (inventory == null)
{
inventory = new Item[0];
}
for (ItemRequirement requirement : itemRequirements)
{
boolean inventoryFulfilled = requirement.fulfilledBy(inventory);
panelComponent.getChildren().add(LineComponent.builder()
.left(requirement.getCollectiveName(plugin.getClient()))
.leftColor(TITLED_CONTENT_COLOR)
.right(inventoryFulfilled ? "\u2713" : "\u2717")
.rightColor(inventoryFulfilled ? Color.GREEN : Color.RED)
.build());
}
}
@Override
public void makeWorldOverlayHint(Graphics2D graphics, ClueScrollPlugin plugin)
{
if (!LOCATION.isInScene(plugin.getClient()))
{
return;
}
for (NPC npc : plugin.getNpcsToMark())
{
OverlayUtil.renderActorOverlayImage(graphics, npc, plugin.getClueScrollImage(), Color.ORANGE, IMAGE_Z_OFFSET);
}
}
@Override
public String[] getNpcs()
{
return new String[] {FALO_THE_BARD};
}
public static FaloTheBardClue forText(String text)
{
for (FaloTheBardClue clue : CLUES)
{
if (clue.text.equalsIgnoreCase(text))
{
return clue;
}
}
return null;
}
}
| runelite-client/src/main/java/net/runelite/client/plugins/cluescrolls/clues/FaloTheBardClue.java | /*
* Copyright (c) 2019, Twiglet1022 <https://github.com/Twiglet1022>
* 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.
*
* 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 net.runelite.client.plugins.cluescrolls.clues;
import com.google.common.collect.ImmutableList;
import java.awt.Color;
import java.awt.Graphics2D;
import java.util.List;
import javax.annotation.Nonnull;
import lombok.Getter;
import net.runelite.api.Item;
import static net.runelite.api.ItemID.ARMADYL_HELMET;
import static net.runelite.api.ItemID.BARRELCHEST_ANCHOR;
import static net.runelite.api.ItemID.BARROWS_GLOVES;
import static net.runelite.api.ItemID.BASALT;
import static net.runelite.api.ItemID.BOOK_OF_BALANCE;
import static net.runelite.api.ItemID.BOOK_OF_DARKNESS;
import static net.runelite.api.ItemID.BOOK_OF_LAW;
import static net.runelite.api.ItemID.BOOK_OF_WAR;
import static net.runelite.api.ItemID.COOKING_GAUNTLETS;
import static net.runelite.api.ItemID.CRYSTAL_BOW_110;
import static net.runelite.api.ItemID.CRYSTAL_BOW_110_I;
import static net.runelite.api.ItemID.DRAGON_DEFENDER;
import static net.runelite.api.ItemID.DRAGON_SCIMITAR;
import static net.runelite.api.ItemID.FIGHTER_TORSO;
import static net.runelite.api.ItemID.GREENMANS_ALEM;
import static net.runelite.api.ItemID.HOLY_BOOK;
import static net.runelite.api.ItemID.INFERNAL_AXE;
import static net.runelite.api.ItemID.IVANDIS_FLAIL;
import static net.runelite.api.ItemID.LAVA_DRAGON_BONES;
import static net.runelite.api.ItemID.MARK_OF_GRACE;
import static net.runelite.api.ItemID.NEW_CRYSTAL_BOW;
import static net.runelite.api.ItemID.NEW_CRYSTAL_BOW_I;
import static net.runelite.api.ItemID.NUMULITE;
import static net.runelite.api.ItemID.ROD_OF_IVANDIS_1;
import static net.runelite.api.ItemID.ROD_OF_IVANDIS_10;
import static net.runelite.api.ItemID.RUNE_PLATEBODY;
import static net.runelite.api.ItemID.TZHAARKETOM;
import static net.runelite.api.ItemID.UNHOLY_BOOK;
import static net.runelite.api.ItemID.WARRIOR_GUILD_TOKEN;
import net.runelite.api.NPC;
import net.runelite.api.coords.WorldPoint;
import static net.runelite.client.plugins.cluescrolls.ClueScrollOverlay.TITLED_CONTENT_COLOR;
import net.runelite.client.plugins.cluescrolls.ClueScrollPlugin;
import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.IMAGE_Z_OFFSET;
import net.runelite.client.plugins.cluescrolls.clues.emote.AnyRequirementCollection;
import net.runelite.client.plugins.cluescrolls.clues.emote.ItemRequirement;
import net.runelite.client.plugins.cluescrolls.clues.emote.RangeItemRequirement;
import net.runelite.client.plugins.cluescrolls.clues.emote.SingleItemRequirement;
import net.runelite.client.ui.overlay.OverlayUtil;
import net.runelite.client.ui.overlay.components.LineComponent;
import net.runelite.client.ui.overlay.components.PanelComponent;
import net.runelite.client.ui.overlay.components.TitleComponent;
@Getter
public class FaloTheBardClue extends ClueScroll implements TextClueScroll, NpcClueScroll
{
private static final List<FaloTheBardClue> CLUES = ImmutableList.of(
new FaloTheBardClue("A blood red weapon, a strong curved sword, found on the island of primate lords.", item(DRAGON_SCIMITAR)),
new FaloTheBardClue("A book that preaches of some great figure, lending strength, might, and vigour.", any("Any god book (must be complete)", item(HOLY_BOOK), item(BOOK_OF_BALANCE), item(UNHOLY_BOOK), item(BOOK_OF_LAW), item(BOOK_OF_WAR), item(BOOK_OF_DARKNESS))),
new FaloTheBardClue("A bow of elven craft was made, it shimmers bright, but will soon fade.", any("Crystal Bow", range(NEW_CRYSTAL_BOW, CRYSTAL_BOW_110), range(NEW_CRYSTAL_BOW_I, CRYSTAL_BOW_110_I))),
new FaloTheBardClue("A fiery axe of great inferno, when you use it, you'll wonder where the logs go.", item(INFERNAL_AXE)),
new FaloTheBardClue("A mark used to increase one's grace, found atop a seer's place.", item(MARK_OF_GRACE)),
new FaloTheBardClue("A molten beast with fiery breath, you acquire these with its death.", item(LAVA_DRAGON_BONES)),
new FaloTheBardClue("A shiny helmet of flight, to obtain this with melee, struggle you might.", item(ARMADYL_HELMET)),
// The wiki doesn't specify whether the trimmed dragon defender will work so I've assumed that it doesn't
new FaloTheBardClue("A sword held in the other hand, red its colour, Cyclops strength you must withstand.", item(DRAGON_DEFENDER)),
new FaloTheBardClue("A token used to kill mythical beasts, in hope of a blade or just for an xp feast.", item(WARRIOR_GUILD_TOKEN)),
new FaloTheBardClue("Green is my favorite, mature ale I do love, this takes your herblore above.", item(GREENMANS_ALEM)),
new FaloTheBardClue("It can hold down a boat or crush a goat, this object, you see, is quite heavy.", item(BARRELCHEST_ANCHOR)),
new FaloTheBardClue("It comes from the ground, underneath the snowy plain. Trolls aplenty, with what looks like a mane.", item(BASALT)),
new FaloTheBardClue("No attack to wield, only strength is required, made of obsidian but with no room for a shield.", item(TZHAARKETOM)),
new FaloTheBardClue("Penance healers runners and more, obtaining this body often gives much deplore.", item(FIGHTER_TORSO)),
new FaloTheBardClue("Strangely found in a chest, many believe these gloves are the best.", item(BARROWS_GLOVES)),
new FaloTheBardClue("These gloves of white won't help you fight, but aid in cooking, they just might.", item(COOKING_GAUNTLETS)),
new FaloTheBardClue("They come from some time ago, from a land unto the east. Fossilised they have become, this small and gentle beast.", item(NUMULITE)),
new FaloTheBardClue("To slay a dragon you must first do, before this chest piece can be put on you.", item(RUNE_PLATEBODY)),
new FaloTheBardClue("Vampyres are agile opponents, damaged best with a weapon of many components.", any("Rod of Ivandis or Ivandis flail", range(ROD_OF_IVANDIS_10, ROD_OF_IVANDIS_1), item(IVANDIS_FLAIL)))
);
private static final WorldPoint LOCATION = new WorldPoint(2689, 3550, 0);
private static final String FALO_THE_BARD = "Falo the Bard";
private static SingleItemRequirement item(int itemId)
{
return new SingleItemRequirement(itemId);
}
private static AnyRequirementCollection any(String name, ItemRequirement... requirements)
{
return new AnyRequirementCollection(name, requirements);
}
private static RangeItemRequirement range(int startItemId, int endItemId)
{
return range(null, startItemId, endItemId);
}
private static RangeItemRequirement range(String name, int startItemId, int endItemId)
{
return new RangeItemRequirement(name, startItemId, endItemId);
}
private final String text;
@Nonnull
private final ItemRequirement[] itemRequirements;
private FaloTheBardClue(String text, @Nonnull ItemRequirement... itemRequirements)
{
this.text = text;
this.itemRequirements = itemRequirements;
}
@Override
public void makeOverlayHint(PanelComponent panelComponent, ClueScrollPlugin plugin)
{
panelComponent.getChildren().add(TitleComponent.builder().text("Falo the Bard Clue").build());
panelComponent.getChildren().add(LineComponent.builder().left("NPC:").build());
panelComponent.getChildren().add(LineComponent.builder()
.left(FALO_THE_BARD)
.leftColor(TITLED_CONTENT_COLOR)
.build());
panelComponent.getChildren().add(LineComponent.builder().left("Item:").build());
Item[] inventory = plugin.getInventoryItems();
// If inventory is null, the player has nothing in their inventory
if (inventory == null)
{
inventory = new Item[0];
}
for (ItemRequirement requirement : itemRequirements)
{
boolean inventoryFulfilled = requirement.fulfilledBy(inventory);
panelComponent.getChildren().add(LineComponent.builder()
.left(requirement.getCollectiveName(plugin.getClient()))
.leftColor(TITLED_CONTENT_COLOR)
.right(inventoryFulfilled ? "\u2713" : "\u2717")
.rightColor(inventoryFulfilled ? Color.GREEN : Color.RED)
.build());
}
}
@Override
public void makeWorldOverlayHint(Graphics2D graphics, ClueScrollPlugin plugin)
{
if (!LOCATION.isInScene(plugin.getClient()))
{
return;
}
for (NPC npc : plugin.getNpcsToMark())
{
OverlayUtil.renderActorOverlayImage(graphics, npc, plugin.getClueScrollImage(), Color.ORANGE, IMAGE_Z_OFFSET);
}
}
@Override
public String[] getNpcs()
{
return new String[] {FALO_THE_BARD};
}
public static FaloTheBardClue forText(String text)
{
for (FaloTheBardClue clue : CLUES)
{
if (clue.text.equalsIgnoreCase(text))
{
return clue;
}
}
return null;
}
}
| clues: correct text of falo the bard warrior guild token clue
| runelite-client/src/main/java/net/runelite/client/plugins/cluescrolls/clues/FaloTheBardClue.java | clues: correct text of falo the bard warrior guild token clue |
|
Java | bsd-3-clause | 254fd976c242a968f5989fc4683a16c40ac6079d | 0 | amazari/dfs-datastores,rodel-talampas/dfs-datastores,criteo-forks/dfs-datastores,ind9/dfs-datastores,embedcard/dfs-datastores,jf87/dfs-datastores,abolibibelot/dfs-datastores,spadala/dfs-datastores,nathanmarz/dfs-datastores | package backtype.hadoop.pail;
import backtype.hadoop.BalancedDistcp;
import backtype.hadoop.Coercer;
import backtype.hadoop.Consolidator;
import backtype.hadoop.PathLister;
import backtype.hadoop.RenameMode;
import backtype.hadoop.formats.RecordInputStream;
import backtype.hadoop.formats.RecordOutputStream;
import backtype.support.Utils;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.log4j.Logger;
public class Pail<T> extends AbstractPail implements Iterable<T>{
public static Logger LOG = Logger.getLogger(Pail.class);
public static final String META = "pail.meta";
public class TypedRecordOutputStream implements RecordOutputStream {
private HashMap<String, RecordOutputStream> _workers = new HashMap<String, RecordOutputStream>();
private String _userfilename;
private boolean _overwrite;
public TypedRecordOutputStream(String userfilename, boolean overwrite) {
_userfilename = userfilename;
_overwrite = overwrite;
}
public void writeObject(T obj) throws IOException {
List<String> rootAttrs = _structure.getTarget(obj);
List<String> attrs = makeRelative(rootAttrs);
String targetDir = Utils.join(attrs, "/");
if(!_workers.containsKey(targetDir)) {
Path p;
if(targetDir.length()==0) p = new Path(_userfilename);
else p = new Path(targetDir, _userfilename);
List<String> totalAttrs = componentsFromRoot(p.toString());
if(!_structure.isValidTarget(totalAttrs.toArray(new String[totalAttrs.size()]))) {
throw new IllegalArgumentException("Cannot write object " + obj.toString() + " to " + p.toString() +
". Conflicts with the structure of the datastore.");
}
_workers.put(targetDir, Pail.super.openWrite(p.toString(), _overwrite));
}
RecordOutputStream os = _workers.get(targetDir);
os.writeRaw(_structure.serialize(obj));
}
public void writeObjects(T... objs) throws IOException {
for(T obj: objs) {
writeObject(obj);
}
}
public void close() throws IOException {
for(RecordOutputStream os: _workers.values()) {
os.close();
}
}
protected List<String> makeRelative(List<String> attrs) {
return Utils.stripRoot(getAttrs(), attrs);
}
public void writeRaw(byte[] record) throws IOException {
writeRaw(record, 0, record.length);
}
public void writeRaw(byte[] record, int start, int length) throws IOException {
if(!_workers.containsKey(_userfilename)) {
checkValidStructure(_userfilename);
_workers.put(_userfilename, Pail.super.openWrite(_userfilename, _overwrite));
}
_workers.get(_userfilename).writeRaw(record, start, length);
}
}
public class TypedRecordInputStream implements RecordInputStream {
private RecordInputStream is;
public TypedRecordInputStream(String userFileName) throws IOException {
is = Pail.super.openRead(userFileName);
}
public T readObject() throws IOException {
byte[] record = readRawRecord();
if(record==null) return null;
else return _structure.deserialize(record);
}
public void close() throws IOException {
is.close();
}
public byte[] readRawRecord() throws IOException {
return is.readRawRecord();
}
}
public static Pail create(String path, PailSpec spec) throws IOException {
return create(Utils.getFS(path), path, spec);
}
public static Pail create(FileSystem fs, String path, PailSpec spec) throws IOException {
return create(fs, path, spec, true);
}
public static Pail create(String path) throws IOException {
return create(Utils.getFS(path), path);
}
public static Pail create(FileSystem fs, String path) throws IOException {
return create(fs, path, (PailSpec) null);
}
public static Pail create(String path, PailStructure structure) throws IOException {
return create(Utils.getFS(path), path, structure);
}
public static Pail create(FileSystem fs, String path, PailStructure structure) throws IOException {
return create(fs, path, new PailSpec(structure));
}
public static Pail create(String path, PailStructure structure, boolean failOnExists) throws IOException {
return create(Utils.getFS(path), path, structure, failOnExists);
}
public static Pail create(FileSystem fs, String path, PailStructure structure, boolean failOnExists) throws IOException {
return create(fs, path, new PailSpec(structure), failOnExists);
}
public static Pail create(String path, boolean failOnExists) throws IOException {
return create(Utils.getFS(path), path, failOnExists);
}
public static Pail create(FileSystem fs, String path, boolean failOnExists) throws IOException {
return create(fs, path, (PailSpec) null, failOnExists);
}
public static Pail create(String path, PailSpec spec, boolean failOnExists) throws IOException {
return create(Utils.getFS(path), path, spec, failOnExists);
}
public static Pail create(FileSystem fs, String path, PailSpec spec, boolean failOnExists) throws IOException {
Path pathp = new Path(path);
PailFormatFactory.create(spec);
PailSpec existing = getSpec(fs, pathp);
if(failOnExists) {
if(existing!=null) {
throw new IllegalArgumentException("Pail already exists at path " + path + " with spec " + existing.toString());
}
if(fs.exists(pathp))
throw new IllegalArgumentException("Path " + path + " already exists");
}
if(spec!=null && existing!=null) {
if(spec.getName()!=null) {
if(!spec.equals(existing))
throw new IllegalArgumentException("Specs do not match " + spec.toString() + ", " + existing.toString());
} else if(spec.getStructure()!=null) {
if(existing.getStructure()==null || !spec.getStructure().getClass().equals(existing.getStructure().getClass())) {
throw new IllegalArgumentException("Specs do not match " + spec.toString() + ", " + existing.toString());
}
}
}
fs.mkdirs(pathp);
if(existing==null) {
if(spec==null) spec = PailFormatFactory.getDefaultCopy();
if(spec.getName()==null) spec = PailFormatFactory.getDefaultCopy().setStructure(spec.getStructure());
spec.writeToFileSystem(fs, new Path(pathp, META));
}
return new Pail(fs, path);
}
private static PailSpec getSpec(FileSystem fs, Path path) throws IOException {
return (PailSpec) getSpecAndRoot(fs, path)[1];
}
private static String getRoot(FileSystem fs, Path path) throws IOException {
return (String) getSpecAndRoot(fs, path)[0];
}
private static Object[] getSpecAndRoot(FileSystem fs, Path path) throws IOException {
Path curr = path;
Object[] ret = null;
while(true) {
Path meta = new Path(curr, META);
if(fs.exists(meta)) {
if(ret!=null) throw new RuntimeException("At least two meta files up directory tree");
PailSpec spec = PailSpec.readFromFileSystem(fs, meta);
ret = new Object[] {curr.toString(), spec};
}
if(curr.depth()==0) break;
curr = curr.getParent();
}
if(ret==null) ret = new Object[] {null, null};
return ret;
}
private PailFormat _format;
private PailSpec _spec;
private PailStructure<T> _structure;
private String _root;
private FileSystem _fs;
public Pail(String path) throws IOException {
this(Utils.getFS(path), path);
}
public Pail(FileSystem fs, String path) throws IOException {
super(path);
_fs = fs;
_root = getRoot(fs, new Path(path));
if(_root==null || !fs.exists(new Path(path))) throw new IllegalArgumentException("Pail does not exist at path " + path);
_spec = getSpec(fs, new Path(path));
_structure = _spec.getStructure();
_format = PailFormatFactory.create(_spec);
}
public FileSystem getFileSystem() {
return _fs;
}
public TypedRecordOutputStream openWrite() throws IOException {
return openWrite(UUID.randomUUID().toString(), false);
}
@Override
public TypedRecordOutputStream openWrite(String subFileName, boolean overwrite) throws IOException {
if(subFileName.contains(META)) throw new IllegalArgumentException("Illegal user file name " + subFileName);
checkPathValidity(subFileName);
return new TypedRecordOutputStream(subFileName, overwrite);
}
@Override
public TypedRecordInputStream openRead(String userfilename) throws IOException {
checkPathValidity(userfilename);
checkValidStructure(userfilename);
return new TypedRecordInputStream(userfilename);
}
protected void checkPathValidity(String subFileName) {
List<String> components = Utils.componentize(subFileName);
for(String s: components) {
if(s.startsWith("_")) {
throw new IllegalArgumentException("Cannot have underscores in path names " + subFileName);
}
}
}
public Pail<T> getSubPail(int... attrs) throws IOException {
List<String> elems = new ArrayList<String>();
for(int i: attrs) {
elems.add("" + i);
}
String relPath = Utils.join(elems, "/");
return getSubPail(relPath);
}
public Pail<T> getSubPail(String relpath) throws IOException {
mkdirs(new Path(getInstanceRoot(), relpath));
return new Pail(_fs, new Path(getInstanceRoot(), relpath).toString());
}
public PailSpec getSpec() {
return _spec;
}
public PailFormat getFormat() {
return _format;
}
public String getRoot() {
return _root;
}
public boolean atRoot() {
Path instanceRoot = new Path(getInstanceRoot()).makeQualified(_fs);
Path root = new Path(getRoot()).makeQualified(_fs);
return root.equals(instanceRoot);
}
public List<String> getAttrs() {
return Utils.stripRoot(Utils.componentize(getRoot()), Utils.componentize(getInstanceRoot()));
}
//returns if formats are same
private boolean checkCombineValidity(Pail p, CopyArgs args) throws IOException {
if(args.force) return true;
PailSpec mine = getSpec();
PailSpec other = p.getSpec();
PailStructure structure = mine.getStructure();
boolean typesSame = structure.getType().equals(other.getStructure().getType());
//can always append into a "raw" pail
if(!structure.getType().equals(new byte[0].getClass()) && !typesSame)
throw new IllegalArgumentException("Cannot combine two pails of different types unless target pail is raw");
//check that structure will be maintained
for(String name: p.getUserFileNames()) {
checkValidStructure(name);
}
return mine.getName().equals(other.getName()) && mine.getArgs().equals(other.getArgs());
}
public Pail snapshot(String path) throws IOException {
Pail ret = createEmptyMimic(path);
ret.copyAppend(this, RenameMode.NO_RENAME);
return ret;
}
public void clear() throws IOException {
for(Path p: getStoredFiles()) {
delete(p, false);
}
}
public void deleteSnapshot(Pail snapshot) throws IOException {
for(String username: snapshot.getUserFileNames()) {
delete(username);
}
}
public Pail createEmptyMimic(String path) throws IOException {
FileSystem otherFs = Utils.getFS(path);
if(getSpec(otherFs, new Path(path))!=null) {
throw new IllegalArgumentException("Cannot make empty mimic at " + path + " because it is a subdir of a pail");
}
if(otherFs.exists(new Path(path))) {
throw new IllegalArgumentException(path + " already exists");
}
return Pail.create(otherFs, path, getSpec(), true);
}
public void coerce(String path, String name, Map<String, Object> args) throws IOException {
Pail.create(path, new PailSpec(name, args).setStructure(getSpec().getStructure())).copyAppend(this);
}
public void coerce(FileSystem fs, String path, String name, Map<String, Object> args) throws IOException {
Pail.create(fs, path, new PailSpec(name, args).setStructure(getSpec().getStructure())).copyAppend(this);
}
public void copyAppend(Pail p) throws IOException {
copyAppend(p, new CopyArgs());
}
public void copyAppend(Pail p, int renameMode) throws IOException {
CopyArgs args = new CopyArgs();
args.renameMode = renameMode;
copyAppend(p, args);
}
protected String getQualifiedRoot(Pail p) {
Path path = new Path(p.getInstanceRoot());
return path.makeQualified(p._fs).toString();
}
/**
* Copy append will copy all the files from p into this pail. Appending maintains the
* structure that was present in p.
*
*/
public void copyAppend(Pail p, CopyArgs args) throws IOException {
args = new CopyArgs(args);
if(args.renameMode==null) args.renameMode = RenameMode.ALWAYS_RENAME;
boolean formatsSame = checkCombineValidity(p, args);
String sourceQual = getQualifiedRoot(p);
String destQual = getQualifiedRoot(this);
if(formatsSame) {
BalancedDistcp.distcp(sourceQual, destQual, args.renameMode, new PailPathLister(args.copyMetadata), EXTENSION);
} else {
Coercer.coerce(sourceQual, destQual, args.renameMode, new PailPathLister(args.copyMetadata), p.getFormat(), getFormat(), EXTENSION);
}
}
public void moveAppend(Pail p) throws IOException {
moveAppend(p, new CopyArgs());
}
public void moveAppend(Pail p, int renameMode) throws IOException {
CopyArgs args = new CopyArgs();
args.renameMode = renameMode;
moveAppend(p, args);
}
public void moveAppend(Pail p, CopyArgs args) throws IOException {
args = new CopyArgs(args);
if(args.renameMode==null) args.renameMode = RenameMode.ALWAYS_RENAME;
boolean formatsSame = checkCombineValidity(p, args);
if(!p._fs.getUri().equals(_fs.getUri())) throw new IllegalArgumentException("Cannot move append between different filesystems");
if(!formatsSame) throw new IllegalArgumentException("Cannot move append different format pails together");
for(String name: p.getUserFileNames()) {
String parent = new Path(name).getParent().toString();
_fs.mkdirs(new Path(getInstanceRoot() + "/" + parent));
Path storedPath = p.toStoredPath(name);
Path targetPath = toStoredPath(name);
if(_fs.exists(targetPath) || args.renameMode == RenameMode.ALWAYS_RENAME) {
if(args.renameMode == RenameMode.NO_RENAME)
throw new IllegalArgumentException("Collision of filenames " + targetPath.toString());
if(parent.equals("")) targetPath = toStoredPath("ma_" + UUID.randomUUID().toString());
else targetPath = toStoredPath(parent + "/ma_" + UUID.randomUUID().toString());
}
_fs.rename(storedPath, targetPath);
}
if(args.copyMetadata) {
for(String metaName: p.getMetadataFileNames()) {
Path source = p.toStoredMetadataPath(metaName);
Path dest = toStoredMetadataPath(metaName);
if(_fs.exists(dest)) {
throw new IllegalArgumentException("Metadata collision: " + source.toString() + " -> " + dest.toString());
}
_fs.rename(source, dest);
}
}
}
public void absorb(Pail p) throws IOException {
absorb(p, new CopyArgs());
}
public void absorb(Pail p, int renameMode) throws IOException {
CopyArgs args = new CopyArgs();
args.renameMode = renameMode;
absorb(p, args);
}
public void absorb(Pail p, CopyArgs args) throws IOException {
args = new CopyArgs(args);
if(args.renameMode==null) args.renameMode = RenameMode.ALWAYS_RENAME;
boolean formatsSame = checkCombineValidity(p, args);
if(formatsSame && p._fs.getUri().equals(_fs.getUri())) {
moveAppend(p, args);
} else {
copyAppend(p, args);
//TODO: should we go ahead and clear out the input pail for consistency?
}
}
public void s3ConsistencyFix() throws IOException {
for(Path p: getStoredFiles()) {
try {
_fs.getFileStatus(p);
} catch(FileNotFoundException e) {
LOG.info("Fixing file: " + p);
_fs.create(p, true).close();
}
}
}
public void consolidate() throws IOException {
consolidate(Consolidator.DEFAULT_CONSOLIDATION_SIZE);
}
public void consolidate(long maxSize) throws IOException {
List<String> toCheck = new ArrayList<String>();
toCheck.add("");
PailStructure structure = getSpec().getStructure();
List<String> consolidatedirs = new ArrayList<String>();
while(toCheck.size()>0) {
String dir = toCheck.remove(0);
List<String> dirComponents = componentsFromRoot(dir);
if(structure.isValidTarget(dirComponents.toArray(new String[dirComponents.size()]))) {
consolidatedirs.add(toFullPath(dir));
} else {
FileStatus[] contents = listStatus(new Path(toFullPath(dir)));
for(FileStatus f: contents) {
if(!f.isDir()) {
if(f.getPath().toString().endsWith(EXTENSION))
throw new IllegalStateException(f.getPath().toString() + " is not a dir and breaks the structure of " + getInstanceRoot());
} else {
String newDir;
if(dir.length()==0) newDir = f.getPath().getName();
else newDir = dir + "/" + f.getPath().getName();
toCheck.add(newDir);
}
}
}
}
Consolidator.consolidate(_fs, _format, new PailPathLister(false), consolidatedirs, maxSize, EXTENSION);
}
@Override
protected RecordInputStream createInputStream(Path path) throws IOException {
return _format.getInputStream(_fs, path);
}
@Override
protected RecordOutputStream createOutputStream(Path path) throws IOException {
return _format.getOutputStream(_fs, path);
}
@Override
protected boolean delete(Path path, boolean recursive) throws IOException {
return _fs.delete(path, recursive);
}
@Override
protected boolean exists(Path path) throws IOException {
return _fs.exists(path);
}
@Override
protected boolean rename(Path source, Path dest) throws IOException {
return _fs.rename(source, dest);
}
@Override
protected boolean mkdirs(Path path) throws IOException {
return _fs.mkdirs(path);
}
@Override
protected FileStatus[] listStatus(Path path) throws IOException {
FileStatus[] arr = _fs.listStatus(path);
List<FileStatus> ret = new ArrayList<FileStatus>();
for(FileStatus fs: arr) {
if(!fs.isDir() || !fs.getPath().getName().startsWith("_")) {
ret.add(fs);
}
}
return ret.toArray(new FileStatus[ret.size()]);
}
protected String toFullPath(String relpath) {
Path p;
if(relpath.length()==0) p = new Path(getInstanceRoot());
else p = new Path(getInstanceRoot(), relpath);
return p.toString();
}
protected List<String> componentsFromRoot(String relpath) {
String fullpath = toFullPath(relpath);
List<String> full = Utils.componentize(fullpath);
List<String> root = Utils.componentize(getRoot());
return Utils.stripRoot(root, full);
}
protected void checkValidStructure(String userfilename) {
List<String> full = componentsFromRoot(userfilename);
full.remove(full.size()-1);
//hack to get around how hadoop does outputs --> _temporary and _attempt*
while(full.size()>0 && full.get(0).startsWith("_")) {
full.remove(0);
}
if(!getSpec().getStructure().isValidTarget(full.toArray(new String[full.size()]))) {
throw new IllegalArgumentException(
userfilename + " is not valid with the pail structure " + getSpec().toString() +
" --> " + full.toString());
}
}
protected static class PailPathLister implements PathLister {
boolean _includeMeta;
public PailPathLister() {
this(true);
}
public PailPathLister(boolean includeMeta) {
_includeMeta = includeMeta;
}
public List<Path> getFiles(FileSystem fs, String path) {
try {
Pail p = new Pail(fs, path);
List<Path> ret;
if(_includeMeta) {
ret = p.getStoredFilesAndMetadata();
} else {
ret = p.getStoredFiles();
}
return ret;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public boolean isEmpty() throws IOException {
PailIterator it = iterator();
boolean ret = !it.hasNext();
it.close();
return ret;
}
public PailIterator iterator() {
return new PailIterator();
}
public class PailIterator implements Iterator<T> {
private List<String> filesleft;
private TypedRecordInputStream curr = null;
private T nextRecord;
public PailIterator() {
try {
filesleft = getUserFileNames();
} catch(IOException e) {
throw new RuntimeException(e);
}
getNextRecord();
}
private void getNextRecord() {
try {
while(curr==null || (nextRecord = curr.readObject()) == null) {
if(curr!=null) curr.close();
if(filesleft.size()==0) break;
curr = openRead(filesleft.remove(0));
}
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public boolean hasNext() {
return nextRecord != null;
}
public T next() {
T ret = nextRecord;
getNextRecord();
return ret;
}
public void close() throws IOException {
if(curr!=null) {
curr.close();
}
}
public void remove() {
throw new UnsupportedOperationException("Cannot remove records from a pail");
}
}
} | src/jvm/backtype/hadoop/pail/Pail.java | package backtype.hadoop.pail;
import backtype.hadoop.BalancedDistcp;
import backtype.hadoop.Coercer;
import backtype.hadoop.Consolidator;
import backtype.hadoop.PathLister;
import backtype.hadoop.RenameMode;
import backtype.hadoop.formats.RecordInputStream;
import backtype.hadoop.formats.RecordOutputStream;
import backtype.support.Utils;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.log4j.Logger;
public class Pail<T> extends AbstractPail implements Iterable<T>{
public static Logger LOG = Logger.getLogger(Pail.class);
public static final String META = "pail.meta";
public class TypedRecordOutputStream implements RecordOutputStream {
private HashMap<String, RecordOutputStream> _workers = new HashMap<String, RecordOutputStream>();
private String _userfilename;
private boolean _overwrite;
public TypedRecordOutputStream(String userfilename, boolean overwrite) {
_userfilename = userfilename;
_overwrite = overwrite;
}
public void writeObject(T obj) throws IOException {
List<String> rootAttrs = _structure.getTarget(obj);
List<String> attrs = makeRelative(rootAttrs);
String targetDir = Utils.join(attrs, "/");
if(!_workers.containsKey(targetDir)) {
Path p;
if(targetDir.length()==0) p = new Path(_userfilename);
else p = new Path(targetDir, _userfilename);
List<String> totalAttrs = componentsFromRoot(p.toString());
if(!_structure.isValidTarget(totalAttrs.toArray(new String[totalAttrs.size()]))) {
throw new IllegalArgumentException("Cannot write object " + obj.toString() + " to " + p.toString() +
". Conflicts with the structure of the datastore.");
}
_workers.put(targetDir, Pail.super.openWrite(p.toString(), _overwrite));
}
RecordOutputStream os = _workers.get(targetDir);
os.writeRaw(_structure.serialize(obj));
}
public void writeObjects(T... objs) throws IOException {
for(T obj: objs) {
writeObject(obj);
}
}
public void close() throws IOException {
for(RecordOutputStream os: _workers.values()) {
os.close();
}
}
protected List<String> makeRelative(List<String> attrs) {
return Utils.stripRoot(getAttrs(), attrs);
}
public void writeRaw(byte[] record) throws IOException {
writeRaw(record, 0, record.length);
}
public void writeRaw(byte[] record, int start, int length) throws IOException {
if(!_workers.containsKey(_userfilename)) {
checkValidStructure(_userfilename);
_workers.put(_userfilename, Pail.super.openWrite(_userfilename, _overwrite));
}
_workers.get(_userfilename).writeRaw(record, start, length);
}
}
public class TypedRecordInputStream implements RecordInputStream {
private RecordInputStream is;
public TypedRecordInputStream(String userFileName) throws IOException {
is = Pail.super.openRead(userFileName);
}
public T readObject() throws IOException {
byte[] record = readRawRecord();
if(record==null) return null;
else return _structure.deserialize(record);
}
public void close() throws IOException {
is.close();
}
public byte[] readRawRecord() throws IOException {
return is.readRawRecord();
}
}
public static Pail create(String path, PailSpec spec) throws IOException {
return create(Utils.getFS(path), path, spec);
}
public static Pail create(FileSystem fs, String path, PailSpec spec) throws IOException {
return create(fs, path, spec, true);
}
public static Pail create(String path) throws IOException {
return create(Utils.getFS(path), path);
}
public static Pail create(FileSystem fs, String path) throws IOException {
return create(fs, path, (PailSpec) null);
}
public static Pail create(String path, PailStructure structure) throws IOException {
return create(Utils.getFS(path), path, structure);
}
public static Pail create(FileSystem fs, String path, PailStructure structure) throws IOException {
return create(fs, path, new PailSpec(structure));
}
public static Pail create(String path, PailStructure structure, boolean failOnExists) throws IOException {
return create(Utils.getFS(path), path, structure, failOnExists);
}
public static Pail create(FileSystem fs, String path, PailStructure structure, boolean failOnExists) throws IOException {
return create(fs, path, new PailSpec(structure), failOnExists);
}
public static Pail create(String path, boolean failOnExists) throws IOException {
return create(Utils.getFS(path), path, failOnExists);
}
public static Pail create(FileSystem fs, String path, boolean failOnExists) throws IOException {
return create(fs, path, (PailSpec) null, failOnExists);
}
public static Pail create(String path, PailSpec spec, boolean failOnExists) throws IOException {
return create(Utils.getFS(path), path, spec, failOnExists);
}
public static Pail create(FileSystem fs, String path, PailSpec spec, boolean failOnExists) throws IOException {
Path pathp = new Path(path);
PailFormatFactory.create(spec);
PailSpec existing = getSpec(fs, pathp);
if(failOnExists) {
if(existing!=null) {
throw new IllegalArgumentException("Pail already exists at path " + path + " with spec " + existing.toString());
}
if(fs.exists(pathp))
throw new IllegalArgumentException("Path " + path + " already exists");
}
if(spec!=null && existing!=null) {
if(spec.getName()!=null) {
if(!spec.equals(existing))
throw new IllegalArgumentException("Specs do not match " + spec.toString() + ", " + existing.toString());
} else if(spec.getStructure()!=null) {
if(existing.getStructure()==null || !spec.getStructure().getClass().equals(existing.getStructure().getClass())) {
throw new IllegalArgumentException("Specs do not match " + spec.toString() + ", " + existing.toString());
}
}
}
fs.mkdirs(pathp);
if(existing==null) {
if(spec==null) spec = PailFormatFactory.getDefaultCopy();
if(spec.getName()==null) spec = PailFormatFactory.getDefaultCopy().setStructure(spec.getStructure());
spec.writeToFileSystem(fs, new Path(pathp, META));
}
return new Pail(fs, path);
}
private static PailSpec getSpec(FileSystem fs, Path path) throws IOException {
return (PailSpec) getSpecAndRoot(fs, path)[1];
}
private static String getRoot(FileSystem fs, Path path) throws IOException {
return (String) getSpecAndRoot(fs, path)[0];
}
private static Object[] getSpecAndRoot(FileSystem fs, Path path) throws IOException {
Path curr = path;
Object[] ret = null;
while(true) {
Path meta = new Path(curr, META);
if(fs.exists(meta)) {
if(ret!=null) throw new RuntimeException("At least two meta files up directory tree");
PailSpec spec = PailSpec.readFromFileSystem(fs, meta);
ret = new Object[] {curr.toString(), spec};
}
if(curr.depth()==0) break;
curr = curr.getParent();
}
if(ret==null) ret = new Object[] {null, null};
return ret;
}
private PailFormat _format;
private PailSpec _spec;
private PailStructure<T> _structure;
private String _root;
private FileSystem _fs;
public Pail(String path) throws IOException {
this(Utils.getFS(path), path);
}
public Pail(FileSystem fs, String path) throws IOException {
super(path);
_fs = fs;
_root = getRoot(fs, new Path(path));
if(_root==null || !fs.exists(new Path(path))) throw new IllegalArgumentException("Pail does not exist at path " + path);
_spec = getSpec(fs, new Path(path));
_structure = _spec.getStructure();
_format = PailFormatFactory.create(_spec);
}
public FileSystem getFileSystem() {
return _fs;
}
public TypedRecordOutputStream openWrite() throws IOException {
return openWrite(UUID.randomUUID().toString(), false);
}
@Override
public TypedRecordOutputStream openWrite(String subFileName, boolean overwrite) throws IOException {
if(subFileName.contains(META)) throw new IllegalArgumentException("Illegal user file name " + subFileName);
checkPathValidity(subFileName);
return new TypedRecordOutputStream(subFileName, overwrite);
}
@Override
public TypedRecordInputStream openRead(String userfilename) throws IOException {
checkPathValidity(userfilename);
checkValidStructure(userfilename);
return new TypedRecordInputStream(userfilename);
}
protected void checkPathValidity(String subFileName) {
List<String> components = Utils.componentize(subFileName);
for(String s: components) {
if(s.startsWith("_")) {
throw new IllegalArgumentException("Cannot have underscores in path names " + subFileName);
}
}
}
public Pail getSubPail(int... attrs) throws IOException {
List<String> elems = new ArrayList<String>();
for(int i: attrs) {
elems.add("" + i);
}
String relPath = Utils.join(elems, "/");
return getSubPail(relPath);
}
public Pail getSubPail(String relpath) throws IOException {
mkdirs(new Path(getInstanceRoot(), relpath));
return new Pail(_fs, new Path(getInstanceRoot(), relpath).toString());
}
public PailSpec getSpec() {
return _spec;
}
public PailFormat getFormat() {
return _format;
}
public String getRoot() {
return _root;
}
public boolean atRoot() {
Path instanceRoot = new Path(getInstanceRoot()).makeQualified(_fs);
Path root = new Path(getRoot()).makeQualified(_fs);
return root.equals(instanceRoot);
}
public List<String> getAttrs() {
return Utils.stripRoot(Utils.componentize(getRoot()), Utils.componentize(getInstanceRoot()));
}
//returns if formats are same
private boolean checkCombineValidity(Pail p, CopyArgs args) throws IOException {
if(args.force) return true;
PailSpec mine = getSpec();
PailSpec other = p.getSpec();
PailStructure structure = mine.getStructure();
boolean typesSame = structure.getType().equals(other.getStructure().getType());
//can always append into a "raw" pail
if(!structure.getType().equals(new byte[0].getClass()) && !typesSame)
throw new IllegalArgumentException("Cannot combine two pails of different types unless target pail is raw");
//check that structure will be maintained
for(String name: p.getUserFileNames()) {
checkValidStructure(name);
}
return mine.getName().equals(other.getName()) && mine.getArgs().equals(other.getArgs());
}
public Pail snapshot(String path) throws IOException {
Pail ret = createEmptyMimic(path);
ret.copyAppend(this, RenameMode.NO_RENAME);
return ret;
}
public void clear() throws IOException {
for(Path p: getStoredFiles()) {
delete(p, false);
}
}
public void deleteSnapshot(Pail snapshot) throws IOException {
for(String username: snapshot.getUserFileNames()) {
delete(username);
}
}
public Pail createEmptyMimic(String path) throws IOException {
FileSystem otherFs = Utils.getFS(path);
if(getSpec(otherFs, new Path(path))!=null) {
throw new IllegalArgumentException("Cannot make empty mimic at " + path + " because it is a subdir of a pail");
}
if(otherFs.exists(new Path(path))) {
throw new IllegalArgumentException(path + " already exists");
}
return Pail.create(otherFs, path, getSpec(), true);
}
public void coerce(String path, String name, Map<String, Object> args) throws IOException {
Pail.create(path, new PailSpec(name, args).setStructure(getSpec().getStructure())).copyAppend(this);
}
public void coerce(FileSystem fs, String path, String name, Map<String, Object> args) throws IOException {
Pail.create(fs, path, new PailSpec(name, args).setStructure(getSpec().getStructure())).copyAppend(this);
}
public void copyAppend(Pail p) throws IOException {
copyAppend(p, new CopyArgs());
}
public void copyAppend(Pail p, int renameMode) throws IOException {
CopyArgs args = new CopyArgs();
args.renameMode = renameMode;
copyAppend(p, args);
}
protected String getQualifiedRoot(Pail p) {
Path path = new Path(p.getInstanceRoot());
return path.makeQualified(p._fs).toString();
}
/**
* Copy append will copy all the files from p into this pail. Appending maintains the
* structure that was present in p.
*
*/
public void copyAppend(Pail p, CopyArgs args) throws IOException {
args = new CopyArgs(args);
if(args.renameMode==null) args.renameMode = RenameMode.ALWAYS_RENAME;
boolean formatsSame = checkCombineValidity(p, args);
String sourceQual = getQualifiedRoot(p);
String destQual = getQualifiedRoot(this);
if(formatsSame) {
BalancedDistcp.distcp(sourceQual, destQual, args.renameMode, new PailPathLister(args.copyMetadata), EXTENSION);
} else {
Coercer.coerce(sourceQual, destQual, args.renameMode, new PailPathLister(args.copyMetadata), p.getFormat(), getFormat(), EXTENSION);
}
}
public void moveAppend(Pail p) throws IOException {
moveAppend(p, new CopyArgs());
}
public void moveAppend(Pail p, int renameMode) throws IOException {
CopyArgs args = new CopyArgs();
args.renameMode = renameMode;
moveAppend(p, args);
}
public void moveAppend(Pail p, CopyArgs args) throws IOException {
args = new CopyArgs(args);
if(args.renameMode==null) args.renameMode = RenameMode.ALWAYS_RENAME;
boolean formatsSame = checkCombineValidity(p, args);
if(!p._fs.getUri().equals(_fs.getUri())) throw new IllegalArgumentException("Cannot move append between different filesystems");
if(!formatsSame) throw new IllegalArgumentException("Cannot move append different format pails together");
for(String name: p.getUserFileNames()) {
String parent = new Path(name).getParent().toString();
_fs.mkdirs(new Path(getInstanceRoot() + "/" + parent));
Path storedPath = p.toStoredPath(name);
Path targetPath = toStoredPath(name);
if(_fs.exists(targetPath) || args.renameMode == RenameMode.ALWAYS_RENAME) {
if(args.renameMode == RenameMode.NO_RENAME)
throw new IllegalArgumentException("Collision of filenames " + targetPath.toString());
if(parent.equals("")) targetPath = toStoredPath("ma_" + UUID.randomUUID().toString());
else targetPath = toStoredPath(parent + "/ma_" + UUID.randomUUID().toString());
}
_fs.rename(storedPath, targetPath);
}
if(args.copyMetadata) {
for(String metaName: p.getMetadataFileNames()) {
Path source = p.toStoredMetadataPath(metaName);
Path dest = toStoredMetadataPath(metaName);
if(_fs.exists(dest)) {
throw new IllegalArgumentException("Metadata collision: " + source.toString() + " -> " + dest.toString());
}
_fs.rename(source, dest);
}
}
}
public void absorb(Pail p) throws IOException {
absorb(p, new CopyArgs());
}
public void absorb(Pail p, int renameMode) throws IOException {
CopyArgs args = new CopyArgs();
args.renameMode = renameMode;
absorb(p, args);
}
public void absorb(Pail p, CopyArgs args) throws IOException {
args = new CopyArgs(args);
if(args.renameMode==null) args.renameMode = RenameMode.ALWAYS_RENAME;
boolean formatsSame = checkCombineValidity(p, args);
if(formatsSame && p._fs.getUri().equals(_fs.getUri())) {
moveAppend(p, args);
} else {
copyAppend(p, args);
//TODO: should we go ahead and clear out the input pail for consistency?
}
}
public void s3ConsistencyFix() throws IOException {
for(Path p: getStoredFiles()) {
try {
_fs.getFileStatus(p);
} catch(FileNotFoundException e) {
LOG.info("Fixing file: " + p);
_fs.create(p, true).close();
}
}
}
public void consolidate() throws IOException {
consolidate(Consolidator.DEFAULT_CONSOLIDATION_SIZE);
}
public void consolidate(long maxSize) throws IOException {
List<String> toCheck = new ArrayList<String>();
toCheck.add("");
PailStructure structure = getSpec().getStructure();
List<String> consolidatedirs = new ArrayList<String>();
while(toCheck.size()>0) {
String dir = toCheck.remove(0);
List<String> dirComponents = componentsFromRoot(dir);
if(structure.isValidTarget(dirComponents.toArray(new String[dirComponents.size()]))) {
consolidatedirs.add(toFullPath(dir));
} else {
FileStatus[] contents = listStatus(new Path(toFullPath(dir)));
for(FileStatus f: contents) {
if(!f.isDir()) {
if(f.getPath().toString().endsWith(EXTENSION))
throw new IllegalStateException(f.getPath().toString() + " is not a dir and breaks the structure of " + getInstanceRoot());
} else {
String newDir;
if(dir.length()==0) newDir = f.getPath().getName();
else newDir = dir + "/" + f.getPath().getName();
toCheck.add(newDir);
}
}
}
}
Consolidator.consolidate(_fs, _format, new PailPathLister(false), consolidatedirs, maxSize, EXTENSION);
}
@Override
protected RecordInputStream createInputStream(Path path) throws IOException {
return _format.getInputStream(_fs, path);
}
@Override
protected RecordOutputStream createOutputStream(Path path) throws IOException {
return _format.getOutputStream(_fs, path);
}
@Override
protected boolean delete(Path path, boolean recursive) throws IOException {
return _fs.delete(path, recursive);
}
@Override
protected boolean exists(Path path) throws IOException {
return _fs.exists(path);
}
@Override
protected boolean rename(Path source, Path dest) throws IOException {
return _fs.rename(source, dest);
}
@Override
protected boolean mkdirs(Path path) throws IOException {
return _fs.mkdirs(path);
}
@Override
protected FileStatus[] listStatus(Path path) throws IOException {
FileStatus[] arr = _fs.listStatus(path);
List<FileStatus> ret = new ArrayList<FileStatus>();
for(FileStatus fs: arr) {
if(!fs.isDir() || !fs.getPath().getName().startsWith("_")) {
ret.add(fs);
}
}
return ret.toArray(new FileStatus[ret.size()]);
}
protected String toFullPath(String relpath) {
Path p;
if(relpath.length()==0) p = new Path(getInstanceRoot());
else p = new Path(getInstanceRoot(), relpath);
return p.toString();
}
protected List<String> componentsFromRoot(String relpath) {
String fullpath = toFullPath(relpath);
List<String> full = Utils.componentize(fullpath);
List<String> root = Utils.componentize(getRoot());
return Utils.stripRoot(root, full);
}
protected void checkValidStructure(String userfilename) {
List<String> full = componentsFromRoot(userfilename);
full.remove(full.size()-1);
//hack to get around how hadoop does outputs --> _temporary and _attempt*
while(full.size()>0 && full.get(0).startsWith("_")) {
full.remove(0);
}
if(!getSpec().getStructure().isValidTarget(full.toArray(new String[full.size()]))) {
throw new IllegalArgumentException(
userfilename + " is not valid with the pail structure " + getSpec().toString() +
" --> " + full.toString());
}
}
protected static class PailPathLister implements PathLister {
boolean _includeMeta;
public PailPathLister() {
this(true);
}
public PailPathLister(boolean includeMeta) {
_includeMeta = includeMeta;
}
public List<Path> getFiles(FileSystem fs, String path) {
try {
Pail p = new Pail(fs, path);
List<Path> ret;
if(_includeMeta) {
ret = p.getStoredFilesAndMetadata();
} else {
ret = p.getStoredFiles();
}
return ret;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public boolean isEmpty() throws IOException {
PailIterator it = iterator();
boolean ret = !it.hasNext();
it.close();
return ret;
}
public PailIterator iterator() {
return new PailIterator();
}
public class PailIterator implements Iterator<T> {
private List<String> filesleft;
private TypedRecordInputStream curr = null;
private T nextRecord;
public PailIterator() {
try {
filesleft = getUserFileNames();
} catch(IOException e) {
throw new RuntimeException(e);
}
getNextRecord();
}
private void getNextRecord() {
try {
while(curr==null || (nextRecord = curr.readObject()) == null) {
if(curr!=null) curr.close();
if(filesleft.size()==0) break;
curr = openRead(filesleft.remove(0));
}
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public boolean hasNext() {
return nextRecord != null;
}
public T next() {
T ret = nextRecord;
getNextRecord();
return ret;
}
public void close() throws IOException {
if(curr!=null) {
curr.close();
}
}
public void remove() {
throw new UnsupportedOperationException("Cannot remove records from a pail");
}
}
} | fix return type of getSubPail
| src/jvm/backtype/hadoop/pail/Pail.java | fix return type of getSubPail |
|
Java | bsd-3-clause | 204b9639b3932a4f652d86a4785be04475d6641a | 0 | bdezonia/zorbage,bdezonia/zorbage | /*
* Zorbage: an algebraic data hierarchy for use in numeric processing.
*
* Copyright (c) 2016-2021 Barry DeZonia All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* Neither the name of the <copyright holder> nor the names of its contributors may
* be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package nom.bdezonia.zorbage.dataview;
import java.math.BigDecimal;
import nom.bdezonia.zorbage.algebra.Allocatable;
import nom.bdezonia.zorbage.algebra.Dimensioned;
import nom.bdezonia.zorbage.coordinates.CoordinateSpace;
import nom.bdezonia.zorbage.coordinates.LinearNdCoordinateSpace;
import nom.bdezonia.zorbage.data.DimensionedDataSource;
import nom.bdezonia.zorbage.data.DimensionedStorage;
/**
*
* @author Barry DeZonia
*
* @param <U>
*/
public class PlaneView<U> implements Dimensioned {
private final int axisNumber0; // number of our 0th axis in the parent data source
private final int axisNumber1; // number of our 1th axis in the parent data source
private final long axisNumber0Size; // dimension of our 0th axis in the parent data source
private final long axisNumber1Size; // dimension of our 1th axis in the parent data source
private final Accessor<U> accessor;
private final DimensionedDataSource<U> data;
/**
* Construct a 2-d view of a {@link DimensionedDataSource} by specifying
* two axis numbers.
*
* @param data The n-d data source the view is being built upon.
* @param axis0 The axis number of the "x" component in the data source. X is
* in quotes here because you can specify the y, x, time, channel
* or whatever other axis is defined for the data source.
* @param axis1 The axis number of the "y" component in the data source. Y is
* in quotes here because you can specify the y, x, time, channel
* or whatever other axis is defined for the data source.
*/
public PlaneView(DimensionedDataSource<U> data, int axis0, int axis1) {
int numD = data.numDimensions();
if (numD == 0)
throw new IllegalArgumentException(
"data source must have at least 1 dimension");
if (axis0 == axis1)
throw new IllegalArgumentException("same coordinate axis specified twice");
if (axis0 >= axis1)
throw new IllegalArgumentException(
"axis specified out of order: all numbers assume left to right declaration");
if (axis0 < 0 || axis0 >= numD)
throw new IllegalArgumentException("coordinate component 0 is outside number of dimensions");
if (axis1 < 0 || ((numD == 1 && axis1 > 1) || (numD > 1 && axis1 >= numD)))
throw new IllegalArgumentException("coordinate component 1 is outside number of dimensions");
this.data = data;
this.axisNumber0 = axis0;
this.axisNumber1 = axis1;
this.axisNumber0Size = data.dimension(axis0);
this.axisNumber1Size = numD == 1 ? 1 : data.dimension(axis1);
switch (numD) {
case 1:
accessor = new Accessor1d<U>(data, axisNumber0, axisNumber1);
break;
case 2:
accessor = new Accessor2d<U>(data);
break;
case 3:
accessor = new Accessor3d<U>(data, axisNumber0, axisNumber1);
break;
case 4:
accessor = new Accessor4d<U>(data, axisNumber0, axisNumber1);
break;
case 5:
accessor = new Accessor5d<U>(data, axisNumber0, axisNumber1);
break;
case 6:
accessor = new Accessor6d<U>(data, axisNumber0, axisNumber1);
break;
case 7:
accessor = new Accessor7d<U>(data, axisNumber0, axisNumber1);
break;
case 8:
accessor = new Accessor8d<U>(data, axisNumber0, axisNumber1);
break;
case 9:
accessor = new Accessor9d<U>(data, axisNumber0, axisNumber1);
break;
case 10:
accessor = new Accessor10d<U>(data, axisNumber0, axisNumber1);
break;
case 11:
accessor = new Accessor11d<U>(data, axisNumber0, axisNumber1);
break;
default:
throw new IllegalArgumentException(
""+numD+" dimensions not yet supported in PlaneView");
}
}
/**
* Returns the {@link DimensionedDataSource} that the PlaneView is attached to.
*/
public DimensionedDataSource<U> getDataSource() {
return data;
}
/**
* Returns the 0th dimension of the view (the width).
*/
public long d0() { return axisNumber0Size; }
/**
* Returns the 1th dimension of the view (the height).
*/
public long d1() { return axisNumber1Size; }
/**
* A view.get() call will pull the value at the view input coordinates
* from the data set into val. No index out of bounds checking is done.
*
* @param i0 0th view input coord
* @param i1 1th view input coord
* @param val The output where the result is placed
*/
public void get(long i0, long i1, U val) {
accessor.get(i0, i1, val);
}
/**
* A planeView.set() call will push the value at the view input
* coordinates into the data set. No index out of bounds checking
* is done.
*
* @param i0 0th view input coord
* @param i1 1th view input coord
* @param val The input that is stored in the underlying data set
*/
public void set(long i0, long i1, U val) {
accessor.set(i0, i1, val);
}
/**
* A planeView.safeGet() call will do a get() call provided the
* passed index coordinate values fit within the view's dimensions.
* If not an exception is thrown instead.
*/
public void safeGet(long i0, long i1, U val) {
if (outOfBounds(i0, i1)) {
throw new IllegalArgumentException("view index out of bounds");
}
else
get(i0, i1, val);
}
/**
* A planeView.safeSet() call will do a set() call provided the
* passed index coordinate values fit within the view's dimensions.
* If not an exception is thrown instead.
*/
public void safeSet(long i0, long i1, U val) {
if (outOfBounds(i0, i1)) {
throw new IllegalArgumentException("view index out of bounds");
}
else
set(i0, i1, val);
}
/**
* Return the column number of 0th index view position
* (i.e. which column is "x" in the view).
*/
public int axisNumber0() {
return axisNumber0;
}
/**
* Return the column number of 1th index view position
* (i.e. which column is "y" in the view).
*/
public int axisNumber1() {
return axisNumber1;
}
/**
* Return the number of dimensions in the view.
*/
@Override
public int numDimensions() {
return 2;
}
/**
* Retrieve each view dimension by index. Throws an exception if
* the dimension index number is outside the view dimensions.
*/
@Override
public long dimension(int d) {
if (d == 0) return axisNumber0Size;
if (d == 1) return axisNumber1Size;
throw new IllegalArgumentException("dimension out of bounds");
}
/**
* Returns the number of dimensions beyond 2 that this PlaneView can manipulate.
* @return
*/
public int getPositionsCount() {
return accessor.getPositionsCount();
}
/**
* Set the position value of one of the dimensions of the PlaneView.
*/
public void setPositionValue(int i, long pos) {
accessor.setPositionValue(i, pos);
}
/**
* Get the position value of one of the dimensions of the PlaneView.
*/
public long getPositionValue(int i) {
return accessor.getPositionValue(i);
}
/**
* Translates the dimensions associated with sliders into their own
* original axis number of the parent data source. Imagine you have
* a 5d dataset. Your "x" and "y" axis numbers set to 1 and 3. The
* planeView stores the 3 other dims as 0, 1, and 2. But their
* original axis numbers in the parent data source were 0, 2, and 4.
* This method maps 0/1/2 into 0/2/4 in this one case.
*
* @param extraDimPos
* @return
*/
public int getDataSourceAxisNumber(int extraDimPos) {
int counted = 0;
for (int i = 0; i < data.numDimensions(); i++) {
if (i == axisNumber0 || i == axisNumber1)
continue;
if (counted == extraDimPos)
return i;
counted++;
}
return -1;
}
/**
* Returns the dimension of extra axis i in the parent data source.
*
* @param extraDimPos
* @return
*/
public long getDataSourceAxisSize(int extraDimPos) {
int pos = getDataSourceAxisNumber(extraDimPos);
return data.dimension(pos);
}
/**
* Returns the model coords of the point on the model currently
* associated with the i0/i1 coords and the current slider
* positions.
*
* @param i0 The 0th component of the point within the d0 x d1 view we are interested in
* @param i1 The 1th component of the point within the d0 x d1 view we are interested in
* @param modelCoords The array to store the output coords in.
*/
public void getModelCoords(long i0, long i1, long[] modelCoords) {
for (int i = 0; i < getPositionsCount(); i++) {
int pos = getDataSourceAxisNumber(i);
long value = getPositionValue(i);
modelCoords[pos] = value;
}
// avoid failure: a 0-d data set would kill code otherwise
if (axisNumber0 < data.numDimensions())
modelCoords[axisNumber0] = i0;
// avoid failure: a 1-d data set would kill code otherwise
if (axisNumber1 < data.numDimensions())
modelCoords[axisNumber1] = i1;
}
/**
* Get a snapshot of a whole plane of data using the current axis positions
* and defined 0th and 1th axis designations. So one can easily generate a
* Y/Z plane where X == 250, for example. As much as feasible pass on the
* units and calibration to the new data source.
*
* @param scratchVar A variable that the routine will use in its calcs.
*
* @return A 2-d data source containing the plane
*/
@SuppressWarnings("unchecked")
public <V extends Allocatable<V>>
DimensionedDataSource<U> copyPlane(U scratchVar)
{
DimensionedDataSource<U> newDs = (DimensionedDataSource<U>)
DimensionedStorage.allocate((V) scratchVar, new long[] {axisNumber0Size,axisNumber1Size});
TwoDView<U> view = new TwoDView<>(newDs);
for (long y = 0; y < axisNumber1Size; y++) {
for (long x = 0; x < axisNumber0Size; x++) {
accessor.get(x, y, scratchVar);
view.set(x, y, scratchVar);
}
}
String d0Str = data.getAxisType(axisNumber0);
String d1Str = data.getAxisType(axisNumber1);
String axes = "["+d0Str+":"+d1Str+"]";
String miniTitle = axes + "slice";
newDs.setName(data.getName() == null ? miniTitle : (miniTitle + " of "+data.getName()));
newDs.setAxisType(0, data.getAxisType(axisNumber0));
newDs.setAxisType(1, data.getAxisType(axisNumber1));
newDs.setAxisUnit(0, data.getAxisUnit(axisNumber0));
newDs.setAxisUnit(1, data.getAxisUnit(axisNumber1));
newDs.setValueType(data.getValueType());
newDs.setValueUnit(data.getValueUnit());
CoordinateSpace origSpace = data.getCoordinateSpace();
if (origSpace instanceof LinearNdCoordinateSpace) {
LinearNdCoordinateSpace origLinSpace =
(LinearNdCoordinateSpace) data.getCoordinateSpace();
BigDecimal[] scales = new BigDecimal[2];
scales[0] = origLinSpace.getScale(axisNumber0);
scales[1] = origLinSpace.getScale(axisNumber1);
BigDecimal[] offsets = new BigDecimal[2];
offsets[0] = origLinSpace.getOffset(axisNumber0);
offsets[1] = origLinSpace.getOffset(axisNumber1);
LinearNdCoordinateSpace newLinSpace = new LinearNdCoordinateSpace(scales, offsets);
newDs.setCoordinateSpace(newLinSpace);
}
return newDs;
}
// ----------------------------------------------------------------------
// PRIVATE DECLARATIONS FOLLOW
// ----------------------------------------------------------------------
// TODO expose these accessors publicly? Will they be useful to someone?
private boolean outOfBounds(long i0, long i1) {
if (i0 < 0 || i0 >= axisNumber0Size) return true;
if (i1 < 0 || i1 >= axisNumber1Size) return true;
return false;
}
private interface Accessor<X> {
void set(long i0, long i1, X value);
void get(long i0, long i1, X value);
int getPositionsCount();
void setPositionValue(int i, long v);
long getPositionValue(int i);
}
private abstract class AccessorBase {
protected PositionMapper posMapper;
private long[] extraDimPositions;
AccessorBase(int numD) {
int size = numD - 2;
if (size < 0) size = 0;
extraDimPositions = new long[size];
}
public int getPositionsCount() {
return extraDimPositions.length;
}
public void setPositionValue(int i, long v) {
if (i < 0 || i >= extraDimPositions.length)
throw new IllegalArgumentException("illegal extra dim position");
extraDimPositions[i] = v;
}
public long getPositionValue(int i) {
if (i < 0 || i >= extraDimPositions.length)
throw new IllegalArgumentException("illegal extra dim position");
return extraDimPositions[i];
}
void setPositionMapper(PositionMapper mapper) {
this.posMapper = mapper;
}
}
private class Accessor1d<X>
extends AccessorBase
implements Accessor<X>
{
private final OneDView<X> view;
Accessor1d(DimensionedDataSource<X> data, int axis0, int axis1) {
super(data.numDimensions());
view = new OneDView<>(data);
}
@Override
public void set(long i0, long i1, X value) {
view.set(i0, value);
}
@Override
public void get(long i0, long i1, X value) {
view.get(i0, value);
}
}
private class Accessor2d<X>
extends AccessorBase
implements Accessor<X>
{
private final TwoDView<X> view;
Accessor2d(DimensionedDataSource<X> data) {
super(data.numDimensions());
view = new TwoDView<>(data);
}
@Override
public void set(long i0, long i1, X value) {
view.set(i0, i1, value);
}
@Override
public void get(long i0, long i1, X value) {
view.get(i0, i1, value);
}
}
// spot checked that i* and u* are correctly ordered
// spot checked that u* are completely specified
private interface PositionMapper {
void setPosition(long i0, long i1);
}
private class Accessor3d<X>
extends AccessorBase
implements Accessor<X>
{
private final ThreeDView<X> view;
private long u0, u1, u2;
Accessor3d(DimensionedDataSource<X> data, int axisNumber0, int axisNumber1) {
super(data.numDimensions());
view = new ThreeDView<>(data);
if (axisNumber0 == 0 && axisNumber1 == 1) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = i1;
u2 = getPositionValue(0);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 2) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = i1;
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 2) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = i1;
}
});
}
else
throw new IllegalArgumentException("missing coordinate combo for 3d "+axisNumber0+" "+axisNumber1);
}
@Override
public void set(long i0, long i1, X value) {
posMapper.setPosition(i0, i1);
view.set(u0, u1, u2, value);
}
@Override
public void get(long i0, long i1, X value) {
posMapper.setPosition(i0, i1);
view.get(u0, u1, u2, value);
}
}
// spot checked that i* and u* are correctly ordered
// spot checked that u* are completely specified
private class Accessor4d<X>
extends AccessorBase
implements Accessor<X>
{
private final FourDView<X> view;
private long u0, u1, u2, u3;
Accessor4d(DimensionedDataSource<X> data, int axisNumber0, int axisNumber1) {
super(data.numDimensions());
view = new FourDView<>(data);
if (axisNumber0 == 0 && axisNumber1 == 1) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = i1;
u2 = getPositionValue(0);
u3 = getPositionValue(1);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 2) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = i1;
u3 = getPositionValue(1);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 3) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = i1;
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 2) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = i1;
u3 = getPositionValue(1);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 3) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = i1;
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 3) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = i1;
}
});
}
else
throw new IllegalArgumentException("missing coordinate combo for 4d "+axisNumber0+" "+axisNumber1);
}
@Override
public void set(long i0, long i1, X value) {
posMapper.setPosition(i0, i1);
view.set(u0, u1, u2, u3, value);
}
@Override
public void get(long i0, long i1, X value) {
posMapper.setPosition(i0, i1);
view.get(u0, u1, u2, u3, value);
}
}
// spot checked that i* and u* are correctly ordered
// spot checked that u* are completely specified
private class Accessor5d<X>
extends AccessorBase
implements Accessor<X>
{
private final FiveDView<X> view;
private long u0, u1, u2, u3, u4;
Accessor5d(DimensionedDataSource<X> data, int axisNumber0, int axisNumber1) {
super(data.numDimensions());
view = new FiveDView<>(data);
if (axisNumber0 == 0 && axisNumber1 == 1) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = i1;
u2 = getPositionValue(0);
u3 = getPositionValue(1);
u4 = getPositionValue(2);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 2) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 3) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 2) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 3) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 3) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = i1;
u4 = getPositionValue(2);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = i1;
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = i1;
}
});
}
else
throw new IllegalArgumentException("missing coordinate combo for 5d "+axisNumber0+" "+axisNumber1);
}
@Override
public void set(long i0, long i1, X value) {
posMapper.setPosition(i0, i1);
view.set(u0, u1, u2, u3, u4, value);
}
@Override
public void get(long i0, long i1, X value) {
posMapper.setPosition(i0, i1);
view.get(u0, u1, u2, u3, u4, value);
}
}
// spot checked that i* and u* are correctly ordered
// spot checked that u* are completely specified
private class Accessor6d<X>
extends AccessorBase
implements Accessor<X>
{
private final SixDView<X> view;
private long u0, u1, u2, u3, u4, u5;
Accessor6d(DimensionedDataSource<X> data, int axisNumber0, int axisNumber1) {
super(data.numDimensions());
view = new SixDView<>(data);
if (axisNumber0 == 0 && axisNumber1 == 1) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = i1;
u2 = getPositionValue(0);
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 2) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 3) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 2) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 3) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 3) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = i1;
u5 = getPositionValue(3);
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = i1;
}
});
}
else if (axisNumber0 == 4 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = i1;
}
});
}
else
throw new IllegalArgumentException("missing coordinate combo for 6d "+axisNumber0+" "+axisNumber1);
}
@Override
public void set(long i0, long i1, X value) {
posMapper.setPosition(i0, i1);
view.set(u0, u1, u2, u3, u4, u5, value);
}
@Override
public void get(long i0, long i1, X value) {
posMapper.setPosition(i0, i1);
view.get(u0, u1, u2, u3, u4, u5, value);
}
}
// spot checked that i* and u* are correctly ordered
// spot checked that u* are completely specified
private class Accessor7d<X>
extends AccessorBase
implements Accessor<X>
{
private final SevenDView<X> view;
private long u0, u1, u2, u3, u4, u5, u6;
Accessor7d(DimensionedDataSource<X> data, int axisNumber0, int axisNumber1) {
super(data.numDimensions());
view = new SevenDView<>(data);
if (axisNumber0 == 0 && axisNumber1 == 1) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = i1;
u2 = getPositionValue(0);
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 2) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 3) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 2) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 3) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 3) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
}
});
}
else if (axisNumber0 == 4 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = i1;
u6 = getPositionValue(4);
}
});
}
else if (axisNumber0 == 4 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = i1;
}
});
}
else if (axisNumber0 == 5 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = i1;
}
});
}
else
throw new IllegalArgumentException("missing coordinate combo for 7d "+axisNumber0+" "+axisNumber1);
}
@Override
public void set(long i0, long i1, X value) {
posMapper.setPosition(i0, i1);
view.set(u0, u1, u2, u3, u4, u5, u6, value);
}
@Override
public void get(long i0, long i1, X value) {
posMapper.setPosition(i0, i1);
view.get(u0, u1, u2, u3, u4, u5, u6, value);
}
}
// spot checked that i* and u* are correctly ordered
// spot checked that u* are completely specified
private class Accessor8d<X>
extends AccessorBase
implements Accessor<X>
{
private final EightDView<X> view;
private long u0, u1, u2, u3, u4, u5, u6, u7;
Accessor8d(DimensionedDataSource<X> data, int axisNumber0, int axisNumber1) {
super(data.numDimensions());
view = new EightDView<>(data);
if (axisNumber0 == 0 && axisNumber1 == 1) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = i1;
u2 = getPositionValue(0);
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 2) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 3) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 2) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 3) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 3) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
}
});
}
else if (axisNumber0 == 4 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
});
}
else if (axisNumber0 == 4 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
}
});
}
else if (axisNumber0 == 4 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
}
});
}
else if (axisNumber0 == 5 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = i1;
u7 = getPositionValue(5);
}
});
}
else if (axisNumber0 == 5 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = getPositionValue(5);
u7 = i1;
}
});
}
else if (axisNumber0 == 6 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = i0;
u7 = i1;
}
});
}
else
throw new IllegalArgumentException("missing coordinate combo for 8d "+axisNumber0+" "+axisNumber1);
}
@Override
public void set(long i0, long i1, X value) {
posMapper.setPosition(i0, i1);
view.set(u0, u1, u2, u3, u4, u5, u6, u7, value);
}
@Override
public void get(long i0, long i1, X value) {
posMapper.setPosition(i0, i1);
view.get(u0, u1, u2, u3, u4, u5, u6, u7, value);
}
}
// spot checked that i* and u* are correctly ordered
// spot checked that u* are completely specified
private class Accessor9d<X>
extends AccessorBase
implements Accessor<X>
{
private final NineDView<X> view;
private long u0, u1, u2, u3, u4, u5, u6, u7, u8;
Accessor9d(DimensionedDataSource<X> data, int axisNumber0, int axisNumber1) {
super(data.numDimensions());
view = new NineDView<>(data);
if (axisNumber0 == 0 && axisNumber1 == 1) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = i1;
u2 = getPositionValue(0);
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 2) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 3) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 8) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 2) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 3) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 8) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 3) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 8) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 8) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
}
});
}
else if (axisNumber0 == 4 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 4 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 4 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 4 && axisNumber1 == 8) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
}
});
}
else if (axisNumber0 == 5 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 5 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 5 && axisNumber1 == 8) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
}
});
}
else if (axisNumber0 == 6 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = i0;
u7 = i1;
u8 = getPositionValue(6);
}
});
}
else if (axisNumber0 == 6 && axisNumber1 == 8) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = i0;
u7 = getPositionValue(6);
u8 = i1;
}
});
}
else if (axisNumber0 == 7 && axisNumber1 == 8) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = getPositionValue(6);
u7 = i0;
u8 = i1;
}
});
}
else
throw new IllegalArgumentException("missing coordinate combo for 9d "+axisNumber0+" "+axisNumber1);
}
@Override
public void set(long i0, long i1, X value) {
posMapper.setPosition(i0, i1);
view.set(u0, u1, u2, u3, u4, u5, u6, u7, u8, value);
}
@Override
public void get(long i0, long i1, X value) {
posMapper.setPosition(i0, i1);
view.get(u0, u1, u2, u3, u4, u5, u6, u7, u8, value);
}
}
// spot checked that i* and u* are correctly ordered
// spot checked that u* are completely specified
private class Accessor10d<X>
extends AccessorBase
implements Accessor<X>
{
private final TenDView<X> view;
private long u0, u1, u2, u3, u4, u5, u6, u7, u8, u9;
Accessor10d(DimensionedDataSource<X> data, int axisNumber0, int axisNumber1) {
super(data.numDimensions());
view = new TenDView<>(data);
if (axisNumber0 == 0 && axisNumber1 == 1) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = i1;
u2 = getPositionValue(0);
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 2) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 3) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 8) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 9) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 2) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 3) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 8) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 9) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 3) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 8) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 9) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 8) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 9) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
}
});
}
else if (axisNumber0 == 4 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 4 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 4 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 4 && axisNumber1 == 8) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 4 && axisNumber1 == 9) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
}
});
}
else if (axisNumber0 == 5 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 5 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 5 && axisNumber1 == 8) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 5 && axisNumber1 == 9) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
}
});
}
else if (axisNumber0 == 6 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = i0;
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 6 && axisNumber1 == 8) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = i0;
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 6 && axisNumber1 == 9) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = i0;
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
}
});
}
else if (axisNumber0 == 7 && axisNumber1 == 8) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = getPositionValue(6);
u7 = i0;
u8 = i1;
u9 = getPositionValue(7);
}
});
}
else if (axisNumber0 == 7 && axisNumber1 == 9) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = getPositionValue(6);
u7 = i0;
u8 = getPositionValue(7);
u9 = i1;
}
});
}
else if (axisNumber0 == 8 && axisNumber1 == 9) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = getPositionValue(6);
u7 = getPositionValue(7);
u8 = i0;
u9 = i1;
}
});
}
else
throw new IllegalArgumentException("missing coordinate combo for 10d "+axisNumber0+" "+axisNumber1);
}
@Override
public void set(long i0, long i1, X value) {
posMapper.setPosition(i0, i1);
view.set(u0, u1, u2, u3, u4, u5, u6, u7, u8, u9, value);
}
@Override
public void get(long i0, long i1, X value) {
posMapper.setPosition(i0, i1);
view.get(u0, u1, u2, u3, u4, u5, u6, u7, u8, u9, value);
}
}
// spot checked that i* and u* are correctly ordered
// spot checked that u* are completely specified
private class Accessor11d<X>
extends AccessorBase
implements Accessor<X>
{
private final ElevenDView<X> view;
private long u0, u1, u2, u3, u4, u5, u6, u7, u8, u9, u10;
Accessor11d(DimensionedDataSource<X> data, int axisNumber0, int axisNumber1) {
super(data.numDimensions());
view = new ElevenDView<>(data);
if (axisNumber0 == 0 && axisNumber1 == 1) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = i1;
u2 = getPositionValue(0);
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 2) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 3) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 8) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 9) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 0 && axisNumber1 == 10) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = getPositionValue(8);
u10 = i1;
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 2) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 3) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 8) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 9) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 1 && axisNumber1 == 10) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = getPositionValue(8);
u10 = i1;
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 3) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 8) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 9) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 2 && axisNumber1 == 10) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = getPositionValue(8);
u10 = i1;
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 4) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 8) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 9) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 3 && axisNumber1 == 10) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = getPositionValue(8);
u10 = i1;
}
});
}
else if (axisNumber0 == 4 && axisNumber1 == 5) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 4 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 4 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 4 && axisNumber1 == 8) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 4 && axisNumber1 == 9) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 4 && axisNumber1 == 10) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = getPositionValue(8);
u10 = i1;
}
});
}
else if (axisNumber0 == 5 && axisNumber1 == 6) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 5 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 5 && axisNumber1 == 8) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 5 && axisNumber1 == 9) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 5 && axisNumber1 == 10) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = getPositionValue(8);
u10 = i1;
}
});
}
else if (axisNumber0 == 6 && axisNumber1 == 7) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = i0;
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 6 && axisNumber1 == 8) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = i0;
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 6 && axisNumber1 == 9) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = i0;
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 6 && axisNumber1 == 10) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = i0;
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = getPositionValue(8);
u10 = i1;
}
});
}
else if (axisNumber0 == 7 && axisNumber1 == 8) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = getPositionValue(6);
u7 = i0;
u8 = i1;
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 7 && axisNumber1 == 9) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = getPositionValue(6);
u7 = i0;
u8 = getPositionValue(7);
u9 = i1;
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 7 && axisNumber1 == 10) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = getPositionValue(6);
u7 = i0;
u8 = getPositionValue(7);
u9 = getPositionValue(8);
u10 = i1;
}
});
}
else if (axisNumber0 == 8 && axisNumber1 == 9) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = getPositionValue(6);
u7 = getPositionValue(7);
u8 = i0;
u9 = i1;
u10 = getPositionValue(8);
}
});
}
else if (axisNumber0 == 8 && axisNumber1 == 10) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = getPositionValue(6);
u7 = getPositionValue(7);
u8 = i0;
u9 = getPositionValue(8);
u10 = i1;
}
});
}
else if (axisNumber0 == 9 && axisNumber1 == 10) {
setPositionMapper(new PositionMapper() {
@Override
public void setPosition(long i0, long i1) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = getPositionValue(6);
u7 = getPositionValue(7);
u8 = getPositionValue(8);
u9 = i0;
u10 = i1;
}
});
}
else
throw new IllegalArgumentException("missing coordinate combo for 11d "+axisNumber0+" "+axisNumber1);
}
@Override
public void set(long i0, long i1, X value) {
posMapper.setPosition(i0, i1);
view.set(u0, u1, u2, u3, u4, u5, u6, u7, u8, u9, u10, value);
}
@Override
public void get(long i0, long i1, X value) {
posMapper.setPosition(i0, i1);
view.get(u0, u1, u2, u3, u4, u5, u6, u7, u8, u9, u10, value);
}
}
}
| src/main/java/nom/bdezonia/zorbage/dataview/PlaneView.java | /*
* Zorbage: an algebraic data hierarchy for use in numeric processing.
*
* Copyright (c) 2016-2021 Barry DeZonia All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* Neither the name of the <copyright holder> nor the names of its contributors may
* be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package nom.bdezonia.zorbage.dataview;
import java.math.BigDecimal;
import nom.bdezonia.zorbage.algebra.Allocatable;
import nom.bdezonia.zorbage.algebra.Dimensioned;
import nom.bdezonia.zorbage.coordinates.CoordinateSpace;
import nom.bdezonia.zorbage.coordinates.LinearNdCoordinateSpace;
import nom.bdezonia.zorbage.data.DimensionedDataSource;
import nom.bdezonia.zorbage.data.DimensionedStorage;
/**
*
* @author Barry DeZonia
*
* @param <U>
*/
public class PlaneView<U> implements Dimensioned {
private final int axisNumber0; // number of our 0th axis in the parent data source
private final int axisNumber1; // number of our 1th axis in the parent data source
private final long axisNumber0Size; // dimension of our 0th axis in the parent data source
private final long axisNumber1Size; // dimension of our 1th axis in the parent data source
private final Accessor<U> accessor;
private final DimensionedDataSource<U> data;
/**
* Construct a 2-d view of a {@link DimensionedDataSource} by specifying
* two axis numbers.
*
* @param data The n-d data source the view is being built upon.
* @param axis0 The axis number of the "x" component in the data source. X is
* in quotes here because you can specify the y, x, time, channel
* or whatever other axis is defined for the data source.
* @param axis1 The axis number of the "y" component in the data source. Y is
* in quotes here because you can specify the y, x, time, channel
* or whatever other axis is defined for the data source.
*/
public PlaneView(DimensionedDataSource<U> data, int axis0, int axis1) {
int numD = data.numDimensions();
if (numD == 0)
throw new IllegalArgumentException(
"data source must have at least 1 dimension");
if (axis0 == axis1)
throw new IllegalArgumentException("same coordinate axis specified twice");
if (axis0 >= axis1)
throw new IllegalArgumentException(
"axis specified out of order: all numbers assume left to right declaration");
if (axis0 < 0 || axis0 >= numD)
throw new IllegalArgumentException("coordinate component 0 is outside number of dimensions");
if (axis1 < 0 || ((numD == 1 && axis1 > 1) || (numD > 1 && axis1 >= numD)))
throw new IllegalArgumentException("coordinate component 1 is outside number of dimensions");
this.data = data;
this.axisNumber0 = axis0;
this.axisNumber1 = axis1;
this.axisNumber0Size = data.dimension(axis0);
this.axisNumber1Size = numD == 1 ? 1 : data.dimension(axis1);
switch (numD) {
case 1:
accessor = new Accessor1d<U>(data);
break;
case 2:
accessor = new Accessor2d<U>(data);
break;
case 3:
accessor = new Accessor3d<U>(data);
break;
case 4:
accessor = new Accessor4d<U>(data);
break;
case 5:
accessor = new Accessor5d<U>(data);
break;
case 6:
accessor = new Accessor6d<U>(data);
break;
case 7:
accessor = new Accessor7d<U>(data);
break;
case 8:
accessor = new Accessor8d<U>(data);
break;
case 9:
accessor = new Accessor9d<U>(data);
break;
case 10:
accessor = new Accessor10d<U>(data);
break;
case 11:
accessor = new Accessor11d<U>(data);
break;
default:
throw new IllegalArgumentException(
""+numD+" dimensions not yet supported in PlaneView");
}
}
/**
* Returns the {@link DimensionedDataSource} that the PlaneView is attached to.
*/
public DimensionedDataSource<U> getDataSource() {
return data;
}
/**
* Returns the 0th dimension of the view (the width).
*/
public long d0() { return axisNumber0Size; }
/**
* Returns the 1th dimension of the view (the height).
*/
public long d1() { return axisNumber1Size; }
/**
* A view.get() call will pull the value at the view input coordinates
* from the data set into val. No index out of bounds checking is done.
*
* @param i0 0th view input coord
* @param i1 1th view input coord
* @param val The output where the result is placed
*/
public void get(long i0, long i1, U val) {
accessor.get(i0, i1, val);
}
/**
* A planeView.set() call will push the value at the view input
* coordinates into the data set. No index out of bounds checking
* is done.
*
* @param i0 0th view input coord
* @param i1 1th view input coord
* @param val The input that is stored in the underlying data set
*/
public void set(long i0, long i1, U val) {
accessor.set(i0, i1, val);
}
/**
* A planeView.safeGet() call will do a get() call provided the
* passed index coordinate values fit within the view's dimensions.
* If not an exception is thrown instead.
*/
public void safeGet(long i0, long i1, U val) {
if (outOfBounds(i0, i1)) {
throw new IllegalArgumentException("view index out of bounds");
}
else
get(i0, i1, val);
}
/**
* A planeView.safeSet() call will do a set() call provided the
* passed index coordinate values fit within the view's dimensions.
* If not an exception is thrown instead.
*/
public void safeSet(long i0, long i1, U val) {
if (outOfBounds(i0, i1)) {
throw new IllegalArgumentException("view index out of bounds");
}
else
set(i0, i1, val);
}
/**
* Return the column number of 0th index view position
* (i.e. which column is "x" in the view).
*/
public int axisNumber0() {
return axisNumber0;
}
/**
* Return the column number of 1th index view position
* (i.e. which column is "y" in the view).
*/
public int axisNumber1() {
return axisNumber1;
}
/**
* Return the number of dimensions in the view.
*/
@Override
public int numDimensions() {
return 2;
}
/**
* Retrieve each view dimension by index. Throws an exception if
* the dimension index number is outside the view dimensions.
*/
@Override
public long dimension(int d) {
if (d == 0) return axisNumber0Size;
if (d == 1) return axisNumber1Size;
throw new IllegalArgumentException("dimension out of bounds");
}
/**
* Returns the number of dimensions beyond 2 that this PlaneView can manipulate.
* @return
*/
public int getPositionsCount() {
return accessor.getPositionsCount();
}
/**
* Set the position value of one of the dimensions of the PlaneView.
*/
public void setPositionValue(int i, long pos) {
accessor.setPositionValue(i, pos);
}
/**
* Get the position value of one of the dimensions of the PlaneView.
*/
public long getPositionValue(int i) {
return accessor.getPositionValue(i);
}
/**
* Translates the dimensions associated with sliders into their own
* original axis number of the parent data source. Imagine you have
* a 5d dataset. Your "x" and "y" axis numbers set to 1 and 3. The
* planeView stores the 3 other dims as 0, 1, and 2. But their
* original axis numbers in the parent data source were 0, 2, and 4.
* This method maps 0/1/2 into 0/2/4 in this one case.
*
* @param extraDimPos
* @return
*/
public int getDataSourceAxisNumber(int extraDimPos) {
int counted = 0;
for (int i = 0; i < data.numDimensions(); i++) {
if (i == axisNumber0 || i == axisNumber1)
continue;
if (counted == extraDimPos)
return i;
counted++;
}
return -1;
}
/**
* Returns the dimension of extra axis i in the parent data source.
*
* @param extraDimPos
* @return
*/
public long getDataSourceAxisSize(int extraDimPos) {
int pos = getDataSourceAxisNumber(extraDimPos);
return data.dimension(pos);
}
/**
* Returns the model coords of the point on the model currently
* associated with the i0/i1 coords and the current slider
* positions.
*
* @param i0 The 0th component of the point within the d0 x d1 view we are interested in
* @param i1 The 1th component of the point within the d0 x d1 view we are interested in
* @param modelCoords The array to store the output coords in.
*/
public void getModelCoords(long i0, long i1, long[] modelCoords) {
for (int i = 0; i < getPositionsCount(); i++) {
int pos = getDataSourceAxisNumber(i);
long value = getPositionValue(i);
modelCoords[pos] = value;
}
// avoid failure: a 0-d data set would kill code otherwise
if (axisNumber0 < data.numDimensions())
modelCoords[axisNumber0] = i0;
// avoid failure: a 1-d data set would kill code otherwise
if (axisNumber1 < data.numDimensions())
modelCoords[axisNumber1] = i1;
}
/**
* Get a snapshot of a whole plane of data using the current axis positions
* and defined 0th and 1th axis designations. So one can easily generate a
* Y/Z plane where X == 250, for example. As much as feasible pass on the
* units and calibration to the new data source.
*
* @param scratchVar A variable that the routine will use in its calcs.
*
* @return A 2-d data source containing the plane
*/
@SuppressWarnings("unchecked")
public <V extends Allocatable<V>>
DimensionedDataSource<U> copyPlane(U scratchVar)
{
DimensionedDataSource<U> newDs = (DimensionedDataSource<U>)
DimensionedStorage.allocate((V) scratchVar, new long[] {axisNumber0Size,axisNumber1Size});
TwoDView<U> view = new TwoDView<>(newDs);
for (long y = 0; y < axisNumber1Size; y++) {
for (long x = 0; x < axisNumber0Size; x++) {
accessor.get(x, y, scratchVar);
view.set(x, y, scratchVar);
}
}
String d0Str = data.getAxisType(axisNumber0);
String d1Str = data.getAxisType(axisNumber1);
String axes = "["+d0Str+":"+d1Str+"]";
String miniTitle = axes + "slice";
newDs.setName(data.getName() == null ? miniTitle : (miniTitle + " of "+data.getName()));
newDs.setAxisType(0, data.getAxisType(axisNumber0));
newDs.setAxisType(1, data.getAxisType(axisNumber1));
newDs.setAxisUnit(0, data.getAxisUnit(axisNumber0));
newDs.setAxisUnit(1, data.getAxisUnit(axisNumber1));
newDs.setValueType(data.getValueType());
newDs.setValueUnit(data.getValueUnit());
CoordinateSpace origSpace = data.getCoordinateSpace();
if (origSpace instanceof LinearNdCoordinateSpace) {
LinearNdCoordinateSpace origLinSpace =
(LinearNdCoordinateSpace) data.getCoordinateSpace();
BigDecimal[] scales = new BigDecimal[2];
scales[0] = origLinSpace.getScale(axisNumber0);
scales[1] = origLinSpace.getScale(axisNumber1);
BigDecimal[] offsets = new BigDecimal[2];
offsets[0] = origLinSpace.getOffset(axisNumber0);
offsets[1] = origLinSpace.getOffset(axisNumber1);
LinearNdCoordinateSpace newLinSpace = new LinearNdCoordinateSpace(scales, offsets);
newDs.setCoordinateSpace(newLinSpace);
}
return newDs;
}
// ----------------------------------------------------------------------
// PRIVATE DECLARATIONS FOLLOW
// ----------------------------------------------------------------------
// TODO expose these publicly? Will they be useful to someone?
private boolean outOfBounds(long i0, long i1) {
if (i0 < 0 || i0 >= axisNumber0Size) return true;
if (i1 < 0 || i1 >= axisNumber1Size) return true;
return false;
}
private interface Accessor<X> {
void set(long i0, long i1, X value);
void get(long i0, long i1, X value);
int getPositionsCount();
void setPositionValue(int i, long v);
long getPositionValue(int i);
}
private abstract class AccessorBase {
private long[] extraDimPositions;
AccessorBase(int numD) {
int size = numD - 2;
if (size < 0) size = 0;
extraDimPositions = new long[size];
}
public int getPositionsCount() {
return extraDimPositions.length;
}
public void setPositionValue(int i, long v) {
if (i < 0 || i >= extraDimPositions.length)
throw new IllegalArgumentException("illegal extra dim position");
extraDimPositions[i] = v;
}
public long getPositionValue(int i) {
if (i < 0 || i >= extraDimPositions.length)
throw new IllegalArgumentException("illegal extra dim position");
return extraDimPositions[i];
}
}
private class Accessor1d<X>
extends AccessorBase
implements Accessor<X>
{
private final OneDView<X> view;
Accessor1d(DimensionedDataSource<X> data) {
super(data.numDimensions());
view = new OneDView<>(data);
}
@Override
public void set(long i0, long i1, X value) {
view.set(i0, value);
}
@Override
public void get(long i0, long i1, X value) {
view.get(i0, value);
}
}
private class Accessor2d<X>
extends AccessorBase
implements Accessor<X>
{
private final TwoDView<X> view;
Accessor2d(DimensionedDataSource<X> data) {
super(data.numDimensions());
view = new TwoDView<>(data);
}
@Override
public void set(long i0, long i1, X value) {
view.set(i0, i1, value);
}
@Override
public void get(long i0, long i1, X value) {
view.get(i0, i1, value);
}
}
// spot checked that i* and u* are correctly ordered
// spot checked that u* are completely specified
private class Accessor3d<X>
extends AccessorBase
implements Accessor<X>
{
private final ThreeDView<X> view;
private long u0, u1, u2;
Accessor3d(DimensionedDataSource<X> data) {
super(data.numDimensions());
view = new ThreeDView<>(data);
}
private void setPos(long i0, long i1) {
if (axisNumber0 == 0 && axisNumber1 == 1) {
u0 = i0;
u1 = i1;
u2 = getPositionValue(0);
}
else if (axisNumber0 == 0 && axisNumber1 == 2) {
u0 = i0;
u1 = getPositionValue(0);
u2 = i1;
}
else if (axisNumber0 == 1 && axisNumber1 == 2) {
u0 = getPositionValue(0);
u1 = i0;
u2 = i1;
}
else
throw new IllegalArgumentException("missing coordinate combo for 3d "+axisNumber0+" "+axisNumber1);
}
@Override
public void set(long i0, long i1, X value) {
setPos(i0, i1);
view.set(u0, u1, u2, value);
}
@Override
public void get(long i0, long i1, X value) {
setPos(i0, i1);
view.get(u0, u1, u2, value);
}
}
// spot checked that i* and u* are correctly ordered
// spot checked that u* are completely specified
private class Accessor4d<X>
extends AccessorBase
implements Accessor<X>
{
private final FourDView<X> view;
private long u0, u1, u2, u3;
Accessor4d(DimensionedDataSource<X> data) {
super(data.numDimensions());
view = new FourDView<>(data);
}
private void setPos(long i0, long i1) {
if (axisNumber0 == 0 && axisNumber1 == 1) {
u0 = i0;
u1 = i1;
u2 = getPositionValue(0);
u3 = getPositionValue(1);
}
else if (axisNumber0 == 0 && axisNumber1 == 2) {
u0 = i0;
u1 = getPositionValue(0);
u2 = i1;
u3 = getPositionValue(1);
}
else if (axisNumber0 == 0 && axisNumber1 == 3) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = i1;
}
else if (axisNumber0 == 1 && axisNumber1 == 2) {
u0 = getPositionValue(0);
u1 = i0;
u2 = i1;
u3 = getPositionValue(1);
}
else if (axisNumber0 == 1 && axisNumber1 == 3) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = i1;
}
else if (axisNumber0 == 2 && axisNumber1 == 3) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = i1;
}
else
throw new IllegalArgumentException("missing coordinate combo for 4d "+axisNumber0+" "+axisNumber1);
}
@Override
public void set(long i0, long i1, X value) {
setPos(i0, i1);
view.set(u0, u1, u2, u3, value);
}
@Override
public void get(long i0, long i1, X value) {
setPos(i0, i1);
view.get(u0, u1, u2, u3, value);
}
}
// spot checked that i* and u* are correctly ordered
// spot checked that u* are completely specified
private class Accessor5d<X>
extends AccessorBase
implements Accessor<X>
{
private final FiveDView<X> view;
private long u0, u1, u2, u3, u4;
Accessor5d(DimensionedDataSource<X> data) {
super(data.numDimensions());
view = new FiveDView<>(data);
}
private void setPos(long i0, long i1) {
if (axisNumber0 == 0 && axisNumber1 == 1) {
u0 = i0;
u1 = i1;
u2 = getPositionValue(0);
u3 = getPositionValue(1);
u4 = getPositionValue(2);
}
else if (axisNumber0 == 0 && axisNumber1 == 2) {
u0 = i0;
u1 = getPositionValue(0);
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
}
else if (axisNumber0 == 0 && axisNumber1 == 3) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
}
else if (axisNumber0 == 0 && axisNumber1 == 4) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
}
else if (axisNumber0 == 1 && axisNumber1 == 2) {
u0 = getPositionValue(0);
u1 = i0;
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
}
else if (axisNumber0 == 1 && axisNumber1 == 3) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
}
else if (axisNumber0 == 1 && axisNumber1 == 4) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
}
else if (axisNumber0 == 2 && axisNumber1 == 3) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = i1;
u4 = getPositionValue(2);
}
else if (axisNumber0 == 2 && axisNumber1 == 4) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = i1;
}
else if (axisNumber0 == 3 && axisNumber1 == 4) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = i1;
}
else
throw new IllegalArgumentException("missing coordinate combo for 5d "+axisNumber0+" "+axisNumber1);
}
@Override
public void set(long i0, long i1, X value) {
setPos(i0, i1);
view.set(u0, u1, u2, u3, u4, value);
}
@Override
public void get(long i0, long i1, X value) {
setPos(i0, i1);
view.get(u0, u1, u2, u3, u4, value);
}
}
// spot checked that i* and u* are correctly ordered
// spot checked that u* are completely specified
private class Accessor6d<X>
extends AccessorBase
implements Accessor<X>
{
private final SixDView<X> view;
private long u0, u1, u2, u3, u4, u5;
Accessor6d(DimensionedDataSource<X> data) {
super(data.numDimensions());
view = new SixDView<>(data);
}
private void setPos(long i0, long i1) {
if (axisNumber0 == 0 && axisNumber1 == 1) {
u0 = i0;
u1 = i1;
u2 = getPositionValue(0);
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
}
else if (axisNumber0 == 0 && axisNumber1 == 2) {
u0 = i0;
u1 = getPositionValue(0);
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
}
else if (axisNumber0 == 0 && axisNumber1 == 3) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
}
else if (axisNumber0 == 0 && axisNumber1 == 4) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
}
else if (axisNumber0 == 0 && axisNumber1 == 5) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
}
else if (axisNumber0 == 1 && axisNumber1 == 2) {
u0 = getPositionValue(0);
u1 = i0;
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
}
else if (axisNumber0 == 1 && axisNumber1 == 3) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
}
else if (axisNumber0 == 1 && axisNumber1 == 4) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
}
else if (axisNumber0 == 1 && axisNumber1 == 5) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
}
else if (axisNumber0 == 2 && axisNumber1 == 3) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
}
else if (axisNumber0 == 2 && axisNumber1 == 4) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
}
else if (axisNumber0 == 2 && axisNumber1 == 5) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
}
else if (axisNumber0 == 3 && axisNumber1 == 4) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = i1;
u5 = getPositionValue(3);
}
else if (axisNumber0 == 3 && axisNumber1 == 5) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = i1;
}
else if (axisNumber0 == 4 && axisNumber1 == 5) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = i1;
}
else
throw new IllegalArgumentException("missing coordinate combo for 6d "+axisNumber0+" "+axisNumber1);
}
@Override
public void set(long i0, long i1, X value) {
setPos(i0, i1);
view.set(u0, u1, u2, u3, u4, u5, value);
}
@Override
public void get(long i0, long i1, X value) {
setPos(i0, i1);
view.get(u0, u1, u2, u3, u4, u5, value);
}
}
// spot checked that i* and u* are correctly ordered
// spot checked that u* are completely specified
private class Accessor7d<X>
extends AccessorBase
implements Accessor<X>
{
private final SevenDView<X> view;
private long u0, u1, u2, u3, u4, u5, u6;
Accessor7d(DimensionedDataSource<X> data) {
super(data.numDimensions());
view = new SevenDView<>(data);
}
private void setPos(long i0, long i1) {
if (axisNumber0 == 0 && axisNumber1 == 1) {
u0 = i0;
u1 = i1;
u2 = getPositionValue(0);
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
}
else if (axisNumber0 == 0 && axisNumber1 == 2) {
u0 = i0;
u1 = getPositionValue(0);
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
}
else if (axisNumber0 == 0 && axisNumber1 == 3) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
}
else if (axisNumber0 == 0 && axisNumber1 == 4) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
}
else if (axisNumber0 == 0 && axisNumber1 == 5) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
}
else if (axisNumber0 == 0 && axisNumber1 == 6) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
}
else if (axisNumber0 == 1 && axisNumber1 == 2) {
u0 = getPositionValue(0);
u1 = i0;
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
}
else if (axisNumber0 == 1 && axisNumber1 == 3) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
}
else if (axisNumber0 == 1 && axisNumber1 == 4) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
}
else if (axisNumber0 == 1 && axisNumber1 == 5) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
}
else if (axisNumber0 == 1 && axisNumber1 == 6) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
}
else if (axisNumber0 == 2 && axisNumber1 == 3) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
}
else if (axisNumber0 == 2 && axisNumber1 == 4) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
}
else if (axisNumber0 == 2 && axisNumber1 == 5) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
}
else if (axisNumber0 == 2 && axisNumber1 == 6) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
}
else if (axisNumber0 == 3 && axisNumber1 == 4) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
}
else if (axisNumber0 == 3 && axisNumber1 == 5) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
}
else if (axisNumber0 == 3 && axisNumber1 == 6) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
}
else if (axisNumber0 == 4 && axisNumber1 == 5) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = i1;
u6 = getPositionValue(4);
}
else if (axisNumber0 == 4 && axisNumber1 == 6) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = i1;
}
else if (axisNumber0 == 5 && axisNumber1 == 6) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = i1;
}
else
throw new IllegalArgumentException("missing coordinate combo for 7d "+axisNumber0+" "+axisNumber1);
}
@Override
public void set(long i0, long i1, X value) {
setPos(i0, i1);
view.set(u0, u1, u2, u3, u4, u5, u6, value);
}
@Override
public void get(long i0, long i1, X value) {
setPos(i0, i1);
view.get(u0, u1, u2, u3, u4, u5, u6, value);
}
}
// spot checked that i* and u* are correctly ordered
// spot checked that u* are completely specified
private class Accessor8d<X>
extends AccessorBase
implements Accessor<X>
{
private final EightDView<X> view;
private long u0, u1, u2, u3, u4, u5, u6, u7;
Accessor8d(DimensionedDataSource<X> data) {
super(data.numDimensions());
view = new EightDView<>(data);
}
private void setPos(long i0, long i1) {
if (axisNumber0 == 0 && axisNumber1 == 1) {
u0 = i0;
u1 = i1;
u2 = getPositionValue(0);
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
else if (axisNumber0 == 0 && axisNumber1 == 2) {
u0 = i0;
u1 = getPositionValue(0);
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
else if (axisNumber0 == 0 && axisNumber1 == 3) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
else if (axisNumber0 == 0 && axisNumber1 == 4) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
else if (axisNumber0 == 0 && axisNumber1 == 5) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
else if (axisNumber0 == 0 && axisNumber1 == 6) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
}
else if (axisNumber0 == 0 && axisNumber1 == 7) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
}
else if (axisNumber0 == 1 && axisNumber1 == 2) {
u0 = getPositionValue(0);
u1 = i0;
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
else if (axisNumber0 == 1 && axisNumber1 == 3) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
else if (axisNumber0 == 1 && axisNumber1 == 4) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
else if (axisNumber0 == 1 && axisNumber1 == 5) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
else if (axisNumber0 == 1 && axisNumber1 == 6) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
}
else if (axisNumber0 == 1 && axisNumber1 == 7) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
}
else if (axisNumber0 == 2 && axisNumber1 == 3) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
else if (axisNumber0 == 2 && axisNumber1 == 4) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
else if (axisNumber0 == 2 && axisNumber1 == 5) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
else if (axisNumber0 == 2 && axisNumber1 == 6) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
}
else if (axisNumber0 == 2 && axisNumber1 == 7) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
}
else if (axisNumber0 == 3 && axisNumber1 == 4) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
else if (axisNumber0 == 3 && axisNumber1 == 5) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
else if (axisNumber0 == 3 && axisNumber1 == 6) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
}
else if (axisNumber0 == 3 && axisNumber1 == 7) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
}
else if (axisNumber0 == 4 && axisNumber1 == 5) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
}
else if (axisNumber0 == 4 && axisNumber1 == 6) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
}
else if (axisNumber0 == 4 && axisNumber1 == 7) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
}
else if (axisNumber0 == 5 && axisNumber1 == 6) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = i1;
u7 = getPositionValue(5);
}
else if (axisNumber0 == 5 && axisNumber1 == 7) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = getPositionValue(5);
u7 = i1;
}
else if (axisNumber0 == 6 && axisNumber1 == 7) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = i0;
u7 = i1;
}
else
throw new IllegalArgumentException("missing coordinate combo for 8d "+axisNumber0+" "+axisNumber1);
}
@Override
public void set(long i0, long i1, X value) {
setPos(i0, i1);
view.set(u0, u1, u2, u3, u4, u5, u6, u7, value);
}
@Override
public void get(long i0, long i1, X value) {
setPos(i0, i1);
view.get(u0, u1, u2, u3, u4, u5, u6, u7, value);
}
}
// spot checked that i* and u* are correctly ordered
// spot checked that u* are completely specified
private class Accessor9d<X>
extends AccessorBase
implements Accessor<X>
{
private final NineDView<X> view;
private long u0, u1, u2, u3, u4, u5, u6, u7, u8;
Accessor9d(DimensionedDataSource<X> data) {
super(data.numDimensions());
view = new NineDView<>(data);
}
private void setPos(long i0, long i1) {
if (axisNumber0 == 0 && axisNumber1 == 1) {
u0 = i0;
u1 = i1;
u2 = getPositionValue(0);
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
else if (axisNumber0 == 0 && axisNumber1 == 2) {
u0 = i0;
u1 = getPositionValue(0);
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
else if (axisNumber0 == 0 && axisNumber1 == 3) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
else if (axisNumber0 == 0 && axisNumber1 == 4) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
else if (axisNumber0 == 0 && axisNumber1 == 5) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
else if (axisNumber0 == 0 && axisNumber1 == 6) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
else if (axisNumber0 == 0 && axisNumber1 == 7) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
}
else if (axisNumber0 == 0 && axisNumber1 == 8) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
}
else if (axisNumber0 == 1 && axisNumber1 == 2) {
u0 = getPositionValue(0);
u1 = i0;
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
else if (axisNumber0 == 1 && axisNumber1 == 3) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
else if (axisNumber0 == 1 && axisNumber1 == 4) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
else if (axisNumber0 == 1 && axisNumber1 == 5) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
else if (axisNumber0 == 1 && axisNumber1 == 6) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
else if (axisNumber0 == 1 && axisNumber1 == 7) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
}
else if (axisNumber0 == 1 && axisNumber1 == 8) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
}
else if (axisNumber0 == 2 && axisNumber1 == 3) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
else if (axisNumber0 == 2 && axisNumber1 == 4) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
else if (axisNumber0 == 2 && axisNumber1 == 5) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
else if (axisNumber0 == 2 && axisNumber1 == 6) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
else if (axisNumber0 == 2 && axisNumber1 == 7) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
}
else if (axisNumber0 == 2 && axisNumber1 == 8) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
}
else if (axisNumber0 == 3 && axisNumber1 == 4) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
else if (axisNumber0 == 3 && axisNumber1 == 5) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
else if (axisNumber0 == 3 && axisNumber1 == 6) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
else if (axisNumber0 == 3 && axisNumber1 == 7) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
}
else if (axisNumber0 == 3 && axisNumber1 == 8) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
}
else if (axisNumber0 == 4 && axisNumber1 == 5) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
else if (axisNumber0 == 4 && axisNumber1 == 6) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
else if (axisNumber0 == 4 && axisNumber1 == 7) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
}
else if (axisNumber0 == 4 && axisNumber1 == 8) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
}
else if (axisNumber0 == 5 && axisNumber1 == 6) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
}
else if (axisNumber0 == 5 && axisNumber1 == 7) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
}
else if (axisNumber0 == 5 && axisNumber1 == 8) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
}
else if (axisNumber0 == 6 && axisNumber1 == 7) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = i0;
u7 = i1;
u8 = getPositionValue(6);
}
else if (axisNumber0 == 6 && axisNumber1 == 8) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = i0;
u7 = getPositionValue(6);
u8 = i1;
}
else if (axisNumber0 == 7 && axisNumber1 == 8) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = getPositionValue(6);
u7 = i0;
u8 = i1;
}
else
throw new IllegalArgumentException("missing coordinate combo for 8d "+axisNumber0+" "+axisNumber1);
}
@Override
public void set(long i0, long i1, X value) {
setPos(i0, i1);
view.set(u0, u1, u2, u3, u4, u5, u6, u7, u8, value);
}
@Override
public void get(long i0, long i1, X value) {
setPos(i0, i1);
view.get(u0, u1, u2, u3, u4, u5, u6, u7, u8, value);
}
}
// spot checked that i* and u* are correctly ordered
// spot checked that u* are completely specified
private class Accessor10d<X>
extends AccessorBase
implements Accessor<X>
{
private final TenDView<X> view;
private long u0, u1, u2, u3, u4, u5, u6, u7, u8, u9;
Accessor10d(DimensionedDataSource<X> data) {
super(data.numDimensions());
view = new TenDView<>(data);
}
private void setPos(long i0, long i1) {
if (axisNumber0 == 0 && axisNumber1 == 1) {
u0 = i0;
u1 = i1;
u2 = getPositionValue(0);
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 0 && axisNumber1 == 2) {
u0 = i0;
u1 = getPositionValue(0);
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 0 && axisNumber1 == 3) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 0 && axisNumber1 == 4) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 0 && axisNumber1 == 5) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 0 && axisNumber1 == 6) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 0 && axisNumber1 == 7) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 0 && axisNumber1 == 8) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
}
else if (axisNumber0 == 0 && axisNumber1 == 9) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
}
else if (axisNumber0 == 1 && axisNumber1 == 2) {
u0 = getPositionValue(0);
u1 = i0;
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 1 && axisNumber1 == 3) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 1 && axisNumber1 == 4) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 1 && axisNumber1 == 5) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 1 && axisNumber1 == 6) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 1 && axisNumber1 == 7) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 1 && axisNumber1 == 8) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
}
else if (axisNumber0 == 1 && axisNumber1 == 9) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
}
else if (axisNumber0 == 2 && axisNumber1 == 3) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 2 && axisNumber1 == 4) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 2 && axisNumber1 == 5) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 2 && axisNumber1 == 6) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 2 && axisNumber1 == 7) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 2 && axisNumber1 == 8) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
}
else if (axisNumber0 == 2 && axisNumber1 == 9) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
}
else if (axisNumber0 == 3 && axisNumber1 == 4) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 3 && axisNumber1 == 5) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 3 && axisNumber1 == 6) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 3 && axisNumber1 == 7) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 3 && axisNumber1 == 8) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
}
else if (axisNumber0 == 3 && axisNumber1 == 9) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
}
else if (axisNumber0 == 4 && axisNumber1 == 5) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 4 && axisNumber1 == 6) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 4 && axisNumber1 == 7) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 4 && axisNumber1 == 8) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
}
else if (axisNumber0 == 4 && axisNumber1 == 9) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
}
else if (axisNumber0 == 5 && axisNumber1 == 6) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 5 && axisNumber1 == 7) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 5 && axisNumber1 == 8) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
}
else if (axisNumber0 == 5 && axisNumber1 == 9) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
}
else if (axisNumber0 == 6 && axisNumber1 == 7) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = i0;
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
}
else if (axisNumber0 == 6 && axisNumber1 == 8) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = i0;
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
}
else if (axisNumber0 == 6 && axisNumber1 == 9) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = i0;
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
}
else if (axisNumber0 == 7 && axisNumber1 == 8) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = getPositionValue(6);
u7 = i0;
u8 = i1;
u9 = getPositionValue(7);
}
else if (axisNumber0 == 7 && axisNumber1 == 9) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = getPositionValue(6);
u7 = i0;
u8 = getPositionValue(7);
u9 = i1;
}
else if (axisNumber0 == 8 && axisNumber1 == 9) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = getPositionValue(6);
u7 = getPositionValue(7);
u8 = i0;
u9 = i1;
}
else
throw new IllegalArgumentException("missing coordinate combo for 8d "+axisNumber0+" "+axisNumber1);
}
@Override
public void set(long i0, long i1, X value) {
setPos(i0, i1);
view.set(u0, u1, u2, u3, u4, u5, u6, u7, u8, u9, value);
}
@Override
public void get(long i0, long i1, X value) {
setPos(i0, i1);
view.get(u0, u1, u2, u3, u4, u5, u6, u7, u8, u9, value);
}
}
// spot checked that i* and u* are correctly ordered
// spot checked that u* are completely specified
private class Accessor11d<X>
extends AccessorBase
implements Accessor<X>
{
private final ElevenDView<X> view;
private long u0, u1, u2, u3, u4, u5, u6, u7, u8, u9, u10;
Accessor11d(DimensionedDataSource<X> data) {
super(data.numDimensions());
view = new ElevenDView<>(data);
}
private void setPos(long i0, long i1) {
if (axisNumber0 == 0 && axisNumber1 == 1) {
u0 = i0;
u1 = i1;
u2 = getPositionValue(0);
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 0 && axisNumber1 == 2) {
u0 = i0;
u1 = getPositionValue(0);
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 0 && axisNumber1 == 3) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 0 && axisNumber1 == 4) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 0 && axisNumber1 == 5) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 0 && axisNumber1 == 6) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 0 && axisNumber1 == 7) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 0 && axisNumber1 == 8) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 0 && axisNumber1 == 9) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
u10 = getPositionValue(8);
}
else if (axisNumber0 == 0 && axisNumber1 == 10) {
u0 = i0;
u1 = getPositionValue(0);
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = getPositionValue(8);
u10 = i1;
}
else if (axisNumber0 == 1 && axisNumber1 == 2) {
u0 = getPositionValue(0);
u1 = i0;
u2 = i1;
u3 = getPositionValue(1);
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 1 && axisNumber1 == 3) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 1 && axisNumber1 == 4) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 1 && axisNumber1 == 5) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 1 && axisNumber1 == 6) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 1 && axisNumber1 == 7) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 1 && axisNumber1 == 8) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 1 && axisNumber1 == 9) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
u10 = getPositionValue(8);
}
else if (axisNumber0 == 1 && axisNumber1 == 10) {
u0 = getPositionValue(0);
u1 = i0;
u2 = getPositionValue(1);
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = getPositionValue(8);
u10 = i1;
}
else if (axisNumber0 == 2 && axisNumber1 == 3) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = i1;
u4 = getPositionValue(2);
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 2 && axisNumber1 == 4) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 2 && axisNumber1 == 5) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 2 && axisNumber1 == 6) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 2 && axisNumber1 == 7) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 2 && axisNumber1 == 8) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 2 && axisNumber1 == 9) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
u10 = getPositionValue(8);
}
else if (axisNumber0 == 2 && axisNumber1 == 10) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = i0;
u3 = getPositionValue(2);
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = getPositionValue(8);
u10 = i1;
}
else if (axisNumber0 == 3 && axisNumber1 == 4) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = i1;
u5 = getPositionValue(3);
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 3 && axisNumber1 == 5) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 3 && axisNumber1 == 6) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 3 && axisNumber1 == 7) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 3 && axisNumber1 == 8) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 3 && axisNumber1 == 9) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
u10 = getPositionValue(8);
}
else if (axisNumber0 == 3 && axisNumber1 == 10) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = i0;
u4 = getPositionValue(3);
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = getPositionValue(8);
u10 = i1;
}
else if (axisNumber0 == 4 && axisNumber1 == 5) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = i1;
u6 = getPositionValue(4);
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 4 && axisNumber1 == 6) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 4 && axisNumber1 == 7) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 4 && axisNumber1 == 8) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 4 && axisNumber1 == 9) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
u10 = getPositionValue(8);
}
else if (axisNumber0 == 4 && axisNumber1 == 10) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = i0;
u5 = getPositionValue(4);
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = getPositionValue(8);
u10 = i1;
}
else if (axisNumber0 == 5 && axisNumber1 == 6) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = i1;
u7 = getPositionValue(5);
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 5 && axisNumber1 == 7) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = getPositionValue(5);
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 5 && axisNumber1 == 8) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 5 && axisNumber1 == 9) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
u10 = getPositionValue(8);
}
else if (axisNumber0 == 5 && axisNumber1 == 10) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = i0;
u6 = getPositionValue(5);
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = getPositionValue(8);
u10 = i1;
}
else if (axisNumber0 == 6 && axisNumber1 == 7) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = i0;
u7 = i1;
u8 = getPositionValue(6);
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 6 && axisNumber1 == 8) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = i0;
u7 = getPositionValue(6);
u8 = i1;
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 6 && axisNumber1 == 9) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = i0;
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = i1;
u10 = getPositionValue(8);
}
else if (axisNumber0 == 6 && axisNumber1 == 10) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = i0;
u7 = getPositionValue(6);
u8 = getPositionValue(7);
u9 = getPositionValue(8);
u10 = i1;
}
else if (axisNumber0 == 7 && axisNumber1 == 8) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = getPositionValue(6);
u7 = i0;
u8 = i1;
u9 = getPositionValue(7);
u10 = getPositionValue(8);
}
else if (axisNumber0 == 7 && axisNumber1 == 9) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = getPositionValue(6);
u7 = i0;
u8 = getPositionValue(7);
u9 = i1;
u10 = getPositionValue(8);
}
else if (axisNumber0 == 7 && axisNumber1 == 10) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = getPositionValue(6);
u7 = i0;
u8 = getPositionValue(7);
u9 = getPositionValue(8);
u10 = i1;
}
else if (axisNumber0 == 8 && axisNumber1 == 9) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = getPositionValue(6);
u7 = getPositionValue(7);
u8 = i0;
u9 = i1;
u10 = getPositionValue(8);
}
else if (axisNumber0 == 8 && axisNumber1 == 10) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = getPositionValue(6);
u7 = getPositionValue(7);
u8 = i0;
u9 = getPositionValue(8);
u10 = i1;
}
else if (axisNumber0 == 9 && axisNumber1 == 10) {
u0 = getPositionValue(0);
u1 = getPositionValue(1);
u2 = getPositionValue(2);
u3 = getPositionValue(3);
u4 = getPositionValue(4);
u5 = getPositionValue(5);
u6 = getPositionValue(6);
u7 = getPositionValue(7);
u8 = getPositionValue(8);
u9 = i0;
u10 = i1;
}
else
throw new IllegalArgumentException("missing coordinate combo for 8d "+axisNumber0+" "+axisNumber1);
}
@Override
public void set(long i0, long i1, X value) {
setPos(i0, i1);
view.set(u0, u1, u2, u3, u4, u5, u6, u7, u8, u9, u10, value);
}
@Override
public void get(long i0, long i1, X value) {
setPos(i0, i1);
view.get(u0, u1, u2, u3, u4, u5, u6, u7, u8, u9, u10, value);
}
}
}
| Make PlaneView (hopefully) faster; especially at higher dimensions
| src/main/java/nom/bdezonia/zorbage/dataview/PlaneView.java | Make PlaneView (hopefully) faster; especially at higher dimensions |
|
Java | mit | ecc8fff5cb33592aabda1bc66ce223e6bd12df46 | 0 | bkahlert/com.bkahlert.nebula,bkahlert/com.bkahlert.nebula,bkahlert/com.bkahlert.nebula,bkahlert/com.bkahlert.nebula,bkahlert/com.bkahlert.nebula | package com.bkahlert.nebula.handlers;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.util.concurrent.Future;
import javax.swing.ImageIcon;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import com.bkahlert.nebula.utils.CompletedFuture;
import com.bkahlert.nebula.utils.ImageUtils;
import com.bkahlert.nebula.utils.StringUtils;
import com.bkahlert.nebula.widgets.browser.Browser;
public class BrowserPasteHandler extends AbstractHandler {
private static final Logger LOGGER = Logger
.getLogger(BrowserPasteHandler.class);
// @see
// http://blog.pengoworks.com/index.cfm/2008/2/8/The-nightmares-of-getting-images-from-the-Mac-OS-X-clipboard-using-Java
private static BufferedImage getBufferedImage(Image img) {
if (img == null) {
return null;
}
int w = img.getWidth(null);
int h = img.getHeight(null);
// draw original image to thumbnail image object and
// scale it to the new size on-the-fly
BufferedImage bufimg = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bufimg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(img, 0, 0, w, h, null);
g2.dispose();
return bufimg;
}
private Future<Object> paste(Browser browser) {
String html = null;
DataFlavor htmlFlavor = new DataFlavor("text/html",
"Hypertext Markup Language");
DataFlavor rtfFlavor = new DataFlavor("text/rtf", "Rich Formatted Text");
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
try {
if (clipboard.isDataFlavorAvailable(DataFlavor.imageFlavor)) {
ImageIcon IMG = new ImageIcon(
(BufferedImage) clipboard
.getData(DataFlavor.imageFlavor));
BufferedImage bImage = getBufferedImage(IMG.getImage());
html = "<img src=\"" + ImageUtils.convertToInlineSrc(bImage)
+ "\"/>";
} else if (clipboard.isDataFlavorAvailable(htmlFlavor)) {
html = StringUtils.join(
IOUtils.readLines((InputStream) clipboard
.getData(htmlFlavor)), "\n");
} else if (clipboard.isDataFlavorAvailable(rtfFlavor)) {
String rtf = StringUtils.join(IOUtils
.readLines((InputStream) clipboard.getData(rtfFlavor)),
"\n");
html = StringUtils.rtfToPlain(rtf);
} else if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor)) {
String plainText = (String) clipboard
.getData(DataFlavor.stringFlavor);
html = plainText;
}
} catch (Exception e) {
LOGGER.error("Error pasting clipboard into browser");
}
if (html != null) {
return browser.pasteHtmlAtCaret(html);
}
return new CompletedFuture<Object>(null, null);
}
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
Control focusControl = Display.getCurrent().getFocusControl();
if (focusControl instanceof org.eclipse.swt.browser.Browser) {
org.eclipse.swt.browser.Browser swtBrowser = (org.eclipse.swt.browser.Browser) focusControl;
if (swtBrowser.getParent() instanceof Browser) {
Browser browser = (Browser) swtBrowser.getParent();
return this.paste(browser);
}
System.err.println(swtBrowser);
}
return null;
}
}
| src/com/bkahlert/nebula/handlers/BrowserPasteHandler.java | package com.bkahlert.nebula.handlers;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.util.concurrent.Future;
import javax.swing.ImageIcon;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import com.bkahlert.nebula.utils.CompletedFuture;
import com.bkahlert.nebula.utils.ImageUtils;
import com.bkahlert.nebula.utils.StringUtils;
import com.bkahlert.nebula.widgets.browser.Browser;
public class BrowserPasteHandler extends AbstractHandler {
private static final Logger LOGGER = Logger
.getLogger(BrowserPasteHandler.class);
// @see
// http://blog.pengoworks.com/index.cfm/2008/2/8/The-nightmares-of-getting-images-from-the-Mac-OS-X-clipboard-using-Java
private static BufferedImage getBufferedImage(Image img) {
if (img == null) {
return null;
}
int w = img.getWidth(null);
int h = img.getHeight(null);
// draw original image to thumbnail image object and
// scale it to the new size on-the-fly
BufferedImage bufimg = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bufimg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(img, 0, 0, w, h, null);
g2.dispose();
return bufimg;
}
private Future<Object> paste(Browser browser) {
String html = null;
DataFlavor htmlFlavor = new DataFlavor("text/html",
"Hypertext Markup Language");
DataFlavor rtfFlavor = new DataFlavor("text/rtf", "Rich Formatted Text");
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
try {
if (clipboard.isDataFlavorAvailable(DataFlavor.imageFlavor)) {
ImageIcon IMG = new ImageIcon(
(BufferedImage) clipboard
.getData(DataFlavor.imageFlavor));
BufferedImage bImage = getBufferedImage(IMG.getImage());
html = "<img src=\"" + ImageUtils.convertToInlineSrc(bImage)
+ "\"/>";
} else if (clipboard.isDataFlavorAvailable(htmlFlavor)) {
html = StringUtils.join(
IOUtils.readLines((InputStream) clipboard
.getData(htmlFlavor)), "\n");
} else if (clipboard.isDataFlavorAvailable(rtfFlavor)) {
String rtf = StringUtils.join(IOUtils
.readLines((InputStream) clipboard.getData(rtfFlavor)),
"\n");
html = StringUtils.rtfToBody(rtf);
} else if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor)) {
String plainText = (String) clipboard
.getData(DataFlavor.stringFlavor);
html = plainText;
}
} catch (Exception e) {
LOGGER.error("Error pasting clipboard into browser");
}
if (html != null) {
return browser.pasteHtmlAtCaret(html);
}
return new CompletedFuture<Object>(null, null);
}
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
Control focusControl = Display.getCurrent().getFocusControl();
if (focusControl instanceof org.eclipse.swt.browser.Browser) {
org.eclipse.swt.browser.Browser swtBrowser = (org.eclipse.swt.browser.Browser) focusControl;
if (swtBrowser.getParent() instanceof Browser) {
Browser browser = (Browser) swtBrowser.getParent();
return this.paste(browser);
}
System.err.println(swtBrowser);
}
return null;
}
}
| [FIX] RTF text is now pasted as plain text in Browsers
| src/com/bkahlert/nebula/handlers/BrowserPasteHandler.java | [FIX] RTF text is now pasted as plain text in Browsers |
|
Java | mit | b97663e09243836fd565e3def149b0bb94dfb82a | 0 | brentvatne/react-native-video,brentvatne/react-native-video,brentvatne/react-native-video | package com.brentvatne.exoplayer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.accessibility.CaptioningManager;
import android.widget.FrameLayout;
import com.brentvatne.react.R;
import com.brentvatne.receiver.AudioBecomingNoisyReceiver;
import com.brentvatne.receiver.BecomingNoisyListener;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Dynamic;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.ThemedReactContext;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.DefaultRenderersFactory;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.PlaybackParameters;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.mediacodec.MediaCodecRenderer;
import com.google.android.exoplayer2.mediacodec.MediaCodecUtil;
import com.google.android.exoplayer2.metadata.Metadata;
import com.google.android.exoplayer2.metadata.MetadataOutput;
import com.google.android.exoplayer2.source.BehindLiveWindowException;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.MergingMediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.source.SingleSampleMediaSource;
import com.google.android.exoplayer2.source.TrackGroup;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.source.dash.DashMediaSource;
import com.google.android.exoplayer2.source.dash.DefaultDashChunkSource;
import com.google.android.exoplayer2.source.hls.HlsMediaSource;
import com.google.android.exoplayer2.source.smoothstreaming.DefaultSsChunkSource;
import com.google.android.exoplayer2.source.smoothstreaming.SsMediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.MappingTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.ui.PlayerControlView;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultAllocator;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.util.Util;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Map;
@SuppressLint("ViewConstructor")
class ReactExoplayerView extends FrameLayout implements
LifecycleEventListener,
Player.EventListener,
BandwidthMeter.EventListener,
BecomingNoisyListener,
AudioManager.OnAudioFocusChangeListener,
MetadataOutput {
private static final String TAG = "ReactExoplayerView";
private static final CookieManager DEFAULT_COOKIE_MANAGER;
private static final int SHOW_PROGRESS = 1;
static {
DEFAULT_COOKIE_MANAGER = new CookieManager();
DEFAULT_COOKIE_MANAGER.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
}
private final VideoEventEmitter eventEmitter;
private final ReactExoplayerConfig config;
private final DefaultBandwidthMeter bandwidthMeter;
private PlayerControlView playerControlView;
private View playPauseControlContainer;
private Player.EventListener eventListener;
private ExoPlayerView exoPlayerView;
private DataSource.Factory mediaDataSourceFactory;
private SimpleExoPlayer player;
private DefaultTrackSelector trackSelector;
private boolean playerNeedsSource;
private int resumeWindow;
private long resumePosition;
private boolean loadVideoStarted;
private boolean isFullscreen;
private boolean isInBackground;
private boolean isPaused;
private boolean isBuffering;
private boolean muted = false;
private float rate = 1f;
private float audioVolume = 1f;
private int minLoadRetryCount = 3;
private int maxBitRate = 0;
private long seekTime = C.TIME_UNSET;
private int minBufferMs = DefaultLoadControl.DEFAULT_MIN_BUFFER_MS;
private int maxBufferMs = DefaultLoadControl.DEFAULT_MAX_BUFFER_MS;
private int bufferForPlaybackMs = DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_MS;
private int bufferForPlaybackAfterRebufferMs = DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS;
// Props from React
private Uri srcUri;
private String extension;
private boolean repeat;
private String audioTrackType;
private Dynamic audioTrackValue;
private String videoTrackType;
private Dynamic videoTrackValue;
private String textTrackType;
private Dynamic textTrackValue;
private ReadableArray textTracks;
private boolean disableFocus;
private float mProgressUpdateInterval = 250.0f;
private boolean playInBackground = false;
private Map<String, String> requestHeaders;
private boolean mReportBandwidth = false;
private boolean controls;
// \ End props
// React
private final ThemedReactContext themedReactContext;
private final AudioManager audioManager;
private final AudioBecomingNoisyReceiver audioBecomingNoisyReceiver;
private final Handler progressHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_PROGRESS:
if (player != null
&& player.getPlaybackState() == Player.STATE_READY
&& player.getPlayWhenReady()
) {
long pos = player.getCurrentPosition();
long bufferedDuration = player.getBufferedPercentage() * player.getDuration() / 100;
eventEmitter.progressChanged(pos, bufferedDuration, player.getDuration());
msg = obtainMessage(SHOW_PROGRESS);
sendMessageDelayed(msg, Math.round(mProgressUpdateInterval));
}
break;
}
}
};
public ReactExoplayerView(ThemedReactContext context, ReactExoplayerConfig config) {
super(context);
this.themedReactContext = context;
this.eventEmitter = new VideoEventEmitter(context);
this.config = config;
this.bandwidthMeter = config.getBandwidthMeter();
createViews();
audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
themedReactContext.addLifecycleEventListener(this);
audioBecomingNoisyReceiver = new AudioBecomingNoisyReceiver(themedReactContext);
initializePlayer();
}
@Override
public void setId(int id) {
super.setId(id);
eventEmitter.setViewId(id);
}
private void createViews() {
clearResumePosition();
mediaDataSourceFactory = buildDataSourceFactory(true);
if (CookieHandler.getDefault() != DEFAULT_COOKIE_MANAGER) {
CookieHandler.setDefault(DEFAULT_COOKIE_MANAGER);
}
LayoutParams layoutParams = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
exoPlayerView = new ExoPlayerView(getContext());
exoPlayerView.setLayoutParams(layoutParams);
addView(exoPlayerView, 0, layoutParams);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
initializePlayer();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
/* We want to be able to continue playing audio when switching tabs.
* Leave this here in case it causes issues.
*/
// stopPlayback();
}
// LifecycleEventListener implementation
@Override
public void onHostResume() {
if (!playInBackground || !isInBackground) {
setPlayWhenReady(!isPaused);
}
isInBackground = false;
}
@Override
public void onHostPause() {
isInBackground = true;
if (playInBackground) {
return;
}
setPlayWhenReady(false);
}
@Override
public void onHostDestroy() {
stopPlayback();
}
public void cleanUpResources() {
stopPlayback();
}
//BandwidthMeter.EventListener implementation
@Override
public void onBandwidthSample(int elapsedMs, long bytes, long bitrate) {
if (mReportBandwidth) {
eventEmitter.bandwidthReport(bitrate);
}
}
// Internal methods
/**
* Toggling the visibility of the player control view
*/
private void togglePlayerControlVisibility() {
if(player == null) return;
reLayout(playerControlView);
if (playerControlView.isVisible()) {
playerControlView.hide();
} else {
playerControlView.show();
}
}
/**
* Initializing Player control
*/
private void initializePlayerControl() {
if (playerControlView == null) {
playerControlView = new PlayerControlView(getContext());
}
// Setting the player for the playerControlView
playerControlView.setPlayer(player);
playerControlView.show();
playPauseControlContainer = playerControlView.findViewById(R.id.exo_play_pause_container);
// Invoking onClick event for exoplayerView
exoPlayerView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
togglePlayerControlVisibility();
}
});
// Invoking onPlayerStateChanged event for Player
eventListener = new Player.EventListener() {
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
reLayout(playPauseControlContainer);
//Remove this eventListener once its executed. since UI will work fine once after the reLayout is done
player.removeListener(eventListener);
}
};
player.addListener(eventListener);
}
/**
* Adding Player control to the frame layout
*/
private void addPlayerControl() {
if(player == null) return;
LayoutParams layoutParams = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
playerControlView.setLayoutParams(layoutParams);
int indexOfPC = indexOfChild(playerControlView);
if (indexOfPC != -1) {
removeViewAt(indexOfPC);
}
addView(playerControlView, 1, layoutParams);
}
/**
* Update the layout
* @param view view needs to update layout
*
* This is a workaround for the open bug in react-native: https://github.com/facebook/react-native/issues/17968
*/
private void reLayout(View view) {
if (view == null) return;
view.measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
view.layout(view.getLeft(), view.getTop(), view.getMeasuredWidth(), view.getMeasuredHeight());
}
private void initializePlayer() {
ReactExoplayerView self = this;
// This ensures all props have been settled, to avoid async racing conditions.
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (player == null) {
TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory();
trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
trackSelector.setParameters(trackSelector.buildUponParameters()
.setMaxVideoBitrate(maxBitRate == 0 ? Integer.MAX_VALUE : maxBitRate));
DefaultAllocator allocator = new DefaultAllocator(true, C.DEFAULT_BUFFER_SEGMENT_SIZE);
DefaultLoadControl.Builder defaultLoadControlBuilder = new DefaultLoadControl.Builder();
defaultLoadControlBuilder.setAllocator(allocator);
defaultLoadControlBuilder.setBufferDurationsMs(minBufferMs, maxBufferMs, bufferForPlaybackMs, bufferForPlaybackAfterRebufferMs);
defaultLoadControlBuilder.setTargetBufferBytes(-1);
defaultLoadControlBuilder.setPrioritizeTimeOverSizeThresholds(true);
DefaultLoadControl defaultLoadControl = defaultLoadControlBuilder.createDefaultLoadControl();
DefaultRenderersFactory renderersFactory =
new DefaultRenderersFactory(getContext())
.setExtensionRendererMode(DefaultRenderersFactory.EXTENSION_RENDERER_MODE_OFF);
// TODO: Add drmSessionManager to 5th param from: https://github.com/react-native-community/react-native-video/pull/1445
player = ExoPlayerFactory.newSimpleInstance(getContext(), renderersFactory,
trackSelector, defaultLoadControl, null, bandwidthMeter);
player.addListener(self);
player.addMetadataOutput(self);
exoPlayerView.setPlayer(player);
audioBecomingNoisyReceiver.setListener(self);
bandwidthMeter.addEventListener(new Handler(), self);
setPlayWhenReady(!isPaused);
playerNeedsSource = true;
PlaybackParameters params = new PlaybackParameters(rate, 1f);
player.setPlaybackParameters(params);
}
if (playerNeedsSource && srcUri != null) {
ArrayList<MediaSource> mediaSourceList = buildTextSources();
MediaSource videoSource = buildMediaSource(srcUri, extension);
MediaSource mediaSource;
if (mediaSourceList.size() == 0) {
mediaSource = videoSource;
} else {
mediaSourceList.add(0, videoSource);
MediaSource[] textSourceArray = mediaSourceList.toArray(
new MediaSource[mediaSourceList.size()]
);
mediaSource = new MergingMediaSource(textSourceArray);
}
boolean haveResumePosition = resumeWindow != C.INDEX_UNSET;
if (haveResumePosition) {
player.seekTo(resumeWindow, resumePosition);
}
player.prepare(mediaSource, !haveResumePosition, false);
playerNeedsSource = false;
eventEmitter.loadStart();
loadVideoStarted = true;
}
// Initializing the playerControlView
initializePlayerControl();
setControls(controls);
applyModifiers();
}
}, 1);
}
private MediaSource buildMediaSource(Uri uri, String overrideExtension) {
int type = Util.inferContentType(!TextUtils.isEmpty(overrideExtension) ? "." + overrideExtension
: uri.getLastPathSegment());
switch (type) {
case C.TYPE_SS:
return new SsMediaSource.Factory(
new DefaultSsChunkSource.Factory(mediaDataSourceFactory),
buildDataSourceFactory(false)
).setLoadErrorHandlingPolicy(
config.buildLoadErrorHandlingPolicy(minLoadRetryCount)
).createMediaSource(uri);
case C.TYPE_DASH:
return new DashMediaSource.Factory(
new DefaultDashChunkSource.Factory(mediaDataSourceFactory),
buildDataSourceFactory(false)
).setLoadErrorHandlingPolicy(
config.buildLoadErrorHandlingPolicy(minLoadRetryCount)
).createMediaSource(uri);
case C.TYPE_HLS:
return new HlsMediaSource.Factory(
mediaDataSourceFactory
).setLoadErrorHandlingPolicy(
config.buildLoadErrorHandlingPolicy(minLoadRetryCount)
).createMediaSource(uri);
case C.TYPE_OTHER:
return new ProgressiveMediaSource.Factory(
mediaDataSourceFactory
).setLoadErrorHandlingPolicy(
config.buildLoadErrorHandlingPolicy(minLoadRetryCount)
).createMediaSource(uri);
default: {
throw new IllegalStateException("Unsupported type: " + type);
}
}
}
private ArrayList<MediaSource> buildTextSources() {
ArrayList<MediaSource> textSources = new ArrayList<>();
if (textTracks == null) {
return textSources;
}
for (int i = 0; i < textTracks.size(); ++i) {
ReadableMap textTrack = textTracks.getMap(i);
String language = textTrack.getString("language");
String title = textTrack.hasKey("title")
? textTrack.getString("title") : language + " " + i;
Uri uri = Uri.parse(textTrack.getString("uri"));
MediaSource textSource = buildTextSource(title, uri, textTrack.getString("type"),
language);
if (textSource != null) {
textSources.add(textSource);
}
}
return textSources;
}
private MediaSource buildTextSource(String title, Uri uri, String mimeType, String language) {
Format textFormat = Format.createTextSampleFormat(title, mimeType, Format.NO_VALUE, language);
return new SingleSampleMediaSource.Factory(mediaDataSourceFactory)
.createMediaSource(uri, textFormat, C.TIME_UNSET);
}
private void releasePlayer() {
if (player != null) {
updateResumePosition();
player.release();
player.removeMetadataOutput(this);
trackSelector = null;
player = null;
}
progressHandler.removeMessages(SHOW_PROGRESS);
themedReactContext.removeLifecycleEventListener(this);
audioBecomingNoisyReceiver.removeListener();
bandwidthMeter.removeEventListener(this);
}
private boolean requestAudioFocus() {
if (disableFocus || srcUri == null) {
return true;
}
int result = audioManager.requestAudioFocus(this,
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
}
private void setPlayWhenReady(boolean playWhenReady) {
if (player == null) {
return;
}
if (playWhenReady) {
boolean hasAudioFocus = requestAudioFocus();
if (hasAudioFocus) {
player.setPlayWhenReady(true);
}
} else {
player.setPlayWhenReady(false);
}
}
private void startPlayback() {
if (player != null) {
switch (player.getPlaybackState()) {
case Player.STATE_IDLE:
case Player.STATE_ENDED:
initializePlayer();
break;
case Player.STATE_BUFFERING:
case Player.STATE_READY:
if (!player.getPlayWhenReady()) {
setPlayWhenReady(true);
}
break;
default:
break;
}
} else {
initializePlayer();
}
if (!disableFocus) {
setKeepScreenOn(true);
}
}
private void pausePlayback() {
if (player != null) {
if (player.getPlayWhenReady()) {
setPlayWhenReady(false);
}
}
setKeepScreenOn(false);
}
private void stopPlayback() {
onStopPlayback();
releasePlayer();
}
private void onStopPlayback() {
if (isFullscreen) {
setFullscreen(false);
}
setKeepScreenOn(false);
audioManager.abandonAudioFocus(this);
}
private void updateResumePosition() {
resumeWindow = player.getCurrentWindowIndex();
resumePosition = player.isCurrentWindowSeekable() ? Math.max(0, player.getCurrentPosition())
: C.TIME_UNSET;
}
private void clearResumePosition() {
resumeWindow = C.INDEX_UNSET;
resumePosition = C.TIME_UNSET;
}
/**
* Returns a new DataSource factory.
*
* @param useBandwidthMeter Whether to set {@link #bandwidthMeter} as a listener to the new
* DataSource factory.
* @return A new DataSource factory.
*/
private DataSource.Factory buildDataSourceFactory(boolean useBandwidthMeter) {
return DataSourceUtil.getDefaultDataSourceFactory(this.themedReactContext,
useBandwidthMeter ? bandwidthMeter : null, requestHeaders);
}
// AudioManager.OnAudioFocusChangeListener implementation
@Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_LOSS:
eventEmitter.audioFocusChanged(false);
break;
case AudioManager.AUDIOFOCUS_GAIN:
eventEmitter.audioFocusChanged(true);
break;
default:
break;
}
if (player != null) {
if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
// Lower the volume
if (!muted) {
player.setVolume(audioVolume * 0.8f);
}
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
// Raise it back to normal
if (!muted) {
player.setVolume(audioVolume * 1);
}
}
}
}
// AudioBecomingNoisyListener implementation
@Override
public void onAudioBecomingNoisy() {
eventEmitter.audioBecomingNoisy();
}
// Player.EventListener implementation
@Override
public void onLoadingChanged(boolean isLoading) {
// Do nothing.
}
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
String text = "onStateChanged: playWhenReady=" + playWhenReady + ", playbackState=";
switch (playbackState) {
case Player.STATE_IDLE:
text += "idle";
eventEmitter.idle();
clearProgressMessageHandler();
break;
case Player.STATE_BUFFERING:
text += "buffering";
onBuffering(true);
clearProgressMessageHandler();
break;
case Player.STATE_READY:
text += "ready";
eventEmitter.ready();
onBuffering(false);
startProgressHandler();
videoLoaded();
// Setting the visibility for the playerControlView
if (playerControlView != null) {
playerControlView.show();
}
break;
case Player.STATE_ENDED:
text += "ended";
eventEmitter.end();
onStopPlayback();
break;
default:
text += "unknown";
break;
}
Log.d(TAG, text);
}
private void startProgressHandler() {
progressHandler.sendEmptyMessage(SHOW_PROGRESS);
}
/*
The progress message handler will duplicate recursions of the onProgressMessage handler
on change of player state from any state to STATE_READY with playWhenReady is true (when
the video is not paused). This clears all existing messages.
*/
private void clearProgressMessageHandler() {
progressHandler.removeMessages(SHOW_PROGRESS);
}
private void videoLoaded() {
if (loadVideoStarted) {
loadVideoStarted = false;
setSelectedAudioTrack(audioTrackType, audioTrackValue);
setSelectedVideoTrack(videoTrackType, videoTrackValue);
setSelectedTextTrack(textTrackType, textTrackValue);
Format videoFormat = player.getVideoFormat();
int width = videoFormat != null ? videoFormat.width : 0;
int height = videoFormat != null ? videoFormat.height : 0;
eventEmitter.load(player.getDuration(), player.getCurrentPosition(), width, height,
getAudioTrackInfo(), getTextTrackInfo(), getVideoTrackInfo());
}
}
private WritableArray getAudioTrackInfo() {
WritableArray audioTracks = Arguments.createArray();
MappingTrackSelector.MappedTrackInfo info = trackSelector.getCurrentMappedTrackInfo();
int index = getTrackRendererIndex(C.TRACK_TYPE_AUDIO);
if (info == null || index == C.INDEX_UNSET) {
return audioTracks;
}
TrackGroupArray groups = info.getTrackGroups(index);
for (int i = 0; i < groups.length; ++i) {
Format format = groups.get(i).getFormat(0);
WritableMap audioTrack = Arguments.createMap();
audioTrack.putInt("index", i);
audioTrack.putString("title", format.id != null ? format.id : "");
audioTrack.putString("type", format.sampleMimeType);
audioTrack.putString("language", format.language != null ? format.language : "");
audioTrack.putString("bitrate", format.bitrate == Format.NO_VALUE ? ""
: String.format(Locale.US, "%.2fMbps", format.bitrate / 1000000f));
audioTracks.pushMap(audioTrack);
}
return audioTracks;
}
private WritableArray getVideoTrackInfo() {
WritableArray videoTracks = Arguments.createArray();
MappingTrackSelector.MappedTrackInfo info = trackSelector.getCurrentMappedTrackInfo();
int index = getTrackRendererIndex(C.TRACK_TYPE_VIDEO);
if (info == null || index == C.INDEX_UNSET) {
return videoTracks;
}
TrackGroupArray groups = info.getTrackGroups(index);
for (int i = 0; i < groups.length; ++i) {
TrackGroup group = groups.get(i);
for (int trackIndex = 0; trackIndex < group.length; trackIndex++) {
Format format = group.getFormat(trackIndex);
WritableMap videoTrack = Arguments.createMap();
videoTrack.putInt("width", format.width == Format.NO_VALUE ? 0 : format.width);
videoTrack.putInt("height",format.height == Format.NO_VALUE ? 0 : format.height);
videoTrack.putInt("bitrate", format.bitrate == Format.NO_VALUE ? 0 : format.bitrate);
videoTrack.putString("codecs", format.codecs != null ? format.codecs : "");
videoTrack.putString("trackId",
format.id == null ? String.valueOf(trackIndex) : format.id);
videoTracks.pushMap(videoTrack);
}
}
return videoTracks;
}
private WritableArray getTextTrackInfo() {
WritableArray textTracks = Arguments.createArray();
MappingTrackSelector.MappedTrackInfo info = trackSelector.getCurrentMappedTrackInfo();
int index = getTrackRendererIndex(C.TRACK_TYPE_TEXT);
if (info == null || index == C.INDEX_UNSET) {
return textTracks;
}
TrackGroupArray groups = info.getTrackGroups(index);
for (int i = 0; i < groups.length; ++i) {
Format format = groups.get(i).getFormat(0);
WritableMap textTrack = Arguments.createMap();
textTrack.putInt("index", i);
textTrack.putString("title", format.id != null ? format.id : "");
textTrack.putString("type", format.sampleMimeType);
textTrack.putString("language", format.language != null ? format.language : "");
textTracks.pushMap(textTrack);
}
return textTracks;
}
private void onBuffering(boolean buffering) {
if (isBuffering == buffering) {
return;
}
isBuffering = buffering;
if (buffering) {
eventEmitter.buffering(true);
} else {
eventEmitter.buffering(false);
}
}
@Override
public void onPositionDiscontinuity(int reason) {
if (playerNeedsSource) {
// This will only occur if the user has performed a seek whilst in the error state. Update the
// resume position so that if the user then retries, playback will resume from the position to
// which they seeked.
updateResumePosition();
}
// When repeat is turned on, reaching the end of the video will not cause a state change
// so we need to explicitly detect it.
if (reason == Player.DISCONTINUITY_REASON_PERIOD_TRANSITION
&& player.getRepeatMode() == Player.REPEAT_MODE_ONE) {
eventEmitter.end();
}
}
@Override
public void onTimelineChanged(Timeline timeline, Object manifest, int reason) {
// Do nothing.
}
@Override
public void onSeekProcessed() {
eventEmitter.seek(player.getCurrentPosition(), seekTime);
seekTime = C.TIME_UNSET;
}
@Override
public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
// Do nothing.
}
@Override
public void onRepeatModeChanged(int repeatMode) {
// Do nothing.
}
@Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
// Do Nothing.
}
@Override
public void onPlaybackParametersChanged(PlaybackParameters params) {
eventEmitter.playbackRateChange(params.speed);
}
@Override
public void onPlayerError(ExoPlaybackException e) {
String errorString = null;
Exception ex = e;
if (e.type == ExoPlaybackException.TYPE_RENDERER) {
Exception cause = e.getRendererException();
if (cause instanceof MediaCodecRenderer.DecoderInitializationException) {
// Special case for decoder initialization failures.
MediaCodecRenderer.DecoderInitializationException decoderInitializationException =
(MediaCodecRenderer.DecoderInitializationException) cause;
if (decoderInitializationException.decoderName == null) {
if (decoderInitializationException.getCause() instanceof MediaCodecUtil.DecoderQueryException) {
errorString = getResources().getString(R.string.error_querying_decoders);
} else if (decoderInitializationException.secureDecoderRequired) {
errorString = getResources().getString(R.string.error_no_secure_decoder,
decoderInitializationException.mimeType);
} else {
errorString = getResources().getString(R.string.error_no_decoder,
decoderInitializationException.mimeType);
}
} else {
errorString = getResources().getString(R.string.error_instantiating_decoder,
decoderInitializationException.decoderName);
}
}
}
else if (e.type == ExoPlaybackException.TYPE_SOURCE) {
ex = e.getSourceException();
errorString = getResources().getString(R.string.unrecognized_media_format);
}
if (errorString != null) {
eventEmitter.error(errorString, ex);
}
playerNeedsSource = true;
if (isBehindLiveWindow(e)) {
clearResumePosition();
initializePlayer();
} else {
updateResumePosition();
}
}
private static boolean isBehindLiveWindow(ExoPlaybackException e) {
if (e.type != ExoPlaybackException.TYPE_SOURCE) {
return false;
}
Throwable cause = e.getSourceException();
while (cause != null) {
if (cause instanceof BehindLiveWindowException) {
return true;
}
cause = cause.getCause();
}
return false;
}
public int getTrackRendererIndex(int trackType) {
int rendererCount = player.getRendererCount();
for (int rendererIndex = 0; rendererIndex < rendererCount; rendererIndex++) {
if (player.getRendererType(rendererIndex) == trackType) {
return rendererIndex;
}
}
return C.INDEX_UNSET;
}
@Override
public void onMetadata(Metadata metadata) {
eventEmitter.timedMetadata(metadata);
}
// ReactExoplayerViewManager public api
public void setSrc(final Uri uri, final String extension, Map<String, String> headers) {
if (uri != null) {
boolean isOriginalSourceNull = srcUri == null;
boolean isSourceEqual = uri.equals(srcUri);
this.srcUri = uri;
this.extension = extension;
this.requestHeaders = headers;
this.mediaDataSourceFactory =
DataSourceUtil.getDefaultDataSourceFactory(this.themedReactContext, bandwidthMeter,
this.requestHeaders);
if (!isOriginalSourceNull && !isSourceEqual) {
reloadSource();
}
}
}
public void setProgressUpdateInterval(final float progressUpdateInterval) {
mProgressUpdateInterval = progressUpdateInterval;
}
public void setReportBandwidth(boolean reportBandwidth) {
mReportBandwidth = reportBandwidth;
}
public void setRawSrc(final Uri uri, final String extension) {
if (uri != null) {
boolean isOriginalSourceNull = srcUri == null;
boolean isSourceEqual = uri.equals(srcUri);
this.srcUri = uri;
this.extension = extension;
this.mediaDataSourceFactory = buildDataSourceFactory(true);
if (!isOriginalSourceNull && !isSourceEqual) {
reloadSource();
}
}
}
public void setTextTracks(ReadableArray textTracks) {
this.textTracks = textTracks;
reloadSource();
}
private void reloadSource() {
playerNeedsSource = true;
initializePlayer();
}
public void setResizeModeModifier(@ResizeMode.Mode int resizeMode) {
exoPlayerView.setResizeMode(resizeMode);
}
private void applyModifiers() {
setRepeatModifier(repeat);
setMutedModifier(muted);
}
public void setRepeatModifier(boolean repeat) {
if (player != null) {
if (repeat) {
player.setRepeatMode(Player.REPEAT_MODE_ONE);
} else {
player.setRepeatMode(Player.REPEAT_MODE_OFF);
}
}
this.repeat = repeat;
}
public void setSelectedTrack(int trackType, String type, Dynamic value) {
if (player == null) return;
int rendererIndex = getTrackRendererIndex(trackType);
if (rendererIndex == C.INDEX_UNSET) {
return;
}
MappingTrackSelector.MappedTrackInfo info = trackSelector.getCurrentMappedTrackInfo();
if (info == null) {
return;
}
TrackGroupArray groups = info.getTrackGroups(rendererIndex);
int groupIndex = C.INDEX_UNSET;
int[] tracks = {0} ;
if (TextUtils.isEmpty(type)) {
type = "default";
}
DefaultTrackSelector.Parameters disableParameters = trackSelector.getParameters()
.buildUpon()
.setRendererDisabled(rendererIndex, true)
.build();
if (type.equals("disabled")) {
trackSelector.setParameters(disableParameters);
return;
} else if (type.equals("language")) {
for (int i = 0; i < groups.length; ++i) {
Format format = groups.get(i).getFormat(0);
if (format.language != null && format.language.equals(value.asString())) {
groupIndex = i;
break;
}
}
} else if (type.equals("title")) {
for (int i = 0; i < groups.length; ++i) {
Format format = groups.get(i).getFormat(0);
if (format.id != null && format.id.equals(value.asString())) {
groupIndex = i;
break;
}
}
} else if (type.equals("index")) {
if (value.asInt() < groups.length) {
groupIndex = value.asInt();
}
} else if (type.equals("resolution")) {
int height = value.asInt();
for (int i = 0; i < groups.length; ++i) { // Search for the exact height
TrackGroup group = groups.get(i);
for (int j = 0; j < group.length; j++) {
Format format = group.getFormat(j);
if (format.height == height) {
groupIndex = i;
tracks[0] = j;
break;
}
}
}
} else if (rendererIndex == C.TRACK_TYPE_TEXT && Util.SDK_INT > 18) { // Text default
// Use system settings if possible
CaptioningManager captioningManager
= (CaptioningManager)themedReactContext.getSystemService(Context.CAPTIONING_SERVICE);
if (captioningManager != null && captioningManager.isEnabled()) {
groupIndex = getGroupIndexForDefaultLocale(groups);
}
} else if (rendererIndex == C.TRACK_TYPE_AUDIO) { // Audio default
groupIndex = getGroupIndexForDefaultLocale(groups);
}
if (groupIndex == C.INDEX_UNSET && trackType == C.TRACK_TYPE_VIDEO && groups.length != 0) { // Video auto
// Add all tracks as valid options for ABR to choose from
TrackGroup group = groups.get(0);
tracks = new int[group.length];
groupIndex = 0;
for (int j = 0; j < group.length; j++) {
tracks[j] = j;
}
}
if (groupIndex == C.INDEX_UNSET) {
trackSelector.setParameters(disableParameters);
return;
}
DefaultTrackSelector.Parameters selectionParameters = trackSelector.getParameters()
.buildUpon()
.setRendererDisabled(rendererIndex, false)
.setSelectionOverride(rendererIndex, groups,
new DefaultTrackSelector.SelectionOverride(groupIndex, tracks))
.build();
trackSelector.setParameters(selectionParameters);
}
private int getGroupIndexForDefaultLocale(TrackGroupArray groups) {
if (groups.length == 0){
return C.INDEX_UNSET;
}
int groupIndex = 0; // default if no match
String locale2 = Locale.getDefault().getLanguage(); // 2 letter code
String locale3 = Locale.getDefault().getISO3Language(); // 3 letter code
for (int i = 0; i < groups.length; ++i) {
Format format = groups.get(i).getFormat(0);
String language = format.language;
if (language != null && (language.equals(locale2) || language.equals(locale3))) {
groupIndex = i;
break;
}
}
return groupIndex;
}
public void setSelectedVideoTrack(String type, Dynamic value) {
videoTrackType = type;
videoTrackValue = value;
setSelectedTrack(C.TRACK_TYPE_VIDEO, videoTrackType, videoTrackValue);
}
public void setSelectedAudioTrack(String type, Dynamic value) {
audioTrackType = type;
audioTrackValue = value;
setSelectedTrack(C.TRACK_TYPE_AUDIO, audioTrackType, audioTrackValue);
}
public void setSelectedTextTrack(String type, Dynamic value) {
textTrackType = type;
textTrackValue = value;
setSelectedTrack(C.TRACK_TYPE_TEXT, textTrackType, textTrackValue);
}
public void setPausedModifier(boolean paused) {
isPaused = paused;
if (player != null) {
if (!paused) {
startPlayback();
} else {
pausePlayback();
}
}
}
public void setMutedModifier(boolean muted) {
this.muted = muted;
audioVolume = muted ? 0.f : 1.f;
if (player != null) {
player.setVolume(audioVolume);
}
}
public void setVolumeModifier(float volume) {
audioVolume = volume;
if (player != null) {
player.setVolume(audioVolume);
}
}
public void seekTo(long positionMs) {
if (player != null) {
seekTime = positionMs;
player.seekTo(positionMs);
}
}
public void setRateModifier(float newRate) {
rate = newRate;
if (player != null) {
PlaybackParameters params = new PlaybackParameters(rate, 1f);
player.setPlaybackParameters(params);
}
}
public void setMaxBitRateModifier(int newMaxBitRate) {
maxBitRate = newMaxBitRate;
if (player != null) {
trackSelector.setParameters(trackSelector.buildUponParameters()
.setMaxVideoBitrate(maxBitRate == 0 ? Integer.MAX_VALUE : maxBitRate));
}
}
public void setMinLoadRetryCountModifier(int newMinLoadRetryCount) {
minLoadRetryCount = newMinLoadRetryCount;
releasePlayer();
initializePlayer();
}
public void setPlayInBackground(boolean playInBackground) {
this.playInBackground = playInBackground;
}
public void setDisableFocus(boolean disableFocus) {
this.disableFocus = disableFocus;
}
public void setFullscreen(boolean fullscreen) {
if (fullscreen == isFullscreen) {
return; // Avoid generating events when nothing is changing
}
isFullscreen = fullscreen;
Activity activity = themedReactContext.getCurrentActivity();
if (activity == null) {
return;
}
Window window = activity.getWindow();
View decorView = window.getDecorView();
int uiOptions;
if (isFullscreen) {
if (Util.SDK_INT >= 19) { // 4.4+
uiOptions = SYSTEM_UI_FLAG_HIDE_NAVIGATION
| SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| SYSTEM_UI_FLAG_FULLSCREEN;
} else {
uiOptions = SYSTEM_UI_FLAG_HIDE_NAVIGATION
| SYSTEM_UI_FLAG_FULLSCREEN;
}
eventEmitter.fullscreenWillPresent();
decorView.setSystemUiVisibility(uiOptions);
eventEmitter.fullscreenDidPresent();
} else {
uiOptions = View.SYSTEM_UI_FLAG_VISIBLE;
eventEmitter.fullscreenWillDismiss();
decorView.setSystemUiVisibility(uiOptions);
eventEmitter.fullscreenDidDismiss();
}
}
public void setUseTextureView(boolean useTextureView) {
exoPlayerView.setUseTextureView(useTextureView);
}
public void setHideShutterView(boolean hideShutterView) {
exoPlayerView.setHideShutterView(hideShutterView);
}
public void setBufferConfig(int newMinBufferMs, int newMaxBufferMs, int newBufferForPlaybackMs, int newBufferForPlaybackAfterRebufferMs) {
minBufferMs = newMinBufferMs;
maxBufferMs = newMaxBufferMs;
bufferForPlaybackMs = newBufferForPlaybackMs;
bufferForPlaybackAfterRebufferMs = newBufferForPlaybackAfterRebufferMs;
releasePlayer();
initializePlayer();
}
/**
* Handling controls prop
*
* @param controls Controls prop, if true enable controls, if false disable them
*/
public void setControls(boolean controls) {
this.controls = controls;
if (player == null || exoPlayerView == null) return;
if (controls) {
addPlayerControl();
} else {
int indexOfPC = indexOfChild(playerControlView);
if (indexOfPC != -1) {
removeViewAt(indexOfPC);
}
}
}
}
| android-exoplayer/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java | package com.brentvatne.exoplayer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.accessibility.CaptioningManager;
import android.widget.FrameLayout;
import com.brentvatne.react.R;
import com.brentvatne.receiver.AudioBecomingNoisyReceiver;
import com.brentvatne.receiver.BecomingNoisyListener;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Dynamic;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.ThemedReactContext;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.DefaultRenderersFactory;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.PlaybackParameters;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.mediacodec.MediaCodecRenderer;
import com.google.android.exoplayer2.mediacodec.MediaCodecUtil;
import com.google.android.exoplayer2.metadata.Metadata;
import com.google.android.exoplayer2.metadata.MetadataOutput;
import com.google.android.exoplayer2.source.BehindLiveWindowException;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.MergingMediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.source.SingleSampleMediaSource;
import com.google.android.exoplayer2.source.TrackGroup;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.source.dash.DashMediaSource;
import com.google.android.exoplayer2.source.dash.DefaultDashChunkSource;
import com.google.android.exoplayer2.source.hls.HlsMediaSource;
import com.google.android.exoplayer2.source.smoothstreaming.DefaultSsChunkSource;
import com.google.android.exoplayer2.source.smoothstreaming.SsMediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.MappingTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.ui.PlayerControlView;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultAllocator;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.util.Util;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Map;
@SuppressLint("ViewConstructor")
class ReactExoplayerView extends FrameLayout implements
LifecycleEventListener,
Player.EventListener,
BandwidthMeter.EventListener,
BecomingNoisyListener,
AudioManager.OnAudioFocusChangeListener,
MetadataOutput {
private static final String TAG = "ReactExoplayerView";
private static final CookieManager DEFAULT_COOKIE_MANAGER;
private static final int SHOW_PROGRESS = 1;
static {
DEFAULT_COOKIE_MANAGER = new CookieManager();
DEFAULT_COOKIE_MANAGER.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
}
private final VideoEventEmitter eventEmitter;
private final ReactExoplayerConfig config;
private final DefaultBandwidthMeter bandwidthMeter;
private PlayerControlView playerControlView;
private View playPauseControlContainer;
private Player.EventListener eventListener;
private ExoPlayerView exoPlayerView;
private DataSource.Factory mediaDataSourceFactory;
private SimpleExoPlayer player;
private DefaultTrackSelector trackSelector;
private boolean playerNeedsSource;
private int resumeWindow;
private long resumePosition;
private boolean loadVideoStarted;
private boolean isFullscreen;
private boolean isInBackground;
private boolean isPaused;
private boolean isBuffering;
private boolean muted = false;
private float rate = 1f;
private float audioVolume = 1f;
private int minLoadRetryCount = 3;
private int maxBitRate = 0;
private long seekTime = C.TIME_UNSET;
private int minBufferMs = DefaultLoadControl.DEFAULT_MIN_BUFFER_MS;
private int maxBufferMs = DefaultLoadControl.DEFAULT_MAX_BUFFER_MS;
private int bufferForPlaybackMs = DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_MS;
private int bufferForPlaybackAfterRebufferMs = DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS;
// Props from React
private Uri srcUri;
private String extension;
private boolean repeat;
private String audioTrackType;
private Dynamic audioTrackValue;
private String videoTrackType;
private Dynamic videoTrackValue;
private String textTrackType;
private Dynamic textTrackValue;
private ReadableArray textTracks;
private boolean disableFocus;
private float mProgressUpdateInterval = 250.0f;
private boolean playInBackground = false;
private Map<String, String> requestHeaders;
private boolean mReportBandwidth = false;
private boolean controls;
// \ End props
// React
private final ThemedReactContext themedReactContext;
private final AudioManager audioManager;
private final AudioBecomingNoisyReceiver audioBecomingNoisyReceiver;
private final Handler progressHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_PROGRESS:
if (player != null
&& player.getPlaybackState() == Player.STATE_READY
&& player.getPlayWhenReady()
) {
long pos = player.getCurrentPosition();
long bufferedDuration = player.getBufferedPercentage() * player.getDuration() / 100;
eventEmitter.progressChanged(pos, bufferedDuration, player.getDuration());
msg = obtainMessage(SHOW_PROGRESS);
sendMessageDelayed(msg, Math.round(mProgressUpdateInterval));
}
break;
}
}
};
public ReactExoplayerView(ThemedReactContext context, ReactExoplayerConfig config) {
super(context);
this.themedReactContext = context;
this.eventEmitter = new VideoEventEmitter(context);
this.config = config;
this.bandwidthMeter = config.getBandwidthMeter();
createViews();
audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
themedReactContext.addLifecycleEventListener(this);
audioBecomingNoisyReceiver = new AudioBecomingNoisyReceiver(themedReactContext);
initializePlayer();
}
@Override
public void setId(int id) {
super.setId(id);
eventEmitter.setViewId(id);
}
private void createViews() {
clearResumePosition();
mediaDataSourceFactory = buildDataSourceFactory(true);
if (CookieHandler.getDefault() != DEFAULT_COOKIE_MANAGER) {
CookieHandler.setDefault(DEFAULT_COOKIE_MANAGER);
}
LayoutParams layoutParams = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
exoPlayerView = new ExoPlayerView(getContext());
exoPlayerView.setLayoutParams(layoutParams);
addView(exoPlayerView, 0, layoutParams);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
initializePlayer();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
/* We want to be able to continue playing audio when switching tabs.
* Leave this here in case it causes issues.
*/
// stopPlayback();
}
// LifecycleEventListener implementation
@Override
public void onHostResume() {
if (!playInBackground || !isInBackground) {
setPlayWhenReady(!isPaused);
}
isInBackground = false;
}
@Override
public void onHostPause() {
isInBackground = true;
if (playInBackground) {
return;
}
setPlayWhenReady(false);
}
@Override
public void onHostDestroy() {
stopPlayback();
}
public void cleanUpResources() {
stopPlayback();
}
//BandwidthMeter.EventListener implementation
@Override
public void onBandwidthSample(int elapsedMs, long bytes, long bitrate) {
if (mReportBandwidth) {
eventEmitter.bandwidthReport(bitrate);
}
}
// Internal methods
/**
* Toggling the visibility of the player control view
*/
private void togglePlayerControlVisibility() {
if(player == null) return;
reLayout(playerControlView);
if (playerControlView.isVisible()) {
playerControlView.hide();
} else {
playerControlView.show();
}
}
/**
* Initializing Player control
*/
private void initializePlayerControl() {
if (playerControlView == null) {
playerControlView = new PlayerControlView(getContext());
}
// Setting the player for the playerControlView
playerControlView.setPlayer(player);
playerControlView.show();
playPauseControlContainer = playerControlView.findViewById(R.id.exo_play_pause_container);
// Invoking onClick event for exoplayerView
exoPlayerView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
togglePlayerControlVisibility();
}
});
// Invoking onPlayerStateChanged event for Player
eventListener = new Player.EventListener() {
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
reLayout(playPauseControlContainer);
//Remove this eventListener once its executed. since UI will work fine once after the reLayout is done
player.removeListener(eventListener);
}
};
player.addListener(eventListener);
}
/**
* Adding Player control to the frame layout
*/
private void addPlayerControl() {
if(player == null) return;
LayoutParams layoutParams = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
playerControlView.setLayoutParams(layoutParams);
int indexOfPC = indexOfChild(playerControlView);
if (indexOfPC != -1) {
removeViewAt(indexOfPC);
}
addView(playerControlView, 1, layoutParams);
}
/**
* Update the layout
* @param view view needs to update layout
*
* This is a workaround for the open bug in react-native: https://github.com/facebook/react-native/issues/17968
*/
private void reLayout(View view) {
if (view == null) return;
view.measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
view.layout(view.getLeft(), view.getTop(), view.getMeasuredWidth(), view.getMeasuredHeight());
}
private void initializePlayer() {
ReactExoplayerView self = this;
// This ensures all props have been settled, to avoid async racing conditions.
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (player == null) {
TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory();
trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
trackSelector.setParameters(trackSelector.buildUponParameters()
.setMaxVideoBitrate(maxBitRate == 0 ? Integer.MAX_VALUE : maxBitRate));
DefaultAllocator allocator = new DefaultAllocator(true, C.DEFAULT_BUFFER_SEGMENT_SIZE);
DefaultLoadControl.Builder defaultLoadControlBuilder = new DefaultLoadControl.Builder();
defaultLoadControlBuilder.setAllocator(allocator);
defaultLoadControlBuilder.setBufferDurationsMs(minBufferMs, maxBufferMs, bufferForPlaybackMs, bufferForPlaybackAfterRebufferMs);
defaultLoadControlBuilder.setTargetBufferBytes(-1);
defaultLoadControlBuilder.setPrioritizeTimeOverSizeThresholds(true);
DefaultLoadControl defaultLoadControl = defaultLoadControlBuilder.createDefaultLoadControl();
DefaultRenderersFactory renderersFactory =
new DefaultRenderersFactory(getContext())
.setExtensionRendererMode(DefaultRenderersFactory.EXTENSION_RENDERER_MODE_OFF);
// TODO: Add drmSessionManager to 5th param from: https://github.com/react-native-community/react-native-video/pull/1445
player = ExoPlayerFactory.newSimpleInstance(getContext(), renderersFactory,
trackSelector, defaultLoadControl, null, bandwidthMeter);
player.addListener(self);
player.addMetadataOutput(self);
exoPlayerView.setPlayer(player);
audioBecomingNoisyReceiver.setListener(self);
bandwidthMeter.addEventListener(new Handler(), self);
setPlayWhenReady(!isPaused);
playerNeedsSource = true;
PlaybackParameters params = new PlaybackParameters(rate, 1f);
player.setPlaybackParameters(params);
}
if (playerNeedsSource && srcUri != null) {
ArrayList<MediaSource> mediaSourceList = buildTextSources();
MediaSource videoSource = buildMediaSource(srcUri, extension);
MediaSource mediaSource;
if (mediaSourceList.size() == 0) {
mediaSource = videoSource;
} else {
mediaSourceList.add(0, videoSource);
MediaSource[] textSourceArray = mediaSourceList.toArray(
new MediaSource[mediaSourceList.size()]
);
mediaSource = new MergingMediaSource(textSourceArray);
}
boolean haveResumePosition = resumeWindow != C.INDEX_UNSET;
if (haveResumePosition) {
player.seekTo(resumeWindow, resumePosition);
}
player.prepare(mediaSource, !haveResumePosition, false);
playerNeedsSource = false;
eventEmitter.loadStart();
loadVideoStarted = true;
}
// Initializing the playerControlView
initializePlayerControl();
setControls(controls);
applyModifiers();
}
}, 1);
}
private MediaSource buildMediaSource(Uri uri, String overrideExtension) {
int type = Util.inferContentType(!TextUtils.isEmpty(overrideExtension) ? "." + overrideExtension
: uri.getLastPathSegment());
switch (type) {
case C.TYPE_SS:
return new SsMediaSource.Factory(
new DefaultSsChunkSource.Factory(mediaDataSourceFactory),
buildDataSourceFactory(false)
).setLoadErrorHandlingPolicy(
config.buildLoadErrorHandlingPolicy(minLoadRetryCount)
).createMediaSource(uri);
case C.TYPE_DASH:
return new DashMediaSource.Factory(
new DefaultDashChunkSource.Factory(mediaDataSourceFactory),
buildDataSourceFactory(false)
).setLoadErrorHandlingPolicy(
config.buildLoadErrorHandlingPolicy(minLoadRetryCount)
).createMediaSource(uri);
case C.TYPE_HLS:
return new HlsMediaSource.Factory(
mediaDataSourceFactory
).setLoadErrorHandlingPolicy(
config.buildLoadErrorHandlingPolicy(minLoadRetryCount)
).createMediaSource(uri);
case C.TYPE_OTHER:
return new ProgressiveMediaSource.Factory(
mediaDataSourceFactory
).setLoadErrorHandlingPolicy(
config.buildLoadErrorHandlingPolicy(minLoadRetryCount)
).createMediaSource(uri);
default: {
throw new IllegalStateException("Unsupported type: " + type);
}
}
}
private ArrayList<MediaSource> buildTextSources() {
ArrayList<MediaSource> textSources = new ArrayList<>();
if (textTracks == null) {
return textSources;
}
for (int i = 0; i < textTracks.size(); ++i) {
ReadableMap textTrack = textTracks.getMap(i);
String language = textTrack.getString("language");
String title = textTrack.hasKey("title")
? textTrack.getString("title") : language + " " + i;
Uri uri = Uri.parse(textTrack.getString("uri"));
MediaSource textSource = buildTextSource(title, uri, textTrack.getString("type"),
language);
if (textSource != null) {
textSources.add(textSource);
}
}
return textSources;
}
private MediaSource buildTextSource(String title, Uri uri, String mimeType, String language) {
Format textFormat = Format.createTextSampleFormat(title, mimeType, Format.NO_VALUE, language);
return new SingleSampleMediaSource.Factory(mediaDataSourceFactory)
.createMediaSource(uri, textFormat, C.TIME_UNSET);
}
private void releasePlayer() {
if (player != null) {
updateResumePosition();
player.release();
player.removeMetadataOutput(this);
trackSelector = null;
player = null;
}
progressHandler.removeMessages(SHOW_PROGRESS);
themedReactContext.removeLifecycleEventListener(this);
audioBecomingNoisyReceiver.removeListener();
bandwidthMeter.removeEventListener(this);
}
private boolean requestAudioFocus() {
if (disableFocus || srcUri == null) {
return true;
}
int result = audioManager.requestAudioFocus(this,
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
}
private void setPlayWhenReady(boolean playWhenReady) {
if (player == null) {
return;
}
if (playWhenReady) {
boolean hasAudioFocus = requestAudioFocus();
if (hasAudioFocus) {
player.setPlayWhenReady(true);
}
} else {
player.setPlayWhenReady(false);
}
}
private void startPlayback() {
if (player != null) {
switch (player.getPlaybackState()) {
case Player.STATE_IDLE:
case Player.STATE_ENDED:
initializePlayer();
break;
case Player.STATE_BUFFERING:
case Player.STATE_READY:
if (!player.getPlayWhenReady()) {
setPlayWhenReady(true);
}
break;
default:
break;
}
} else {
initializePlayer();
}
if (!disableFocus) {
setKeepScreenOn(true);
}
}
private void pausePlayback() {
if (player != null) {
if (player.getPlayWhenReady()) {
setPlayWhenReady(false);
}
}
setKeepScreenOn(false);
}
private void stopPlayback() {
onStopPlayback();
releasePlayer();
}
private void onStopPlayback() {
if (isFullscreen) {
setFullscreen(false);
}
setKeepScreenOn(false);
audioManager.abandonAudioFocus(this);
}
private void updateResumePosition() {
resumeWindow = player.getCurrentWindowIndex();
resumePosition = player.isCurrentWindowSeekable() ? Math.max(0, player.getCurrentPosition())
: C.TIME_UNSET;
}
private void clearResumePosition() {
resumeWindow = C.INDEX_UNSET;
resumePosition = C.TIME_UNSET;
}
/**
* Returns a new DataSource factory.
*
* @param useBandwidthMeter Whether to set {@link #bandwidthMeter} as a listener to the new
* DataSource factory.
* @return A new DataSource factory.
*/
private DataSource.Factory buildDataSourceFactory(boolean useBandwidthMeter) {
return DataSourceUtil.getDefaultDataSourceFactory(this.themedReactContext,
useBandwidthMeter ? bandwidthMeter : null, requestHeaders);
}
// AudioManager.OnAudioFocusChangeListener implementation
@Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_LOSS:
eventEmitter.audioFocusChanged(false);
break;
case AudioManager.AUDIOFOCUS_GAIN:
eventEmitter.audioFocusChanged(true);
break;
default:
break;
}
if (player != null) {
if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
// Lower the volume
if (!muted) {
player.setVolume(audioVolume * 0.8f);
}
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
// Raise it back to normal
if (!muted) {
player.setVolume(audioVolume * 1);
}
}
}
}
// AudioBecomingNoisyListener implementation
@Override
public void onAudioBecomingNoisy() {
eventEmitter.audioBecomingNoisy();
}
// Player.EventListener implementation
@Override
public void onLoadingChanged(boolean isLoading) {
// Do nothing.
}
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
String text = "onStateChanged: playWhenReady=" + playWhenReady + ", playbackState=";
switch (playbackState) {
case Player.STATE_IDLE:
text += "idle";
eventEmitter.idle();
break;
case Player.STATE_BUFFERING:
text += "buffering";
onBuffering(true);
break;
case Player.STATE_READY:
text += "ready";
eventEmitter.ready();
onBuffering(false);
startProgressHandler();
videoLoaded();
//Setting the visibility for the playerControlView
if (playerControlView != null) {
playerControlView.show();
}
break;
case Player.STATE_ENDED:
text += "ended";
eventEmitter.end();
onStopPlayback();
break;
default:
text += "unknown";
break;
}
Log.d(TAG, text);
}
private void startProgressHandler() {
progressHandler.sendEmptyMessage(SHOW_PROGRESS);
}
private void videoLoaded() {
if (loadVideoStarted) {
loadVideoStarted = false;
setSelectedAudioTrack(audioTrackType, audioTrackValue);
setSelectedVideoTrack(videoTrackType, videoTrackValue);
setSelectedTextTrack(textTrackType, textTrackValue);
Format videoFormat = player.getVideoFormat();
int width = videoFormat != null ? videoFormat.width : 0;
int height = videoFormat != null ? videoFormat.height : 0;
eventEmitter.load(player.getDuration(), player.getCurrentPosition(), width, height,
getAudioTrackInfo(), getTextTrackInfo(), getVideoTrackInfo());
}
}
private WritableArray getAudioTrackInfo() {
WritableArray audioTracks = Arguments.createArray();
MappingTrackSelector.MappedTrackInfo info = trackSelector.getCurrentMappedTrackInfo();
int index = getTrackRendererIndex(C.TRACK_TYPE_AUDIO);
if (info == null || index == C.INDEX_UNSET) {
return audioTracks;
}
TrackGroupArray groups = info.getTrackGroups(index);
for (int i = 0; i < groups.length; ++i) {
Format format = groups.get(i).getFormat(0);
WritableMap audioTrack = Arguments.createMap();
audioTrack.putInt("index", i);
audioTrack.putString("title", format.id != null ? format.id : "");
audioTrack.putString("type", format.sampleMimeType);
audioTrack.putString("language", format.language != null ? format.language : "");
audioTrack.putString("bitrate", format.bitrate == Format.NO_VALUE ? ""
: String.format(Locale.US, "%.2fMbps", format.bitrate / 1000000f));
audioTracks.pushMap(audioTrack);
}
return audioTracks;
}
private WritableArray getVideoTrackInfo() {
WritableArray videoTracks = Arguments.createArray();
MappingTrackSelector.MappedTrackInfo info = trackSelector.getCurrentMappedTrackInfo();
int index = getTrackRendererIndex(C.TRACK_TYPE_VIDEO);
if (info == null || index == C.INDEX_UNSET) {
return videoTracks;
}
TrackGroupArray groups = info.getTrackGroups(index);
for (int i = 0; i < groups.length; ++i) {
TrackGroup group = groups.get(i);
for (int trackIndex = 0; trackIndex < group.length; trackIndex++) {
Format format = group.getFormat(trackIndex);
WritableMap videoTrack = Arguments.createMap();
videoTrack.putInt("width", format.width == Format.NO_VALUE ? 0 : format.width);
videoTrack.putInt("height",format.height == Format.NO_VALUE ? 0 : format.height);
videoTrack.putInt("bitrate", format.bitrate == Format.NO_VALUE ? 0 : format.bitrate);
videoTrack.putString("codecs", format.codecs != null ? format.codecs : "");
videoTrack.putString("trackId",
format.id == null ? String.valueOf(trackIndex) : format.id);
videoTracks.pushMap(videoTrack);
}
}
return videoTracks;
}
private WritableArray getTextTrackInfo() {
WritableArray textTracks = Arguments.createArray();
MappingTrackSelector.MappedTrackInfo info = trackSelector.getCurrentMappedTrackInfo();
int index = getTrackRendererIndex(C.TRACK_TYPE_TEXT);
if (info == null || index == C.INDEX_UNSET) {
return textTracks;
}
TrackGroupArray groups = info.getTrackGroups(index);
for (int i = 0; i < groups.length; ++i) {
Format format = groups.get(i).getFormat(0);
WritableMap textTrack = Arguments.createMap();
textTrack.putInt("index", i);
textTrack.putString("title", format.id != null ? format.id : "");
textTrack.putString("type", format.sampleMimeType);
textTrack.putString("language", format.language != null ? format.language : "");
textTracks.pushMap(textTrack);
}
return textTracks;
}
private void onBuffering(boolean buffering) {
if (isBuffering == buffering) {
return;
}
isBuffering = buffering;
if (buffering) {
eventEmitter.buffering(true);
} else {
eventEmitter.buffering(false);
}
}
@Override
public void onPositionDiscontinuity(int reason) {
if (playerNeedsSource) {
// This will only occur if the user has performed a seek whilst in the error state. Update the
// resume position so that if the user then retries, playback will resume from the position to
// which they seeked.
updateResumePosition();
}
// When repeat is turned on, reaching the end of the video will not cause a state change
// so we need to explicitly detect it.
if (reason == Player.DISCONTINUITY_REASON_PERIOD_TRANSITION
&& player.getRepeatMode() == Player.REPEAT_MODE_ONE) {
eventEmitter.end();
}
}
@Override
public void onTimelineChanged(Timeline timeline, Object manifest, int reason) {
// Do nothing.
}
@Override
public void onSeekProcessed() {
eventEmitter.seek(player.getCurrentPosition(), seekTime);
seekTime = C.TIME_UNSET;
}
@Override
public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
// Do nothing.
}
@Override
public void onRepeatModeChanged(int repeatMode) {
// Do nothing.
}
@Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
// Do Nothing.
}
@Override
public void onPlaybackParametersChanged(PlaybackParameters params) {
eventEmitter.playbackRateChange(params.speed);
}
@Override
public void onPlayerError(ExoPlaybackException e) {
String errorString = null;
Exception ex = e;
if (e.type == ExoPlaybackException.TYPE_RENDERER) {
Exception cause = e.getRendererException();
if (cause instanceof MediaCodecRenderer.DecoderInitializationException) {
// Special case for decoder initialization failures.
MediaCodecRenderer.DecoderInitializationException decoderInitializationException =
(MediaCodecRenderer.DecoderInitializationException) cause;
if (decoderInitializationException.decoderName == null) {
if (decoderInitializationException.getCause() instanceof MediaCodecUtil.DecoderQueryException) {
errorString = getResources().getString(R.string.error_querying_decoders);
} else if (decoderInitializationException.secureDecoderRequired) {
errorString = getResources().getString(R.string.error_no_secure_decoder,
decoderInitializationException.mimeType);
} else {
errorString = getResources().getString(R.string.error_no_decoder,
decoderInitializationException.mimeType);
}
} else {
errorString = getResources().getString(R.string.error_instantiating_decoder,
decoderInitializationException.decoderName);
}
}
}
else if (e.type == ExoPlaybackException.TYPE_SOURCE) {
ex = e.getSourceException();
errorString = getResources().getString(R.string.unrecognized_media_format);
}
if (errorString != null) {
eventEmitter.error(errorString, ex);
}
playerNeedsSource = true;
if (isBehindLiveWindow(e)) {
clearResumePosition();
initializePlayer();
} else {
updateResumePosition();
}
}
private static boolean isBehindLiveWindow(ExoPlaybackException e) {
if (e.type != ExoPlaybackException.TYPE_SOURCE) {
return false;
}
Throwable cause = e.getSourceException();
while (cause != null) {
if (cause instanceof BehindLiveWindowException) {
return true;
}
cause = cause.getCause();
}
return false;
}
public int getTrackRendererIndex(int trackType) {
int rendererCount = player.getRendererCount();
for (int rendererIndex = 0; rendererIndex < rendererCount; rendererIndex++) {
if (player.getRendererType(rendererIndex) == trackType) {
return rendererIndex;
}
}
return C.INDEX_UNSET;
}
@Override
public void onMetadata(Metadata metadata) {
eventEmitter.timedMetadata(metadata);
}
// ReactExoplayerViewManager public api
public void setSrc(final Uri uri, final String extension, Map<String, String> headers) {
if (uri != null) {
boolean isOriginalSourceNull = srcUri == null;
boolean isSourceEqual = uri.equals(srcUri);
this.srcUri = uri;
this.extension = extension;
this.requestHeaders = headers;
this.mediaDataSourceFactory =
DataSourceUtil.getDefaultDataSourceFactory(this.themedReactContext, bandwidthMeter,
this.requestHeaders);
if (!isOriginalSourceNull && !isSourceEqual) {
reloadSource();
}
}
}
public void setProgressUpdateInterval(final float progressUpdateInterval) {
mProgressUpdateInterval = progressUpdateInterval;
}
public void setReportBandwidth(boolean reportBandwidth) {
mReportBandwidth = reportBandwidth;
}
public void setRawSrc(final Uri uri, final String extension) {
if (uri != null) {
boolean isOriginalSourceNull = srcUri == null;
boolean isSourceEqual = uri.equals(srcUri);
this.srcUri = uri;
this.extension = extension;
this.mediaDataSourceFactory = buildDataSourceFactory(true);
if (!isOriginalSourceNull && !isSourceEqual) {
reloadSource();
}
}
}
public void setTextTracks(ReadableArray textTracks) {
this.textTracks = textTracks;
reloadSource();
}
private void reloadSource() {
playerNeedsSource = true;
initializePlayer();
}
public void setResizeModeModifier(@ResizeMode.Mode int resizeMode) {
exoPlayerView.setResizeMode(resizeMode);
}
private void applyModifiers() {
setRepeatModifier(repeat);
setMutedModifier(muted);
}
public void setRepeatModifier(boolean repeat) {
if (player != null) {
if (repeat) {
player.setRepeatMode(Player.REPEAT_MODE_ONE);
} else {
player.setRepeatMode(Player.REPEAT_MODE_OFF);
}
}
this.repeat = repeat;
}
public void setSelectedTrack(int trackType, String type, Dynamic value) {
if (player == null) return;
int rendererIndex = getTrackRendererIndex(trackType);
if (rendererIndex == C.INDEX_UNSET) {
return;
}
MappingTrackSelector.MappedTrackInfo info = trackSelector.getCurrentMappedTrackInfo();
if (info == null) {
return;
}
TrackGroupArray groups = info.getTrackGroups(rendererIndex);
int groupIndex = C.INDEX_UNSET;
int[] tracks = {0} ;
if (TextUtils.isEmpty(type)) {
type = "default";
}
DefaultTrackSelector.Parameters disableParameters = trackSelector.getParameters()
.buildUpon()
.setRendererDisabled(rendererIndex, true)
.build();
if (type.equals("disabled")) {
trackSelector.setParameters(disableParameters);
return;
} else if (type.equals("language")) {
for (int i = 0; i < groups.length; ++i) {
Format format = groups.get(i).getFormat(0);
if (format.language != null && format.language.equals(value.asString())) {
groupIndex = i;
break;
}
}
} else if (type.equals("title")) {
for (int i = 0; i < groups.length; ++i) {
Format format = groups.get(i).getFormat(0);
if (format.id != null && format.id.equals(value.asString())) {
groupIndex = i;
break;
}
}
} else if (type.equals("index")) {
if (value.asInt() < groups.length) {
groupIndex = value.asInt();
}
} else if (type.equals("resolution")) {
int height = value.asInt();
for (int i = 0; i < groups.length; ++i) { // Search for the exact height
TrackGroup group = groups.get(i);
for (int j = 0; j < group.length; j++) {
Format format = group.getFormat(j);
if (format.height == height) {
groupIndex = i;
tracks[0] = j;
break;
}
}
}
} else if (rendererIndex == C.TRACK_TYPE_TEXT && Util.SDK_INT > 18) { // Text default
// Use system settings if possible
CaptioningManager captioningManager
= (CaptioningManager)themedReactContext.getSystemService(Context.CAPTIONING_SERVICE);
if (captioningManager != null && captioningManager.isEnabled()) {
groupIndex = getGroupIndexForDefaultLocale(groups);
}
} else if (rendererIndex == C.TRACK_TYPE_AUDIO) { // Audio default
groupIndex = getGroupIndexForDefaultLocale(groups);
}
if (groupIndex == C.INDEX_UNSET && trackType == C.TRACK_TYPE_VIDEO && groups.length != 0) { // Video auto
// Add all tracks as valid options for ABR to choose from
TrackGroup group = groups.get(0);
tracks = new int[group.length];
groupIndex = 0;
for (int j = 0; j < group.length; j++) {
tracks[j] = j;
}
}
if (groupIndex == C.INDEX_UNSET) {
trackSelector.setParameters(disableParameters);
return;
}
DefaultTrackSelector.Parameters selectionParameters = trackSelector.getParameters()
.buildUpon()
.setRendererDisabled(rendererIndex, false)
.setSelectionOverride(rendererIndex, groups,
new DefaultTrackSelector.SelectionOverride(groupIndex, tracks))
.build();
trackSelector.setParameters(selectionParameters);
}
private int getGroupIndexForDefaultLocale(TrackGroupArray groups) {
if (groups.length == 0){
return C.INDEX_UNSET;
}
int groupIndex = 0; // default if no match
String locale2 = Locale.getDefault().getLanguage(); // 2 letter code
String locale3 = Locale.getDefault().getISO3Language(); // 3 letter code
for (int i = 0; i < groups.length; ++i) {
Format format = groups.get(i).getFormat(0);
String language = format.language;
if (language != null && (language.equals(locale2) || language.equals(locale3))) {
groupIndex = i;
break;
}
}
return groupIndex;
}
public void setSelectedVideoTrack(String type, Dynamic value) {
videoTrackType = type;
videoTrackValue = value;
setSelectedTrack(C.TRACK_TYPE_VIDEO, videoTrackType, videoTrackValue);
}
public void setSelectedAudioTrack(String type, Dynamic value) {
audioTrackType = type;
audioTrackValue = value;
setSelectedTrack(C.TRACK_TYPE_AUDIO, audioTrackType, audioTrackValue);
}
public void setSelectedTextTrack(String type, Dynamic value) {
textTrackType = type;
textTrackValue = value;
setSelectedTrack(C.TRACK_TYPE_TEXT, textTrackType, textTrackValue);
}
public void setPausedModifier(boolean paused) {
isPaused = paused;
if (player != null) {
if (!paused) {
startPlayback();
} else {
pausePlayback();
}
}
}
public void setMutedModifier(boolean muted) {
this.muted = muted;
audioVolume = muted ? 0.f : 1.f;
if (player != null) {
player.setVolume(audioVolume);
}
}
public void setVolumeModifier(float volume) {
audioVolume = volume;
if (player != null) {
player.setVolume(audioVolume);
}
}
public void seekTo(long positionMs) {
if (player != null) {
seekTime = positionMs;
player.seekTo(positionMs);
}
}
public void setRateModifier(float newRate) {
rate = newRate;
if (player != null) {
PlaybackParameters params = new PlaybackParameters(rate, 1f);
player.setPlaybackParameters(params);
}
}
public void setMaxBitRateModifier(int newMaxBitRate) {
maxBitRate = newMaxBitRate;
if (player != null) {
trackSelector.setParameters(trackSelector.buildUponParameters()
.setMaxVideoBitrate(maxBitRate == 0 ? Integer.MAX_VALUE : maxBitRate));
}
}
public void setMinLoadRetryCountModifier(int newMinLoadRetryCount) {
minLoadRetryCount = newMinLoadRetryCount;
releasePlayer();
initializePlayer();
}
public void setPlayInBackground(boolean playInBackground) {
this.playInBackground = playInBackground;
}
public void setDisableFocus(boolean disableFocus) {
this.disableFocus = disableFocus;
}
public void setFullscreen(boolean fullscreen) {
if (fullscreen == isFullscreen) {
return; // Avoid generating events when nothing is changing
}
isFullscreen = fullscreen;
Activity activity = themedReactContext.getCurrentActivity();
if (activity == null) {
return;
}
Window window = activity.getWindow();
View decorView = window.getDecorView();
int uiOptions;
if (isFullscreen) {
if (Util.SDK_INT >= 19) { // 4.4+
uiOptions = SYSTEM_UI_FLAG_HIDE_NAVIGATION
| SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| SYSTEM_UI_FLAG_FULLSCREEN;
} else {
uiOptions = SYSTEM_UI_FLAG_HIDE_NAVIGATION
| SYSTEM_UI_FLAG_FULLSCREEN;
}
eventEmitter.fullscreenWillPresent();
decorView.setSystemUiVisibility(uiOptions);
eventEmitter.fullscreenDidPresent();
} else {
uiOptions = View.SYSTEM_UI_FLAG_VISIBLE;
eventEmitter.fullscreenWillDismiss();
decorView.setSystemUiVisibility(uiOptions);
eventEmitter.fullscreenDidDismiss();
}
}
public void setUseTextureView(boolean useTextureView) {
exoPlayerView.setUseTextureView(useTextureView);
}
public void setHideShutterView(boolean hideShutterView) {
exoPlayerView.setHideShutterView(hideShutterView);
}
public void setBufferConfig(int newMinBufferMs, int newMaxBufferMs, int newBufferForPlaybackMs, int newBufferForPlaybackAfterRebufferMs) {
minBufferMs = newMinBufferMs;
maxBufferMs = newMaxBufferMs;
bufferForPlaybackMs = newBufferForPlaybackMs;
bufferForPlaybackAfterRebufferMs = newBufferForPlaybackAfterRebufferMs;
releasePlayer();
initializePlayer();
}
/**
* Handling controls prop
*
* @param controls Controls prop, if true enable controls, if false disable them
*/
public void setControls(boolean controls) {
this.controls = controls;
if (player == null || exoPlayerView == null) return;
if (controls) {
addPlayerControl();
} else {
int indexOfPC = indexOfChild(playerControlView);
if (indexOfPC != -1) {
removeViewAt(indexOfPC);
}
}
}
}
| Clear progress messages on STATE_IDLE and STATE_BUFFERING (#1768)
The progress message handler will duplicate recursions of the `onProgressMessage` handler on change of player state from any state to STATE_READY with `playWhenReady` is true (when video is not paused). This clears the messages on STATE_IDLE and STATE_BUFFERING to break the recursion. | android-exoplayer/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java | Clear progress messages on STATE_IDLE and STATE_BUFFERING (#1768) |
|
Java | mit | 12319d188f9b52cb29f9189e7a88432631cc4f33 | 0 | kz/balances-android | package in.iamkelv.balances;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.content.WakefulBroadcastReceiver;
import java.util.Calendar;
public class AlarmReceiver extends WakefulBroadcastReceiver{
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
private PreferencesModel preferences;
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, SchedulingService.class);
startWakefulService(context, service);
}
public void setAlarm(Context context) {
alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
// Set alarm trigger time
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
preferences = new PreferencesModel(context);
calendar.set(Calendar.HOUR_OF_DAY, preferences.getNotificationHours());
calendar.set(Calendar.MINUTE, preferences.getNotificationMinutes());
// Set alarm to fire at specified time, rebooting once per day
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);
// Enable automatic restart on device reboot
ComponentName receiver = new ComponentName(context, BootReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
}
public void cancelAlarm(Context context) {
if (alarmMgr != null) {
alarmMgr.cancel(alarmIntent);
}
// Disable BootReceiver
ComponentName receiver = new ComponentName(context, BootReceiver.class.getSimpleName());
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
}
}
| app/src/main/java/in/iamkelv/balances/AlarmReceiver.java | package in.iamkelv.balances;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.content.WakefulBroadcastReceiver;
import java.util.Calendar;
public class AlarmReceiver extends WakefulBroadcastReceiver{
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
private PreferencesModel preferences;
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, SchedulingService.class);
startWakefulService(context, service);
}
public void setAlarm(Context context) {
alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
// Set alarm trigger time
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
preferences = new PreferencesModel(context);
calendar.set(Calendar.HOUR_OF_DAY, preferences.getNotificationHours());
calendar.set(Calendar.MINUTE, preferences.getNotificationMinutes());
// Set alarm to fire at specified time, rebooting once per day
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);
// Enable automatic restart on device reboot
ComponentName receiver = new ComponentName(context, BootReceiver.class.getSimpleName());
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
}
public void cancelAlarm(Context context) {
if (alarmMgr != null) {
alarmMgr.cancel(alarmIntent);
}
// Disable BootReceiver
ComponentName receiver = new ComponentName(context, BootReceiver.class.getSimpleName());
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
}
}
| No more IllegalArgumentException (thanks @berwyn!)
| app/src/main/java/in/iamkelv/balances/AlarmReceiver.java | No more IllegalArgumentException (thanks @berwyn!) |
|
Java | mit | 0e28e2b9d76654dec91b1d0199a3dd03e275576e | 0 | astyler/chargecar | package chargecar.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.io.*;
import org.xml.sax.*;
public class GPXTripParser extends org.xml.sax.helpers.DefaultHandler {
List<Integer> rawTimes;
List<Double> rawLats;
List<Double> rawLons;
List<Double> rawEles;
Stack<String> elementNames;
private StringBuilder contentBuffer;
private int points;
public GPXTripParser() {
clear();
}
public void clear() {
elementNames = new Stack<String>();
contentBuffer = new StringBuilder();
rawTimes = new ArrayList<Integer>();
rawLats = new ArrayList<Double>();
rawLons = new ArrayList<Double>();
rawEles = new ArrayList<Double>();
points = 0;
}
public List<List<PointFeatures>> read(String filename, double carMass) throws IOException {
clear();
FileInputStream in = new FileInputStream(new File(filename));
InputSource source = new InputSource(in);
XMLReader parser;
try {
parser = org.xml.sax.helpers.XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
parser.setContentHandler(this);
parser.parse(source);
} catch (SAXException e) {
e.printStackTrace();
throw new IOException();
}
in.close();
return calculateTrips(carMass);
}
private List<List<PointFeatures>> calculateTrips(double carMass) {
List<List<PointFeatures>> trips = new ArrayList<List<PointFeatures>>();
if(rawTimes.isEmpty()){
return trips;
}
//clean of duplicate readings
removeDuplicates();
List<Integer> times = new ArrayList<Integer>();
List<Double> lats = new ArrayList<Double>();
List<Double> lons = new ArrayList<Double>();
List<Double> eles = new ArrayList<Double>();
times.add(rawTimes.get(0));
lats.add(rawLats.get(0));
lons.add(rawLons.get(0));
eles.add(rawEles.get(0));
for(int i=1;i<rawTimes.size();i++){
if(rawTimes.get(i) - rawTimes.get(i-1) > 360)
{
//if enough time has passed between points (360 seconds)
//consider them disjoint trips
trips.add(calculateTrip(times,lats,lons,eles,carMass));
times.clear();
lats.clear();
lons.clear();
eles.clear();
}
times.add(rawTimes.get(i));
lats.add(rawLats.get(i));
lons.add(rawLons.get(i));
eles.add(rawEles.get(i));
}
if(times.size() > 10){
//get last trip
trips.add(calculateTrip(times,lats,lons,eles,carMass));
}
return trips;
}
private List<PointFeatures> calculateTrip(List<Integer> times, List<Double> lats, List<Double> lons, List<Double> eles, double carMass){
correctTunnels(times, lats, lons, eles);
List<PointFeatures> tripPoints = new ArrayList<PointFeatures>(times.size());
runPowerModel(tripPoints, times, lats, lons, eles, carMass);
return tripPoints;
}
private void runPowerModel(List<PointFeatures> tripPoints,
List<Integer> times, List<Double> lats,
List<Double> lons, List<Double> eles, double carMass) {
// TODO Auto-generated method stub
}
private void correctTunnels(List<Integer> times, List<Double> lats,
List<Double> lons, List<Double> eles) {
int consecutiveCounter = 1;
for(int i=1;i<times.size();i++){
if(lats.get(i).compareTo(lats.get(i-1)) == 0 &&
lons.get(i).compareTo(lons.get(i-1)) == 0){
//consecutive readings at the same position
consecutiveCounter++;
}
else if(consecutiveCounter > 1){
//position has changed, after consectuive readings at same position
//can be tunnel, red light, etc...
//if(POSITION HAS CHANGED ENOUGH TO SUGGEST A TUNNEL){
double latDiff = lats.get(i) - lats.get(i-consecutiveCounter);
double lonDiff = lons.get(i) - lons.get(i-consecutiveCounter);
//}
consecutiveCounter = 1;
}
}
}
private void removeDuplicates() {
int length = rawTimes.size();
for(int i=1;i<length;i++){
if(rawTimes.get(i).compareTo(rawTimes.get(i-1))==0){
rawTimes.remove(i);
rawLats.remove(i);
rawLons.remove(i);
rawEles.remove(i);
i--;
length--;
}
}
}
/*
* DefaultHandler::startElement() fires whenever an XML start tag is encountered
* @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
// the <trkpht> element has attributes which specify latitude and longitude (it has child elements that specify the time and elevation)
if (localName.compareToIgnoreCase("trkpt") == 0) {
rawLats.add(Double.parseDouble(attributes.getValue("lat")));
rawLons.add(Double.parseDouble(attributes.getValue("lon")));
points++;
}
// Clear content buffer
contentBuffer.delete(0, contentBuffer.length());
// Store name of current element in stack
elementNames.push(qName);
}
/*
* the DefaultHandler::characters() function fires 1 or more times for each text node encountered
*
*/
public void characters(char[] ch, int start, int length) throws SAXException {
contentBuffer.append(String.copyValueOf(ch, start, length));
}
/*
* the DefaultHandler::endElement() function fires for each end tag
*
*/
public void endElement(String uri, String localName, String qName) throws SAXException {
String currentElement = elementNames.pop();
if (points > 0 && currentElement != null) {
if (currentElement.compareToIgnoreCase("ele") == 0) {
rawEles.add(Double.parseDouble(contentBuffer.toString()));
}
else if (currentElement.compareToIgnoreCase("time") == 0) {
rawTimes.add(gmtStringToSeconds(contentBuffer.toString()));
}
}
}
private Integer gmtStringToSeconds(String string) {
// TODO Auto-generated method stub
return null;
}
}
/* #This old code would query the USGS server for elevaiton data. Extremely slow. Instead, we use our own copy of USGS data
i = 1
counter = 0
start_index = -1
num_times = @gmt_times.size
while i < num_times do
#this check is done if we have duplicate gmt entries (happens with the iPhone due to sub-second tracking)
#this would cause a problem where the diff in gmt time would be 0 and it would seem that 24 hours had
#passed between these two points. Easiest method is to just filt out the 2nd point rather than account for it.
if @gmt_times[i] == @gmt_times[i-1]
@gmt_times.delete_at(i)
@lats.delete_at(i)
@lngs.delete_at(i)
@elvs.delete_at(i)
#puts "Bad GPS Data Was Removed."
i -= 1
num_times -= 1
elsif @lats[i] == @lats[i-1] && @lngs[i] == @lngs[i-1]
if start_index == -1
start_index = i-1
end
counter += 1
else
if (counter >= 20) #20 steps (corresponding on average to 20-40 seconds)
(counter+1).times do
@gmt_times.delete_at(start_index)
@lats.delete_at(start_index)
@lngs.delete_at(start_index)
@elvs.delete_at(start_index)
#puts "Bad GPS Data Was Removed."
end
i = i - counter - 2
num_times = @gmt_times.size
end
counter = 0
start_index = -1
end
i += 1
end
#we've gone through the file, but the last 20 have been flagged for removal
if (counter >= 20) #20 steps (corresponding on average to 20-40 seconds)
(counter+1).times do
@gmt_times.delete_at(start_index)
@lats.delete_at(start_index)
@lngs.delete_at(start_index)
@elvs.delete_at(start_index)
#puts "Bad GPS Data Was Removed."
end
end
end
#after parsing the data file, do the main calculation on it - power, speeds, etc
def self.do_calculations(carWeight,cargoWeight,passengerWeight,carArea,carDragCoeff,temperature)
@times = []
i = 1
time = 0
#calculate relative times
@times << 0 #for the first data point we are not moving yet
num_times = @gmt_times.size
while i < num_times
#grab the hour(s) from the gmt time strings
time2_hour = @gmt_times[i][0,2].to_i
time1_hour = @gmt_times[i-1][0,2].to_i
#grab the minute(s) from the gmt time strings
time2_minute = @gmt_times[i][2,2].to_i
time1_minute = @gmt_times[i-1][2,2].to_i
#grab the second(s) from the gmt time strings
time2_sec = @gmt_times[i][4,6].to_f #taken as a float to handle fractional gpx time stamps
time1_sec = @gmt_times[i-1][4,6].to_f #taken as a float to handle fractional gpx time stamps
#convert the full times into seconds
time1_seconds = time1_hour * 3600 + time1_minute * 60 + time1_sec
time2_seconds = time2_hour * 3600 + time2_minute * 60 + time2_sec
if (time1_seconds >= time2_seconds) #time wrap around - ie midnight
time = time + (((24 * 60 * 60) - time1_seconds) + time2_seconds)
@times << time
else
time = time + (time2_seconds - time1_seconds)
@times << time
end
i += 1
end
@speeds = []
@accels = []
i = 1
@planar_dists = [] #assumes world is flat; used only to calculate angle of the ground
@adjusted_dists = [] #assumes world is not flat; used for distance/speed calculations
@planar_dists << 0.0
@adjusted_dists << 0.0
#calculate speed
@speeds << 0 #for the first data point we are not moving yet
num_lats = @lats.size
while i < num_lats
temp_dist = Haversine(@lats[i-1], @lngs[i-1], @lats[i], @lngs[i]).to_f #returns dist in km
temp_planar_dist = temp_dist*1000.0 #now in meters
@planar_dists << temp_planar_dist.round(6)
temp_adjusted_dist = Math.sqrt((temp_planar_dist**2)+(@elvs[i]-@elvs[i-1])**2) #account for angle
@adjusted_dists << temp_adjusted_dist.round(6) #store dist into an array of distances
temp_speed = (temp_adjusted_dist/(@times[i]-@times[i-1])) #speed is now m/s
if (temp_planar_dist == 0.0)
@speeds << 0.0
else
@speeds << temp_speed.round(6)
end
i += 1
end
i = 1
#calculate acceleration
@accels << 0 #for the first data point we are not moving yet
num_speeds = @speeds.size
while i < num_speeds
@accels << ((@speeds[i] - @speeds[i-1])/(@times[i]-@times[i-1])).round(6)
i += 1
end
car_weight = carWeight * 0.45359237 #lbs to kg
passenger_weight = passengerWeight * 0.45359237 #lbs to kg
cargo_weight = cargoWeight * 0.45359237 #lbs to kg
area = carArea #in m^2
cp = carDragCoeff
if carWeight.nil?
car_weight = @average_car_curb_weight
end
if carArea.nil?
area = @average_car_area
end
if carDragCoeff.nil?
cp = @average_drag_coefficient
end
mu = 0.015 #rolling resistance coef
gravity = 9.81 #in m/s^2
total_weight = car_weight + passenger_weight + cargo_weight
offset = -0.35
ineff = 1/0.85
rolling_resistance = mu*total_weight*gravity # Rolling Resistance
outsideTemp = ((temperature + 459.67) * 5/9) # in Kelvin now
@calc_power = []
mgsinthetas = []
air_resistances = []
i = 0
#calculate power based on model
num_accels = @accels.size
while i < num_accels
pressure = 101325 * (1-((0.0065 * @elvs[i])/288.15)) ** ((9.81*0.0289)/(8.314*0.0065))
rho = (pressure * 0.0289) / (8.314 * outsideTemp)
air_resistance_coef = 0.5*rho*area*cp
mgsintheta = 0
if (i > 0)
elv_diff = (@elvs[i] - @elvs[i-1])
if (@planar_dists[i] == 0.0)
mgsintheta = 0
elsif (@speeds[i] < 0.50) #speeds really low here, so mgsintheta doesn't account for very much at all
mgsintheta = 0
#going uphill
elsif (@elvs[i] > @elvs[i-1])
mgsintheta = (total_weight * gravity * Math.sin(Math.atan(elv_diff/@planar_dists[i]))) * -1
#going downhill
elsif (@elvs[i] < @elvs[i-1])
mgsintheta = (total_weight * gravity * Math.sin(Math.atan(elv_diff/@planar_dists[i]))) * -1
end
end
mgsinthetas << mgsintheta
air_resistance = air_resistance_coef * (@speeds[i] ** 2)
air_resistances << air_resistance
force = total_weight * @accels[i]
#level ground
if (mgsintheta == 0)
if (force == (rolling_resistance + air_resistance))
pwr = 0
elsif (force == 0)
pwr = (((rolling_resistance + air_resistance) * @speeds[i]) * ineff)
elsif (force < (rolling_resistance + air_resistance))
pwr = 0.35 * (force - rolling_resistance - air_resistance) * @speeds[i]
elsif (force > (rolling_resistance + air_resistance))
pwr = (((force + rolling_resistance + air_resistance) * @speeds[i]) * ineff)
end
#uphill
elsif (@elvs[i] > @elvs[i-1])
if (force == (mgsintheta + rolling_resistance + air_resistance))
pwr = 0
elsif (force > (mgsintheta + rolling_resistance + air_resistance))
pwr = (((force - rolling_resistance - air_resistance - mgsintheta) * @speeds[i]) * ineff)
elsif (force == 0)
pwr = (((mgsintheta + rolling_resistance + air_resistance)) * ineff)
elsif (force < (mgsintheta + rolling_resistance + air_resistance))
pwr = 0.35 * (force - mgsintheta - rolling_resistance - air_resistance) * @speeds[i]
end
#downhill
elsif (@elvs[i] < @elvs[i-1])
if (force == (mgsintheta + rolling_resistance + air_resistance))
pwr = 0
elsif (force > (mgsintheta + rolling_resistance + air_resistance))
pwr = (((force + rolling_resistance + air_resistance - mgsintheta) * @speeds[i]) * ineff)
elsif (force == 0)
pwr = (((rolling_resistance + air_resistance - mgsintheta) * @speeds[i]) * ineff)
elsif (force < (rolling_resistance + air_resistance + mgsintheta))
pwr = 0.35 * (force - mgsintheta - rolling_resistance - air_resistance) * @speeds[i]
end
end
tmp = ((pwr/-1000.0) + offset)
#quadratic adjustment if the speed is above 12 m/s
#temporary fix for high speed drives
if (@speeds[i] > 12.0)
tmp = ((tmp - (0.056*(@speeds[i]**2))) + (0.68*@speeds[i]))
end
@calc_power << tmp.round(5) #in Kw, round to 5 decimal places
i += 1
end
end
#second pass on the scan tool data to remove any calculation outliers as a result of gps satellite oddities
def self.clean_gps_data2
i = 0
num_times = @gmt_times.size
while i < num_times do
if (@speeds[i] > 80 || @accels[i].abs > 80 || @calc_power[i].abs > 100) #80 m/s, ~180 mph; 100 kW
#puts "speeds: " + @speeds[i].to_s + " accels: " + @accels[i].abs.to_s + " calc_power: " + @calc_power[i].abs.to_s
@gmt_times.delete_at(i)
@times.delete_at(i)
@lats.delete_at(i)
@lngs.delete_at(i)
@elvs.delete_at(i)
@planar_dists.delete_at(i)
@adjusted_dists.delete_at(i)
@speeds.delete_at(i)
@accels.delete_at(i)
@calc_power.delete_at(i)
#puts "More Bad GPS Data Was Removed."
i = i - 2 #arrays have been resized, so we need to reset our index 1 back for this and 1 more since we do +1 below
num_times = @gmt_times.size
end
i += 1
end
end
#write the newly created calculations based on gps data to a file
def self.write_gps_calculations(upload_id,type)
i = 0
file = File.new("#{$data_directory}/#{type}/#{upload_id}/calculations.txt", 'w')
file2 = File.new("#{$data_directory}/#{type}/#{upload_id}/calculations-strip.txt", 'w')
#file.puts "format: GMT time, relative time, lat, long, elev, planar distance, adjusted distance, speed, accel, calc power"
#file2.puts "format: GMT time, relative time, elev, planar distance, adjusted distance, speed, accel, calc power, power, current, voltage"
num_times = @gmt_times.size
while i < num_times do
file.puts "#{@gmt_times[i]},#{@times[i]},#{@lats[i]},#{@lngs[i]},#{@elvs[i]},#{@planar_dists[i]},#{@adjusted_dists[i]},#{@speeds[i]},#{@accels[i]},#{@calc_power[i]}"
file2.puts "#{@gmt_times[i]},#{@times[i]},#{@elvs[i]},#{@planar_dists[i]},#{@adjusted_dists[i]},#{@speeds[i]},#{@accels[i]},#{@calc_power[i]}"
i += 1
end
file.close
file2.close
end
#segment gps calculation files for use with graphing - done becuase large time gaps may occur in trip and graphing "breaks" as a result
def self.segment_gps_data(upload_id,type)
segment = 1
i = 1
file = File.new("#{$data_directory}/#{type}/#{upload_id}/calculations-#{segment}.txt", 'w')
file.puts "#{@gmt_times[0]},#{@times[0]},#{@lats[0]},#{@lngs[0]},#{@elvs[0]},#{@planar_dists[0]},#{@adjusted_dists[0]},#{@speeds[0]},#{@accels[0]},#{@calc_power[0]}"
num_times = @gmt_times.size
while i < num_times do
if ((@times[i] - @times[i-1]) > 60 * 10) #10 minutes have passed, create a new drive segment
file.close
segment += 1
file = File.new("#{$data_directory}/#{type}/#{upload_id}/calculations-#{segment}.txt", 'w')
end
file.puts "#{@gmt_times[i]},#{@times[i]},#{@lats[i]},#{@lngs[i]},#{@elvs[i]},#{@planar_dists[i]},#{@adjusted_dists[i]},#{@speeds[i]},#{@accels[i]},#{@calc_power[i]}"
i += 1
end
file.close
end
*/
| chargecarprize/javatestsuite/ChargeCarPrize/src/chargecar/util/GPXTripParser.java | package chargecar.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.io.*;
import org.xml.sax.*;
public class GPXTripParser extends org.xml.sax.helpers.DefaultHandler {
List<Integer> rawTimes;
List<Double> rawLats;
List<Double> rawLons;
List<Double> rawEles;
Stack<String> elementNames;
private StringBuilder contentBuffer;
private int points;
public GPXTripParser() {
clear();
}
public void clear() {
elementNames = new Stack<String>();
contentBuffer = new StringBuilder();
rawTimes = new ArrayList<Integer>();
rawLats = new ArrayList<Double>();
rawLons = new ArrayList<Double>();
rawEles = new ArrayList<Double>();
points = 0;
}
public List<List<PointFeatures>> read(String filename, double carMass) throws IOException {
clear();
FileInputStream in = new FileInputStream(new File(filename));
InputSource source = new InputSource(in);
XMLReader parser;
try {
parser = org.xml.sax.helpers.XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
parser.setContentHandler(this);
parser.parse(source);
} catch (SAXException e) {
e.printStackTrace();
throw new IOException();
}
in.close();
return calculateTrips(carMass);
}
private List<List<PointFeatures>> calculateTrips(double carMass) {
List<List<PointFeatures>> trips = new ArrayList<List<PointFeatures>>();
if(rawTimes.isEmpty()){
return trips;
}
//clean of duplicate readings
removeDuplicates();
List<Integer> times = new ArrayList<Integer>();
List<Double> lats = new ArrayList<Double>();
List<Double> lons = new ArrayList<Double>();
List<Double> eles = new ArrayList<Double>();
times.add(rawTimes.get(0));
lats.add(rawLats.get(0));
lons.add(rawLons.get(0));
eles.add(rawEles.get(0));
for(int i=1;i<rawTimes.size();i++){
if(rawTimes.get(i) - rawTimes.get(i-1) > 360)
{
//if enough time has passed between points (360 seconds)
//consider them disjoint trips
trips.add(calculateTrip(times,lats,lons,eles,carMass));
times.clear();
lats.clear();
lons.clear();
eles.clear();
}
times.add(rawTimes.get(i));
lats.add(rawLats.get(i));
lons.add(rawLons.get(i));
eles.add(rawEles.get(i));
}
if(times.size() > 10){
//get last trip
trips.add(calculateTrip(times,lats,lons,eles,carMass));
}
return trips;
}
private List<PointFeatures> calculateTrip(List<Integer> times, List<Double> lats, List<Double> lons, List<Double> eles, double carMass){
correctTunnels(times, lats, lons, eles);
List<PointFeatures> tripPoints = new ArrayList<PointFeatures>(times.size());
runPowerModel(tripPoints, times, lats, lons, eles, carMass);
return tripPoints;
}
private void runPowerModel(List<PointFeatures> tripPoints,
List<Integer> times, List<Double> lats,
List<Double> lons, List<Double> eles, double carMass) {
// TODO Auto-generated method stub
}
private void correctTunnels(List<Integer> times, List<Double> lats,
List<Double> lons, List<Double> eles) {
int consecutiveCounter = 0;
for(int i=1;i<times.size();i++){
if(lats.get(i).compareTo(lats.get(i-1)) == 0 &&
lons.get(i).compareTo(lons.get(i-1)) == 0){
//consecutive readings at the same position
consecutiveCounter++;
}
else if(consecutiveCounter > 0){
//position has changed, after consectuive readings at same position
//can be tunnel, red light, etc...
consecutiveCounter = 0;
}
}
}
private void removeDuplicates() {
int length = rawTimes.size();
for(int i=1;i<length;i++){
if(rawTimes.get(i).compareTo(rawTimes.get(i-1))==0){
rawTimes.remove(i);
rawLats.remove(i);
rawLons.remove(i);
rawEles.remove(i);
i--;
length--;
}
}
}
/*
* DefaultHandler::startElement() fires whenever an XML start tag is encountered
* @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
// the <trkpht> element has attributes which specify latitude and longitude (it has child elements that specify the time and elevation)
if (localName.compareToIgnoreCase("trkpt") == 0) {
rawLats.add(Double.parseDouble(attributes.getValue("lat")));
rawLons.add(Double.parseDouble(attributes.getValue("lon")));
points++;
}
// Clear content buffer
contentBuffer.delete(0, contentBuffer.length());
// Store name of current element in stack
elementNames.push(qName);
}
/*
* the DefaultHandler::characters() function fires 1 or more times for each text node encountered
*
*/
public void characters(char[] ch, int start, int length) throws SAXException {
contentBuffer.append(String.copyValueOf(ch, start, length));
}
/*
* the DefaultHandler::endElement() function fires for each end tag
*
*/
public void endElement(String uri, String localName, String qName) throws SAXException {
String currentElement = elementNames.pop();
if (points > 0 && currentElement != null) {
if (currentElement.compareToIgnoreCase("ele") == 0) {
rawEles.add(Double.parseDouble(contentBuffer.toString()));
}
else if (currentElement.compareToIgnoreCase("time") == 0) {
rawTimes.add(gmtStringToSeconds(contentBuffer.toString()));
}
}
}
private Integer gmtStringToSeconds(String string) {
// TODO Auto-generated method stub
return null;
}
}
/* #This old code would query the USGS server for elevaiton data. Extremely slow. Instead, we use our own copy of USGS data
i = 1
counter = 0
start_index = -1
num_times = @gmt_times.size
while i < num_times do
#this check is done if we have duplicate gmt entries (happens with the iPhone due to sub-second tracking)
#this would cause a problem where the diff in gmt time would be 0 and it would seem that 24 hours had
#passed between these two points. Easiest method is to just filt out the 2nd point rather than account for it.
if @gmt_times[i] == @gmt_times[i-1]
@gmt_times.delete_at(i)
@lats.delete_at(i)
@lngs.delete_at(i)
@elvs.delete_at(i)
#puts "Bad GPS Data Was Removed."
i -= 1
num_times -= 1
elsif @lats[i] == @lats[i-1] && @lngs[i] == @lngs[i-1]
if start_index == -1
start_index = i-1
end
counter += 1
else
if (counter >= 20) #20 steps (corresponding on average to 20-40 seconds)
(counter+1).times do
@gmt_times.delete_at(start_index)
@lats.delete_at(start_index)
@lngs.delete_at(start_index)
@elvs.delete_at(start_index)
#puts "Bad GPS Data Was Removed."
end
i = i - counter - 2
num_times = @gmt_times.size
end
counter = 0
start_index = -1
end
i += 1
end
#we've gone through the file, but the last 20 have been flagged for removal
if (counter >= 20) #20 steps (corresponding on average to 20-40 seconds)
(counter+1).times do
@gmt_times.delete_at(start_index)
@lats.delete_at(start_index)
@lngs.delete_at(start_index)
@elvs.delete_at(start_index)
#puts "Bad GPS Data Was Removed."
end
end
end
#after parsing the data file, do the main calculation on it - power, speeds, etc
def self.do_calculations(carWeight,cargoWeight,passengerWeight,carArea,carDragCoeff,temperature)
@times = []
i = 1
time = 0
#calculate relative times
@times << 0 #for the first data point we are not moving yet
num_times = @gmt_times.size
while i < num_times
#grab the hour(s) from the gmt time strings
time2_hour = @gmt_times[i][0,2].to_i
time1_hour = @gmt_times[i-1][0,2].to_i
#grab the minute(s) from the gmt time strings
time2_minute = @gmt_times[i][2,2].to_i
time1_minute = @gmt_times[i-1][2,2].to_i
#grab the second(s) from the gmt time strings
time2_sec = @gmt_times[i][4,6].to_f #taken as a float to handle fractional gpx time stamps
time1_sec = @gmt_times[i-1][4,6].to_f #taken as a float to handle fractional gpx time stamps
#convert the full times into seconds
time1_seconds = time1_hour * 3600 + time1_minute * 60 + time1_sec
time2_seconds = time2_hour * 3600 + time2_minute * 60 + time2_sec
if (time1_seconds >= time2_seconds) #time wrap around - ie midnight
time = time + (((24 * 60 * 60) - time1_seconds) + time2_seconds)
@times << time
else
time = time + (time2_seconds - time1_seconds)
@times << time
end
i += 1
end
@speeds = []
@accels = []
i = 1
@planar_dists = [] #assumes world is flat; used only to calculate angle of the ground
@adjusted_dists = [] #assumes world is not flat; used for distance/speed calculations
@planar_dists << 0.0
@adjusted_dists << 0.0
#calculate speed
@speeds << 0 #for the first data point we are not moving yet
num_lats = @lats.size
while i < num_lats
temp_dist = Haversine(@lats[i-1], @lngs[i-1], @lats[i], @lngs[i]).to_f #returns dist in km
temp_planar_dist = temp_dist*1000.0 #now in meters
@planar_dists << temp_planar_dist.round(6)
temp_adjusted_dist = Math.sqrt((temp_planar_dist**2)+(@elvs[i]-@elvs[i-1])**2) #account for angle
@adjusted_dists << temp_adjusted_dist.round(6) #store dist into an array of distances
temp_speed = (temp_adjusted_dist/(@times[i]-@times[i-1])) #speed is now m/s
if (temp_planar_dist == 0.0)
@speeds << 0.0
else
@speeds << temp_speed.round(6)
end
i += 1
end
i = 1
#calculate acceleration
@accels << 0 #for the first data point we are not moving yet
num_speeds = @speeds.size
while i < num_speeds
@accels << ((@speeds[i] - @speeds[i-1])/(@times[i]-@times[i-1])).round(6)
i += 1
end
car_weight = carWeight * 0.45359237 #lbs to kg
passenger_weight = passengerWeight * 0.45359237 #lbs to kg
cargo_weight = cargoWeight * 0.45359237 #lbs to kg
area = carArea #in m^2
cp = carDragCoeff
if carWeight.nil?
car_weight = @average_car_curb_weight
end
if carArea.nil?
area = @average_car_area
end
if carDragCoeff.nil?
cp = @average_drag_coefficient
end
mu = 0.015 #rolling resistance coef
gravity = 9.81 #in m/s^2
total_weight = car_weight + passenger_weight + cargo_weight
offset = -0.35
ineff = 1/0.85
rolling_resistance = mu*total_weight*gravity # Rolling Resistance
outsideTemp = ((temperature + 459.67) * 5/9) # in Kelvin now
@calc_power = []
mgsinthetas = []
air_resistances = []
i = 0
#calculate power based on model
num_accels = @accels.size
while i < num_accels
pressure = 101325 * (1-((0.0065 * @elvs[i])/288.15)) ** ((9.81*0.0289)/(8.314*0.0065))
rho = (pressure * 0.0289) / (8.314 * outsideTemp)
air_resistance_coef = 0.5*rho*area*cp
mgsintheta = 0
if (i > 0)
elv_diff = (@elvs[i] - @elvs[i-1])
if (@planar_dists[i] == 0.0)
mgsintheta = 0
elsif (@speeds[i] < 0.50) #speeds really low here, so mgsintheta doesn't account for very much at all
mgsintheta = 0
#going uphill
elsif (@elvs[i] > @elvs[i-1])
mgsintheta = (total_weight * gravity * Math.sin(Math.atan(elv_diff/@planar_dists[i]))) * -1
#going downhill
elsif (@elvs[i] < @elvs[i-1])
mgsintheta = (total_weight * gravity * Math.sin(Math.atan(elv_diff/@planar_dists[i]))) * -1
end
end
mgsinthetas << mgsintheta
air_resistance = air_resistance_coef * (@speeds[i] ** 2)
air_resistances << air_resistance
force = total_weight * @accels[i]
#level ground
if (mgsintheta == 0)
if (force == (rolling_resistance + air_resistance))
pwr = 0
elsif (force == 0)
pwr = (((rolling_resistance + air_resistance) * @speeds[i]) * ineff)
elsif (force < (rolling_resistance + air_resistance))
pwr = 0.35 * (force - rolling_resistance - air_resistance) * @speeds[i]
elsif (force > (rolling_resistance + air_resistance))
pwr = (((force + rolling_resistance + air_resistance) * @speeds[i]) * ineff)
end
#uphill
elsif (@elvs[i] > @elvs[i-1])
if (force == (mgsintheta + rolling_resistance + air_resistance))
pwr = 0
elsif (force > (mgsintheta + rolling_resistance + air_resistance))
pwr = (((force - rolling_resistance - air_resistance - mgsintheta) * @speeds[i]) * ineff)
elsif (force == 0)
pwr = (((mgsintheta + rolling_resistance + air_resistance)) * ineff)
elsif (force < (mgsintheta + rolling_resistance + air_resistance))
pwr = 0.35 * (force - mgsintheta - rolling_resistance - air_resistance) * @speeds[i]
end
#downhill
elsif (@elvs[i] < @elvs[i-1])
if (force == (mgsintheta + rolling_resistance + air_resistance))
pwr = 0
elsif (force > (mgsintheta + rolling_resistance + air_resistance))
pwr = (((force + rolling_resistance + air_resistance - mgsintheta) * @speeds[i]) * ineff)
elsif (force == 0)
pwr = (((rolling_resistance + air_resistance - mgsintheta) * @speeds[i]) * ineff)
elsif (force < (rolling_resistance + air_resistance + mgsintheta))
pwr = 0.35 * (force - mgsintheta - rolling_resistance - air_resistance) * @speeds[i]
end
end
tmp = ((pwr/-1000.0) + offset)
#quadratic adjustment if the speed is above 12 m/s
#temporary fix for high speed drives
if (@speeds[i] > 12.0)
tmp = ((tmp - (0.056*(@speeds[i]**2))) + (0.68*@speeds[i]))
end
@calc_power << tmp.round(5) #in Kw, round to 5 decimal places
i += 1
end
end
#second pass on the scan tool data to remove any calculation outliers as a result of gps satellite oddities
def self.clean_gps_data2
i = 0
num_times = @gmt_times.size
while i < num_times do
if (@speeds[i] > 80 || @accels[i].abs > 80 || @calc_power[i].abs > 100) #80 m/s, ~180 mph; 100 kW
#puts "speeds: " + @speeds[i].to_s + " accels: " + @accels[i].abs.to_s + " calc_power: " + @calc_power[i].abs.to_s
@gmt_times.delete_at(i)
@times.delete_at(i)
@lats.delete_at(i)
@lngs.delete_at(i)
@elvs.delete_at(i)
@planar_dists.delete_at(i)
@adjusted_dists.delete_at(i)
@speeds.delete_at(i)
@accels.delete_at(i)
@calc_power.delete_at(i)
#puts "More Bad GPS Data Was Removed."
i = i - 2 #arrays have been resized, so we need to reset our index 1 back for this and 1 more since we do +1 below
num_times = @gmt_times.size
end
i += 1
end
end
#write the newly created calculations based on gps data to a file
def self.write_gps_calculations(upload_id,type)
i = 0
file = File.new("#{$data_directory}/#{type}/#{upload_id}/calculations.txt", 'w')
file2 = File.new("#{$data_directory}/#{type}/#{upload_id}/calculations-strip.txt", 'w')
#file.puts "format: GMT time, relative time, lat, long, elev, planar distance, adjusted distance, speed, accel, calc power"
#file2.puts "format: GMT time, relative time, elev, planar distance, adjusted distance, speed, accel, calc power, power, current, voltage"
num_times = @gmt_times.size
while i < num_times do
file.puts "#{@gmt_times[i]},#{@times[i]},#{@lats[i]},#{@lngs[i]},#{@elvs[i]},#{@planar_dists[i]},#{@adjusted_dists[i]},#{@speeds[i]},#{@accels[i]},#{@calc_power[i]}"
file2.puts "#{@gmt_times[i]},#{@times[i]},#{@elvs[i]},#{@planar_dists[i]},#{@adjusted_dists[i]},#{@speeds[i]},#{@accels[i]},#{@calc_power[i]}"
i += 1
end
file.close
file2.close
end
#segment gps calculation files for use with graphing - done becuase large time gaps may occur in trip and graphing "breaks" as a result
def self.segment_gps_data(upload_id,type)
segment = 1
i = 1
file = File.new("#{$data_directory}/#{type}/#{upload_id}/calculations-#{segment}.txt", 'w')
file.puts "#{@gmt_times[0]},#{@times[0]},#{@lats[0]},#{@lngs[0]},#{@elvs[0]},#{@planar_dists[0]},#{@adjusted_dists[0]},#{@speeds[0]},#{@accels[0]},#{@calc_power[0]}"
num_times = @gmt_times.size
while i < num_times do
if ((@times[i] - @times[i-1]) > 60 * 10) #10 minutes have passed, create a new drive segment
file.close
segment += 1
file = File.new("#{$data_directory}/#{type}/#{upload_id}/calculations-#{segment}.txt", 'w')
end
file.puts "#{@gmt_times[i]},#{@times[i]},#{@lats[i]},#{@lngs[i]},#{@elvs[i]},#{@planar_dists[i]},#{@adjusted_dists[i]},#{@speeds[i]},#{@accels[i]},#{@calc_power[i]}"
i += 1
end
file.close
end
*/
| minimal EOD | chargecarprize/javatestsuite/ChargeCarPrize/src/chargecar/util/GPXTripParser.java | minimal EOD |
|
Java | epl-1.0 | 19393bf2f99a0f17a9176b6d0794ed8824b0f5bf | 0 | LeoNerdoG/kapua,LeoNerdoG/kapua,LeoNerdoG/kapua,cbaerikebc/kapua,LeoNerdoG/kapua,stzilli/kapua,stzilli/kapua,cbaerikebc/kapua,stzilli/kapua,cbaerikebc/kapua,cbaerikebc/kapua,LeoNerdoG/kapua,stzilli/kapua,stzilli/kapua | /*******************************************************************************
* Copyright (c) 2011, 2016 Eurotech and/or its affiliates
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Eurotech - initial API and implementation
*******************************************************************************/
package org.eclipse.kapua.locator.guice;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.eclipse.kapua.locator.KapuaLocatorErrorCodes;
import org.eclipse.kapua.locator.KapuaLocatorException;
public class LocatorConfig {
private static final String SERVICE_RESOURCE_INTERFACES = "provided.api";
private static final String SERVICE_RESOURCE_PACKAGES = "packages.package";
private final URL url;
private final List<String> packageNames;
private final List<String> providedInterfaceNames;
private LocatorConfig(URL url) {
this.url = url;
packageNames = new ArrayList<>();
providedInterfaceNames = new ArrayList<>();
}
public static LocatorConfig fromURL(URL url) throws KapuaLocatorException {
if (url == null) {
throw new IllegalArgumentException();
}
LocatorConfig config = new LocatorConfig(url);
XMLConfiguration xmlConfig;
try {
xmlConfig = new XMLConfiguration(url);
} catch (ConfigurationException e) {
throw new KapuaLocatorException(KapuaLocatorErrorCodes.INVALID_CONFIGURATION, e);
}
Object props = xmlConfig.getProperty(SERVICE_RESOURCE_PACKAGES);
if (props instanceof Collection) {
config.packageNames.addAll((Collection<String>) props);
}
if (props instanceof String) {
config.packageNames.add((String) props);
}
props = xmlConfig.getProperty(SERVICE_RESOURCE_INTERFACES);
if (props instanceof Collection) {
config.providedInterfaceNames.addAll((Collection<String>) props);
}
if (props instanceof String) {
config.providedInterfaceNames.add((String) props);
}
return config;
}
public URL getURL() {
return url;
}
public Collection<String> getPackageNames() {
return Collections.unmodifiableCollection(packageNames);
}
public Collection<String> getProvidedInterfaceNames() {
return Collections.unmodifiableCollection(providedInterfaceNames);
}
}
| locator/guice/src/main/java/org/eclipse/kapua/locator/guice/LocatorConfig.java | /*******************************************************************************
* Copyright (c) 2011, 2016 Eurotech and/or its affiliates
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Eurotech - initial API and implementation
*******************************************************************************/
package org.eclipse.kapua.locator.guice;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.eclipse.kapua.locator.KapuaLocatorErrorCodes;
import org.eclipse.kapua.locator.KapuaLocatorException;
public class LocatorConfig {
private static final String SERVICE_RESOURCE_INTERFACES = "provided.api";
private static final String SERVICE_RESOURCE_PACKAGES = "packages.package";
private final URL url;
private List<String> packageNames;
private List<String> providedInterfaceNames;
private LocatorConfig(URL url)
{
this.url = url;
this.packageNames = new ArrayList<String>();
this.providedInterfaceNames = new ArrayList<String>();
}
public static LocatorConfig fromURL(URL url) throws KapuaLocatorException
{
if (url == null)
throw new IllegalArgumentException();
LocatorConfig config = new LocatorConfig(url);
XMLConfiguration xmlConfig;
try {
xmlConfig = new XMLConfiguration(url);
} catch (ConfigurationException e) {
throw new KapuaLocatorException(KapuaLocatorErrorCodes.INVALID_CONFIGURATION, e);
}
Object props = xmlConfig.getProperty(SERVICE_RESOURCE_PACKAGES);
if (props instanceof Collection)
config.packageNames.addAll((Collection<String>) props);
if (props instanceof String)
config.packageNames.add((String) props);
props = xmlConfig.getProperty(SERVICE_RESOURCE_INTERFACES);
if (props instanceof Collection)
config.providedInterfaceNames.addAll((Collection<String>) props);
if (props instanceof String)
config.providedInterfaceNames.add((String)props);
return config;
}
public URL getURL() {
return url;
}
public Collection<String> getPackageNames() {
return Collections.unmodifiableCollection(packageNames);
}
public Collection<String> getProvidedInterfaceNames() {
return Collections.unmodifiableCollection(providedInterfaceNames);
}
}
| Apply code formatter and cleanup
Signed-off-by: Jens Reimann <[email protected]> | locator/guice/src/main/java/org/eclipse/kapua/locator/guice/LocatorConfig.java | Apply code formatter and cleanup |
|
Java | epl-1.0 | 916f85bff7529acc597183deab11a6f270c3266b | 0 | ESSICS/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,css-iter/cs-studio | package org.csstudio.swt.xygraph.undo;
/**
* @author Xihui Chen
*
*/
public interface IUndoableCommand {
/**
* Restore the state of the target to the state before this
* command has been executed.
*/
public void undo();
/**
* Restore the state of the target to the state after this
* command has been executed.
*/
public void redo();
// toString() is used to obtain the text that's used
// when displaying this command in the GUI
}
| applications/plugins/org.csstudio.swt.xygraph/src/org/csstudio/swt/xygraph/undo/IUndoableCommand.java | package org.csstudio.swt.xygraph.undo;
/**
* @author Xihui Chen
*
*/
public interface IUndoableCommand {
/**
* Restore the state of the target to the state before this
* command has been executed.
*/
public void undo();
/**
* Restore the state of the target to the state after this
* command has been executed.
*/
public void redo();
}
| toString
| applications/plugins/org.csstudio.swt.xygraph/src/org/csstudio/swt/xygraph/undo/IUndoableCommand.java | toString |
|
Java | epl-1.0 | 2da43ca8a8a2e1b2bebd9c9f0e90cc1af9c76c43 | 0 | Yakindu/statecharts,Yakindu/statecharts,Yakindu/statecharts,Yakindu/statecharts,Yakindu/statecharts,Yakindu/statecharts,Yakindu/statecharts | /**
* Copyright (c) 2011 committers of YAKINDU and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
* Contributors:
* committers of YAKINDU - initial API and implementation
*
*/
package org.yakindu.sct.ui.editor.propertysheets;
import org.eclipse.core.databinding.UpdateValueStrategy;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.databinding.EMFDataBindingContext;
import org.eclipse.emf.databinding.IEMFValueProperty;
import org.eclipse.emf.databinding.edit.EMFEditProperties;
import org.eclipse.emf.transaction.util.TransactionUtil;
import org.eclipse.jface.databinding.swt.ISWTObservableValue;
import org.eclipse.jface.databinding.swt.WidgetProperties;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.Text;
import org.yakindu.base.base.BasePackage;
import org.yakindu.sct.model.sgraph.SGraphPackage;
import org.yakindu.sct.ui.editor.extensions.ExpressionLanguageProviderExtensions.SemanticTarget;
import org.yakindu.sct.ui.editor.utils.HelpContextIds;
import com.google.inject.Injector;
/**
*
* @author andreas muelder - Initial contribution and API
*
*/
public class TransitionPropertySection extends
AbstractTwoColumnEditorPropertySection {
private Control textControl;
private Text txtDoc;
protected Layout createLeftColumnLayout() {
return new GridLayout(2, false);
}
@Override
protected void createLeftColumnControls(Composite parent) {
Label lblExpression = getToolkit().createLabel(parent, "Expression: ");
GridDataFactory.fillDefaults().span(2, 1).applyTo(lblExpression);
Injector injector = getInjector(SemanticTarget.TransitionSpecification);
if (injector != null) {
textControl = new StyledText(parent, SWT.MULTI | SWT.BORDER
| SWT.V_SCROLL | SWT.WRAP);
((StyledText) textControl).setAlwaysShowScrollBars(false);
enableXtext(textControl, injector);
createHelpWidget(parent, textControl,
HelpContextIds.SC_PROPERTIES_TRANSITION_EXPRESSION);
} else {
textControl = getToolkit().createText(parent, "", SWT.MULTI);
}
GridDataFactory.fillDefaults().grab(true, true).hint(parent.getSize())
.applyTo(textControl);
}
@Override
protected void createRightColumnControls(Composite parent) {
Label lblDocumentation = getToolkit().createLabel(parent,
"Documentation: ");
txtDoc = getToolkit().createText(parent, "", SWT.MULTI);
GridDataFactory.fillDefaults().span(2, 1).applyTo(lblDocumentation);
GridDataFactory.fillDefaults().grab(true, true).applyTo(txtDoc);
}
@Override
public void bindModel(EMFDataBindingContext context) {
IEMFValueProperty modelProperty = EMFEditProperties.value(
TransactionUtil.getEditingDomain(eObject),
SGraphPackage.Literals.SPECIFICATION_ELEMENT__SPECIFICATION);
ISWTObservableValue uiProperty = WidgetProperties.text(SWT.FocusOut)
.observe(textControl);
context.bindValue(uiProperty, modelProperty.observe(eObject), null,
new UpdateValueStrategy() {
@Override
protected IStatus doSet(IObservableValue observableValue,
Object value) {
if (!getCompletionProposalAdapter()
.isProposalPopupOpen())
return super.doSet(observableValue, value);
return Status.OK_STATUS;
}
});
IEMFValueProperty property = EMFEditProperties.value(
TransactionUtil.getEditingDomain(eObject),
BasePackage.Literals.DOCUMENTED_ELEMENT__DOCUMENTATION);
ISWTObservableValue observe = WidgetProperties.text(
new int[] { SWT.FocusOut, SWT.DefaultSelection }).observe(
txtDoc);
context.bindValue(observe, property.observe(eObject));
}
}
| plugins/org.yakindu.sct.ui.editor/src/org/yakindu/sct/ui/editor/propertysheets/TransitionPropertySection.java | /**
* Copyright (c) 2011 committers of YAKINDU and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
* Contributors:
* committers of YAKINDU - initial API and implementation
*
*/
package org.yakindu.sct.ui.editor.propertysheets;
import org.eclipse.core.databinding.UpdateValueStrategy;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.databinding.EMFDataBindingContext;
import org.eclipse.emf.databinding.IEMFValueProperty;
import org.eclipse.emf.databinding.edit.EMFEditProperties;
import org.eclipse.emf.transaction.util.TransactionUtil;
import org.eclipse.jface.databinding.swt.ISWTObservableValue;
import org.eclipse.jface.databinding.swt.WidgetProperties;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.Text;
import org.yakindu.base.base.BasePackage;
import org.yakindu.sct.model.sgraph.SGraphPackage;
import org.yakindu.sct.ui.editor.extensions.ExpressionLanguageProviderExtensions.SemanticTarget;
import org.yakindu.sct.ui.editor.utils.HelpContextIds;
import com.google.inject.Injector;
/**
*
* @author andreas muelder - Initial contribution and API
*
*/
public class TransitionPropertySection extends AbstractEditorPropertySection {
private Control textControl;
private Text txtDoc;
@Override
protected Layout createBodyLayout() {
return new GridLayout(2, false);
}
@Override
public void createControls(Composite parent) {
Injector injector = getInjector(SemanticTarget.TransitionSpecification);
if (injector != null) {
textControl = new StyledText(parent, SWT.MULTI | SWT.BORDER
| SWT.V_SCROLL | SWT.WRAP);
((StyledText) textControl).setAlwaysShowScrollBars(false);
enableXtext(textControl, injector);
createHelpWidget(parent, textControl,
HelpContextIds.SC_PROPERTIES_TRANSITION_EXPRESSION);
} else {
textControl = getToolkit().createText(parent, "", SWT.MULTI);
}
GridDataFactory.fillDefaults().grab(true, true).hint(parent.getSize())
.applyTo(textControl);
Label lblDocumentation = getToolkit().createLabel(parent,
"Documentation: ");
txtDoc = getToolkit().createText(parent, "", SWT.MULTI);
GridDataFactory.fillDefaults().span(2,1).applyTo(lblDocumentation);
GridDataFactory.fillDefaults().grab(true,true).applyTo(txtDoc);
}
@Override
public void bindModel(EMFDataBindingContext context) {
IEMFValueProperty modelProperty = EMFEditProperties.value(
TransactionUtil.getEditingDomain(eObject),
SGraphPackage.Literals.SPECIFICATION_ELEMENT__SPECIFICATION);
ISWTObservableValue uiProperty = WidgetProperties.text(SWT.FocusOut)
.observe(textControl);
context.bindValue(uiProperty, modelProperty.observe(eObject), null,
new UpdateValueStrategy() {
@Override
protected IStatus doSet(IObservableValue observableValue,
Object value) {
if (!getCompletionProposalAdapter()
.isProposalPopupOpen())
return super.doSet(observableValue, value);
return Status.OK_STATUS;
}
});
IEMFValueProperty property = EMFEditProperties.value(
TransactionUtil.getEditingDomain(eObject),
BasePackage.Literals.DOCUMENTED_ELEMENT__DOCUMENTATION);
ISWTObservableValue observe = WidgetProperties.text(
new int[] { SWT.FocusOut, SWT.DefaultSelection }).observe(
txtDoc);
context.bindValue(observe, property.observe(eObject));
}
}
| 2 Column Transition Property Page | plugins/org.yakindu.sct.ui.editor/src/org/yakindu/sct/ui/editor/propertysheets/TransitionPropertySection.java | 2 Column Transition Property Page |
|
Java | epl-1.0 | a32f9216211902390542ab331f8c273265d7399c | 0 | rohitmohan96/ceylon-ide-eclipse,rohitmohan96/ceylon-ide-eclipse | package com.redhat.ceylon.eclipse.util;
import static com.redhat.ceylon.compiler.java.codegen.CodegenUtil.getJavaNameOfDeclaration;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.getCeylonClassesOutputFolder;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.getProjectTypeChecker;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.isExplodeModulesEnabled;
import static com.redhat.ceylon.eclipse.util.Escaping.toInitialLowercase;
import static com.redhat.ceylon.model.loader.AbstractModelLoader.CEYLON_ATTRIBUTE_ANNOTATION;
import static com.redhat.ceylon.model.loader.AbstractModelLoader.CEYLON_CEYLON_ANNOTATION;
import static com.redhat.ceylon.model.loader.AbstractModelLoader.CEYLON_LOCAL_DECLARATION_ANNOTATION;
import static com.redhat.ceylon.model.loader.AbstractModelLoader.CEYLON_METHOD_ANNOTATION;
import static com.redhat.ceylon.model.loader.AbstractModelLoader.CEYLON_NAME_ANNOTATION;
import static com.redhat.ceylon.model.loader.AbstractModelLoader.CEYLON_OBJECT_ANNOTATION;
import static java.util.Collections.emptyList;
import static org.eclipse.jdt.core.IJavaElement.PACKAGE_FRAGMENT;
import static org.eclipse.jdt.core.search.IJavaSearchConstants.CLASS_AND_INTERFACE;
import static org.eclipse.jdt.core.search.IJavaSearchConstants.FIELD;
import static org.eclipse.jdt.core.search.IJavaSearchConstants.METHOD;
import static org.eclipse.jdt.core.search.SearchPattern.R_EXACT_MATCH;
import static org.eclipse.jdt.core.search.SearchPattern.createOrPattern;
import static org.eclipse.jdt.core.search.SearchPattern.createPattern;
import static org.eclipse.jdt.internal.core.util.Util.getUnresolvedJavaElement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IAnnotatable;
import org.eclipse.jdt.core.IAnnotation;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.ILocalVariable;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMemberValuePair;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.core.search.SearchPattern;
import org.eclipse.jdt.core.search.SearchRequestor;
import org.eclipse.jdt.internal.compiler.env.IBinaryType;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.core.JavaElement;
import org.eclipse.jdt.internal.corext.util.SearchUtils;
import com.redhat.ceylon.compiler.java.codegen.Naming;
import com.redhat.ceylon.compiler.java.language.AbstractCallable;
import com.redhat.ceylon.compiler.typechecker.TypeChecker;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.eclipse.core.builder.CeylonBuilder;
import com.redhat.ceylon.eclipse.core.builder.CeylonNature;
import com.redhat.ceylon.eclipse.core.model.CeylonBinaryUnit;
import com.redhat.ceylon.eclipse.core.model.CeylonUnit;
import com.redhat.ceylon.eclipse.core.model.IJavaModelAware;
import com.redhat.ceylon.eclipse.core.model.JDTModelLoader;
import com.redhat.ceylon.eclipse.core.model.JDTModelLoader.ActionOnResolvedGeneratedType;
import com.redhat.ceylon.eclipse.core.model.JDTModule;
import com.redhat.ceylon.model.loader.ModelLoader.DeclarationType;
import com.redhat.ceylon.model.loader.NamingBase;
import com.redhat.ceylon.model.loader.NamingBase.Prefix;
import com.redhat.ceylon.model.loader.NamingBase.Suffix;
import com.redhat.ceylon.model.typechecker.model.Declaration;
import com.redhat.ceylon.model.typechecker.model.Function;
import com.redhat.ceylon.model.typechecker.model.ModelUtil;
import com.redhat.ceylon.model.typechecker.model.Module;
import com.redhat.ceylon.model.typechecker.model.Modules;
import com.redhat.ceylon.model.typechecker.model.Package;
import com.redhat.ceylon.model.typechecker.model.Scope;
import com.redhat.ceylon.model.typechecker.model.Specification;
import com.redhat.ceylon.model.typechecker.model.Unit;
import com.redhat.ceylon.model.typechecker.model.Value;
public class JavaSearch {
public static SearchPattern createSearchPattern(
Declaration declaration, int limitTo) {
String pattern;
try {
pattern = getJavaNameOfDeclaration(declaration);
}
catch (IllegalArgumentException iae) {
return null;
}
if (declaration instanceof Function) {
return createPattern(pattern, METHOD,
limitTo, R_EXACT_MATCH);
}
else if (declaration instanceof Value) {
int loc = pattern.lastIndexOf('.') + 1;
if (pattern.substring(loc).startsWith("get")) {
String setter =
pattern.substring(0,loc) +
"set" + pattern.substring(loc+3);
SearchPattern getterPattern =
createPattern(pattern, METHOD,
limitTo, R_EXACT_MATCH);
SearchPattern setterPattern =
createPattern(setter, METHOD,
limitTo, R_EXACT_MATCH);
switch (limitTo) {
case IJavaSearchConstants.WRITE_ACCESSES:
return setterPattern;
case IJavaSearchConstants.READ_ACCESSES:
return getterPattern;
default:
return createOrPattern(getterPattern,
setterPattern);
}
}
else {
SearchPattern fieldPattern =
createPattern(pattern, FIELD,
limitTo, R_EXACT_MATCH);
return fieldPattern;
}
}
else {
SearchPattern searchPattern =
createPattern(pattern, CLASS_AND_INTERFACE,
limitTo, R_EXACT_MATCH);
//weirdly, ALL_OCCURRENCES doesn't return all occurrences
/*if (limitTo==IJavaSearchConstants.ALL_OCCURRENCES) {
searchPattern = createOrPattern(createPattern(pattern, CLASS_AND_INTERFACE,
IJavaSearchConstants.IMPLEMENTORS, R_EXACT_MATCH),
searchPattern);
}*/
return searchPattern;
}
}
public static IProject[] getProjectAndReferencingProjects(
IProject project) {
IProject[] referencingProjects =
project.getReferencingProjects();
IProject[] projects =
new IProject[referencingProjects.length+1];
projects[0] = project;
System.arraycopy(referencingProjects, 0,
projects, 1, referencingProjects.length);
return projects;
}
public static IProject[] getProjectAndReferencedProjects(
IProject project) {
try {
IProject[] referencedProjects =
project.getReferencedProjects();
IProject[] projects =
new IProject[referencedProjects.length+1];
projects[0] = project;
System.arraycopy(referencedProjects, 0,
projects, 1, referencedProjects.length);
return projects;
}
catch (Exception e) {
e.printStackTrace();
return new IProject[] { project };
}
}
@SuppressWarnings("deprecation")
public static void runSearch(
IProgressMonitor pm,
SearchEngine searchEngine,
SearchPattern searchPattern,
IProject[] projects,
SearchRequestor requestor)
throws OperationCanceledException {
try {
searchEngine.search(searchPattern,
SearchUtils.getDefaultSearchParticipants(),
SearchEngine.createJavaSearchScope(projects),
requestor, pm);
}
catch (OperationCanceledException oce) {
throw oce;
}
catch (Exception e) {
e.printStackTrace();
}
}
public static String getJavaQualifiedName(IMember dec) {
IPackageFragment packageFragment =
(IPackageFragment)
dec.getAncestor(PACKAGE_FRAGMENT);
IType type =
(IType)
dec.getAncestor(IJavaElement.TYPE);
String qualifier = packageFragment.getElementName();
if (! qualifier.isEmpty()) {
qualifier += '.';
}
String name = dec.getElementName();
if (dec instanceof IMethod && name.equals("get_")) {
return getJavaQualifiedName(type);
}
else if (dec instanceof IType && name.endsWith("_")) {
return qualifier +
name.substring(0, name.length()-1);
}
if (dec instanceof IMethod) {
if (name.startsWith("$")) {
name = name.substring(1);
}
else if (name.startsWith("get") ||
name.startsWith("set")) {
name = toInitialLowercase(name.substring(3));
}
}
if (dec!=type) {
String fullyQualifiedTypeName =
type.getFullyQualifiedName();
String[] parts =
fullyQualifiedTypeName.split("\\.");
String typeName =
parts.length == 0 ?
fullyQualifiedTypeName :
parts[parts.length-1];
if (typeName.endsWith(name + "_")) {
return qualifier + name;
}
else {
return qualifier +
typeName + '.' + name;
}
}
else {
return qualifier + name;
}
}
private static boolean isCeylon(IMember element) {
if (element instanceof IAnnotatable) {
IAnnotatable annotatable =
(IAnnotatable) element;
IAnnotation ceylonAnnotation =
annotatable.getAnnotation(
CEYLON_CEYLON_ANNOTATION);
return ceylonAnnotation.exists();
}
return false;
}
private static boolean isCeylonObject(IMember element) {
if (element instanceof IAnnotatable) {
IAnnotatable annotatable =
(IAnnotatable) element;
IAnnotation ceylonAnnotation =
annotatable.getAnnotation(
CEYLON_OBJECT_ANNOTATION);
return ceylonAnnotation.exists();
}
return false;
}
private static boolean isCeylonAttribute(IMember element) {
if (element instanceof IAnnotatable) {
IAnnotatable annotatable =
(IAnnotatable) element;
IAnnotation ceylonAnnotation =
annotatable.getAnnotation(
CEYLON_ATTRIBUTE_ANNOTATION);
return ceylonAnnotation.exists();
}
return false;
}
private static boolean isCeylonMethod(IMember element) {
if (element instanceof IAnnotatable) {
IAnnotatable annotatable =
(IAnnotatable) element;
IAnnotation ceylonAnnotation =
annotatable.getAnnotation(
CEYLON_METHOD_ANNOTATION);
return ceylonAnnotation.exists();
}
return false;
}
private static String getCeylonNameAnnotationValue(
IMember element) {
if (element instanceof IAnnotatable) {
IAnnotatable annotatable =
(IAnnotatable) element;
IAnnotation nameAnnotation =
annotatable.getAnnotation(
CEYLON_NAME_ANNOTATION);
if (nameAnnotation.exists()) {
try {
for (IMemberValuePair mvp:
nameAnnotation.getMemberValuePairs()) {
if ("value".equals(mvp.getMemberName())) {
Object value = mvp.getValue();
if ((value instanceof String)
&& ! "".equals(value)) {
return (String) value;
}
}
}
} catch (JavaModelException e) {
e.printStackTrace();
}
}
}
return null;
}
private static String getLocalDeclarationQualifier(
IMember element) {
if (element instanceof IAnnotatable) {
IAnnotatable annotatable =
(IAnnotatable) element;
IAnnotation nameAnnotation =
annotatable.getAnnotation(
CEYLON_LOCAL_DECLARATION_ANNOTATION);
if (nameAnnotation.exists()) {
try {
for (IMemberValuePair mvp:
nameAnnotation.getMemberValuePairs()) {
if ("qualifier".equals(
mvp.getMemberName())) {
Object value = mvp.getValue();
if ((value instanceof String)
&& ! "".equals(value)) {
return (String) value;
}
}
}
} catch (JavaModelException e) {
e.printStackTrace();
}
}
}
return null;
}
public static class JdtDefaultArgumentMethodSearch
extends DefaultArgumentMethodSearch<IMethod> {
@Override
protected String getMethodName(IMethod method) {
return method.getElementName();
}
@Override
protected boolean isMethodPrivate(IMethod method) {
try {
return (method.getFlags() &
Flags.AccPrivate)
!= 0;
} catch (JavaModelException e) {
e.printStackTrace();
return false;
}
}
@Override
protected List<IMethod> getMethodsOfDeclaringType(
IMethod method, String searchedName) {
IType declaringType = method.getDeclaringType();
if (declaringType == null) {
return emptyList();
}
List<IMethod> foundMethods = new ArrayList<>();
try {
for (IMethod m: declaringType.getMethods()) {
if (searchedName == null ||
searchedName.equals(
m.getElementName())) {
foundMethods.add(m);
}
}
} catch (JavaModelException e) {
e.printStackTrace();
return emptyList();
}
return foundMethods;
}
@Override
protected List<String> getParameterNames(IMethod method) {
List<String> paramNames = new ArrayList<>();
try {
for (ILocalVariable param:
method.getParameters()) {
String paramName = null;
IAnnotation nameAnnotation =
param.getAnnotation(
CEYLON_NAME_ANNOTATION);
if (nameAnnotation != null &&
nameAnnotation.exists()) {
IMemberValuePair[] valuePairs =
nameAnnotation.getMemberValuePairs();
if (valuePairs != null &&
valuePairs.length > 0) {
paramName =
(String)
valuePairs[0]
.getValue();
}
}
if (paramName == null) {
paramName = param.getElementName();
}
paramNames.add(paramName);
}
return Arrays.asList(method.getParameterNames());
} catch (JavaModelException e) {
e.printStackTrace();
return Collections.emptyList();
}
}
}
public static abstract class DefaultArgumentMethodSearch<MethodType> {
public class Result {
public Result(MethodType defaultArgumentMethod,
String defaultArgumentName,
MethodType overloadedMethod,
MethodType implementationMethod) {
this.defaultArgumentMethod = defaultArgumentMethod;
this.defaultArgumentName = defaultArgumentName;
this.overloadedMethod = overloadedMethod;
this.implementationMethod = implementationMethod;
}
public MethodType defaultArgumentMethod;
public String defaultArgumentName;
public MethodType overloadedMethod;
public MethodType implementationMethod;
}
protected abstract String getMethodName(
MethodType method);
protected abstract boolean isMethodPrivate(
MethodType method);
protected abstract List<MethodType> getMethodsOfDeclaringType(
MethodType method, String name);
protected abstract List<String> getParameterNames(
MethodType method);
public Result search(MethodType method) {
String methodName = getMethodName(method);
if (methodName.endsWith(
NamingBase.Suffix.$canonical$.name())) {
return new Result(null, null, null, method);
}
String[] parts = methodName.split("\\$");
if (methodName.startsWith("$") &&
parts.length > 0) {
parts[0] = "$" + parts[0];
}
String searchedMethodName = "";
boolean canBeADefaultArgumentMethod;
if (parts.length == 2 &&
! methodName.endsWith("$")) {
canBeADefaultArgumentMethod = true;
searchedMethodName = parts[0];
if (isMethodPrivate(method)) {
searchedMethodName +=
NamingBase.Suffix.$priv$.name();
}
} else {
canBeADefaultArgumentMethod = false;
searchedMethodName = methodName;
}
MethodType canonicalMethod = null;
List<MethodType> canonicalMethodSearchResult =
getMethodsOfDeclaringType(method,
searchedMethodName +
NamingBase.Suffix.$canonical$.name());
if (canonicalMethodSearchResult != null &&
! canonicalMethodSearchResult.isEmpty()) {
canonicalMethod =
canonicalMethodSearchResult.get(0);
} else {
List<String> defaultArguments =
new ArrayList<>();
List<MethodType> defaultArgumentMethods =
new ArrayList<>();
for (MethodType m:
getMethodsOfDeclaringType(method,
null)) {
if (getMethodName(m)
.startsWith(parts[0] + "$")) {
defaultArgumentMethods.add(m);
}
}
if (! defaultArgumentMethods.isEmpty()) {
for (MethodType defaultArgumentMethod:
defaultArgumentMethods) {
String argumentName =
getMethodName(
defaultArgumentMethod)
.substring(parts[0].length() + 1);
if (! argumentName.isEmpty()) {
defaultArguments.add(argumentName);
}
}
}
if (! defaultArguments.isEmpty()) {
List<MethodType> overloadedMethods =
getMethodsOfDeclaringType(method,
parts[0]);
if (overloadedMethods.size() > 1) {
for (MethodType overloadedMethod:
overloadedMethods) {
List<String> argumentNames =
getParameterNames(
overloadedMethod);
if (argumentNames.size()
< defaultArguments.size()) {
continue;
}
if (! argumentNames.containsAll(
defaultArguments)) {
continue;
}
canonicalMethod = overloadedMethod;
break;
}
}
}
}
if (canonicalMethod != null) {
if (canBeADefaultArgumentMethod) {
if (getParameterNames(canonicalMethod)
.contains(parts[1])) {
return new Result(method, parts[1],
null, canonicalMethod);
}
} else {
if (canonicalMethod.equals(method)) {
return new Result(null, null, null,
canonicalMethod);
} else {
return new Result(null, null, method,
canonicalMethod);
}
}
}
return new Result(null, null, null, null);
}
}
/*
* returns null if it's a method with no Ceylon equivalent
* (internal getter of a Ceylon object value)
*/
public static String getCeylonSimpleName(IMember dec) {
String name = dec.getElementName();
String nameAnnotationValue =
getCeylonNameAnnotationValue(dec);
if (nameAnnotationValue != null) {
return nameAnnotationValue;
}
if (dec instanceof IMethod) {
if (name.startsWith(Prefix.$default$.name())) {
name = name.substring(
Prefix.$default$.name()
.length());
} else if (name.equals("get_")) {
boolean isStatic = false;
int parameterCount = 0;
IMethod method = (IMethod) dec;
try {
isStatic =
(method.getFlags() &
Flags.AccStatic)
!= 0;
parameterCount =
method.getParameterNames()
.length;
} catch (JavaModelException e) {
e.printStackTrace();
}
if (isStatic && parameterCount == 0) {
name = null;
}
} else if (name.startsWith("$")) {
name = name.substring(1);
} else if ((name.startsWith("get")
|| name.startsWith("set"))
&& name.length() > 3) {
StringBuffer newName =
new StringBuffer(
Character.toLowerCase(
name.charAt(3)));
if (name.length() > 4) {
newName.append(name.substring(4));
}
name = newName.toString();
} else if (name.equals("toString")) {
name = "string";
} else if (name.equals("hashCode")) {
name = "hash";
} else if (name.contains("$")) {
IMethod method = (IMethod) dec;
JdtDefaultArgumentMethodSearch.Result searchResult =
new JdtDefaultArgumentMethodSearch()
.search(method);
if (searchResult.defaultArgumentName != null) {
name = searchResult.defaultArgumentName;
}
}
if (name.endsWith(Suffix.$canonical$.name())) {
name = name.substring(0,
name.length() -
Suffix.$canonical$.name().length());
}
if (name.endsWith(Suffix.$priv$.name())) {
name = name.substring(0,
name.length() -
Suffix.$priv$.name().length());
}
} else if (dec instanceof IType) {
IType type = (IType) dec;
if (name.endsWith("_")) {
if (isCeylonObject(type) ||
isCeylonMethod(type)) {
name = name.substring(0,
name.length()-1);
}
}
}
return name;
}
public static boolean elementEqualsDeclaration(
IMember typeOrMethod, Declaration declaration) {
// loadAllAnnotations(typeOrMethod); // Uncomment to easily load all annotations while debugging
String javaElementSimpleName =
getCeylonSimpleName(typeOrMethod);
String ceylonDeclarationSimpleName =
declaration.getName();
if (javaElementSimpleName == null) {
return false;
}
if (!javaElementSimpleName.equals(
ceylonDeclarationSimpleName)) {
if ( javaElementSimpleName.isEmpty()) {
try {
if (!(typeOrMethod instanceof IType
&& ((IType)typeOrMethod).isAnonymous()
&& (declaration instanceof Function)
&& ! isCeylonObject(typeOrMethod)
&& AbstractCallable.class.getName()
.equals(((IType) typeOrMethod)
.getSuperclassName()))) {
return false;
}
} catch (JavaModelException e) {
e.printStackTrace();
return false;
}
} else {
return false;
}
}
if (typeOrMethod instanceof IType) {
String localDeclarationQualifier =
getLocalDeclarationQualifier(
typeOrMethod);
if (localDeclarationQualifier != null) {
if (!localDeclarationQualifier.equals(
declaration.getQualifier())) {
return false;
}
}
if (isCeylonObject(typeOrMethod)
&& declaration.isToplevel()
&& !(declaration instanceof Value)) {
return false;
}
}
IMember declaringElement =
getDeclaringElement(typeOrMethod);
if (declaringElement != null) {
declaringElement =
toCeylonDeclarationElement(
declaringElement);
Declaration ceylonContainingDeclaration =
getContainingDeclaration(declaration);
if (ceylonContainingDeclaration != null) {
return elementEqualsDeclaration(
declaringElement,
(Declaration)
ceylonContainingDeclaration);
}
} else {
Scope scope = declaration.getScope();
if (scope instanceof Package) {
String ceylonDeclarationPkgName =
scope.getQualifiedNameString();
IPackageFragment pkgFragment =
(IPackageFragment)
typeOrMethod.getAncestor(
PACKAGE_FRAGMENT);
String pkgFragmentName =
pkgFragment == null ? null :
pkgFragment.getElementName();
return ceylonDeclarationPkgName.equals(
pkgFragmentName);
}
}
return false;
}
public static void loadAllAnnotations(IMember typeOrMethod) {
Map<String, Map<String, Object>> memberAnnotations =
new HashMap<String, Map<String, Object>>();
if (typeOrMethod instanceof IAnnotatable) {
try {
IAnnotatable annotatable =
(IAnnotatable) typeOrMethod;
for (IAnnotation annotation:
annotatable.getAnnotations()) {
String annotationName =
annotation.getElementName();
if (!memberAnnotations.containsKey(
annotationName)) {
memberAnnotations.put(annotationName,
new HashMap<String, Object>());
}
Map<String, Object> annotationMembers =
memberAnnotations.get(
annotationName);
for (IMemberValuePair pair:
annotation.getMemberValuePairs()) {
annotationMembers.put(
pair.getMemberName(),
pair.getValue());
}
}
} catch (JavaModelException e) {
e.printStackTrace();
}
}
Map<String, Map<String, Object>> typeAnnotations =
new HashMap<String, Map<String, Object>>();
if (typeOrMethod instanceof IType) {
IType type = (IType) typeOrMethod;
try {
IAnnotatable annotatable =
(IAnnotatable) type;
for (IAnnotation annotation:
annotatable.getAnnotations()) {
String annotationName =
annotation.getElementName();
if (! typeAnnotations.containsKey(
annotationName)) {
typeAnnotations.put(annotationName,
new HashMap<String, Object>());
}
Map<String, Object> annotationMembers =
typeAnnotations.get(annotationName);
for (IMemberValuePair pair:
annotation.getMemberValuePairs()) {
annotationMembers.put(
pair.getMemberName(),
pair.getValue());
}
}
} catch (JavaModelException e) {
e.printStackTrace();
}
}
}
public static Declaration getContainingDeclaration(
Declaration declaration) {
Declaration ceylonContainingDeclaration = null;
if (declaration == null) {
return null;
}
if (! declaration.isToplevel()) {
Scope scope = declaration.getContainer();
while (!(scope instanceof Package)) {
if (scope instanceof Declaration) {
ceylonContainingDeclaration =
(Declaration) scope;
break;
}
if (scope instanceof Specification) {
Specification specification =
(Specification) scope;
ceylonContainingDeclaration =
specification.getDeclaration();
break;
}
scope = scope.getContainer();
}
}
return ceylonContainingDeclaration;
}
public static IMember getDeclaringElement(IMember typeOrMethod) {
// TODO : also manage the case of local declarations that are
// wrongly top-level (specific retrieval of the parent IMember)
IMember declaringElement =
typeOrMethod.getDeclaringType();
if (declaringElement == null) {
if (typeOrMethod instanceof IType) {
IType type = (IType) typeOrMethod;
try {
if (type.isLocal() ||type.isAnonymous() || false) {
final MethodBinding[] enclosingMethodBinding =
new MethodBinding[1];
JDTModelLoader.doOnResolvedGeneratedType(type,
new ActionOnResolvedGeneratedType() {
@Override
public void doWithBinding(
IType classModel,
ReferenceBinding classBinding,
IBinaryType binaryType) {
char[] enclosingMethodSignature =
binaryType.getEnclosingMethod();
if (enclosingMethodSignature != null
&& enclosingMethodSignature.length > 0) {
ReferenceBinding enclosingType =
classBinding.enclosingType();
if (enclosingType != null) {
for (MethodBinding method:
enclosingType.methods()) {
if (CharOperation.equals(
CharOperation.concat(
method.selector,
method.signature()),
enclosingMethodSignature)) {
enclosingMethodBinding[0] = method;
break;
}
}
}
}
}
});
if (enclosingMethodBinding[0] != null) {
IMethod enclosingMethod =
(IMethod)
getUnresolvedJavaElement(
enclosingMethodBinding[0],
null, null);
if (enclosingMethod != null &&
!enclosingMethod.isResolved()) {
JavaElement je =
(JavaElement)
enclosingMethod;
enclosingMethod =
(IMethod)
je.resolved(enclosingMethodBinding[0]);
if (enclosingMethod != null) {
declaringElement = enclosingMethod;
}
}
}
}
} catch (JavaModelException e) {
e.printStackTrace();
}
}
} else {
if (typeOrMethod instanceof IMethod) {
IMethod method = (IMethod) typeOrMethod;
String methodName = method.getElementName();
if (declaringElement.getElementName() != null
&& declaringElement.getElementName()
.equals(methodName + "_")
&& isCeylonMethod(declaringElement)) {
IMember declaringElementDeclaringElement =
getDeclaringElement(declaringElement);
return declaringElementDeclaringElement;
} else if (methodName.contains("$")) {
if (declaringElement instanceof IType) {
JdtDefaultArgumentMethodSearch.Result searchResult =
new JdtDefaultArgumentMethodSearch()
.search(method);
if (searchResult.defaultArgumentMethod != null) {
return searchResult.implementationMethod;
}
}
}
}
}
return declaringElement;
}
public static IProject[] getProjectsToSearch(IProject project) {
if (project == null ||
project.getName()
.equals("Ceylon Source Archives")) {
return CeylonBuilder.getProjects()
.toArray(new IProject[0]);
}
else {
return getProjectAndReferencingProjects(project);
}
}
public static IMember toCeylonDeclarationElement(
IMember typeOrMethod) {
if (typeOrMethod instanceof IMethod) {
IMethod method = (IMethod)typeOrMethod;
String methodName = method.getElementName();
if (methodName == null) {
return typeOrMethod;
}
try {
IType parentType = method.getDeclaringType();
if (parentType != null) {
if ("get_".equals(methodName)
&& ((method.getFlags() & Flags.AccStatic) > 0)
&& (isCeylonObject(parentType) ||
isCeylonAttribute(parentType))) {
return toCeylonDeclarationElement(
parentType);
}
if (methodName.equals(
parentType.getElementName())
&& method.isConstructor()
&& isCeylon(parentType)) {
String constructorName =
getCeylonNameAnnotationValue(method);
if (constructorName != null) {
return method;
} else {
return toCeylonDeclarationElement(
parentType);
}
}
if (methodName.equals(Naming.Unfix.$call$.name()) ||
methodName.equals(Naming.Unfix.$calltyped$.name()) ||
methodName.equals(Naming.Unfix.$callvariadic$.name())) {
return toCeylonDeclarationElement(parentType);
}
if (methodName.equals("$evaluate$")) {
return toCeylonDeclarationElement(
getDeclaringElement(parentType));
}
}
} catch (JavaModelException e) {
e.printStackTrace();
}
}
if (typeOrMethod instanceof IType) {
IType type = (IType) typeOrMethod;
String fullyQualifiedTypeName =
type.getFullyQualifiedName();
if (fullyQualifiedTypeName.endsWith("$impl")) {
IType interfaceType = null;
try {
String name =
fullyQualifiedTypeName.substring(0,
fullyQualifiedTypeName.length() - 5);
interfaceType =
type.getJavaProject()
.findType(name,
(IProgressMonitor) null);
} catch (JavaModelException e) {
e.printStackTrace();
}
if (interfaceType != null) {
return toCeylonDeclarationElement(
interfaceType);
}
}
}
return typeOrMethod;
}
public static Declaration toCeylonDeclaration(
IJavaElement javaElement,
List<? extends PhasedUnit> phasedUnits) {
if (! (javaElement instanceof IMember)) {
return null;
}
IMember member = (IMember) javaElement;
IMember declarationElement =
toCeylonDeclarationElement(member);
IProject project =
javaElement.getJavaProject()
.getProject();
Declaration javaSourceTypeDeclaration =
javaSourceElementToTypeDeclaration(
javaElement, project);
if (javaSourceTypeDeclaration != null &&
javaSourceTypeDeclaration.isNative()) {
Declaration headerDeclaration =
ModelUtil.getNativeHeader(
javaSourceTypeDeclaration.getContainer(),
javaSourceTypeDeclaration.getName());
if (headerDeclaration != null) {
if (elementEqualsDeclaration(
declarationElement,
headerDeclaration)) {
return headerDeclaration;
}
Unit nativeHeaderUnit =
headerDeclaration.getUnit();
if (nativeHeaderUnit instanceof CeylonUnit) {
CeylonUnit unit =
(CeylonUnit) nativeHeaderUnit;
PhasedUnit phasedUnit =
unit.getPhasedUnit();
if (phasedUnit != null) {
phasedUnits =
Arrays.asList(phasedUnit);
}
}
}
}
for (PhasedUnit pu: phasedUnits) {
for (Declaration declaration:
pu.getDeclarations()) {
if (elementEqualsDeclaration(
declarationElement, declaration)) {
return declaration;
}
}
}
return null;
}
private static boolean belongsToModule(
IJavaElement javaElement, JDTModule module) {
return javaElement.getAncestor(PACKAGE_FRAGMENT)
.getElementName()
.startsWith(module.getNameAsString());
}
public static Declaration toCeylonDeclaration(
IProject project, IJavaElement javaElement) {
Set<String> searchedArchives = new HashSet<String>();
for (IProject referencedProject:
getProjectAndReferencedProjects(project)) {
if (CeylonNature.isEnabled(referencedProject)) {
TypeChecker typeChecker =
getProjectTypeChecker(referencedProject);
if (typeChecker!=null) {
List<PhasedUnit> phasedUnits =
typeChecker.getPhasedUnits()
.getPhasedUnits();
Declaration result =
toCeylonDeclaration(javaElement,
phasedUnits);
if (result!=null) return result;
Modules modules =
typeChecker.getContext()
.getModules();
for (Module m: modules.getListOfModules()) {
if (m instanceof JDTModule) {
JDTModule module = (JDTModule) m;
if (module.isCeylonArchive() &&
!module.isProjectModule() &&
module.getArtifact()!=null) {
String archivePath =
module.getArtifact()
.getAbsolutePath();
if (searchedArchives.add(archivePath) &&
belongsToModule(javaElement, module)) {
result =
toCeylonDeclaration(
javaElement,
module.getPhasedUnits());
if (result!=null) {
return result;
}
}
}
}
}
}
}
}
return null;
}
public static boolean isCeylonDeclaration(
IJavaElement javaElement) {
IProject project =
javaElement.getJavaProject()
.getProject();
IJavaModelAware unit =
CeylonBuilder.getUnit(javaElement);
IPath path = javaElement.getPath();
if (path!=null) {
if (unit instanceof CeylonBinaryUnit ||
(isExplodeModulesEnabled(project)
&& getCeylonClassesOutputFolder(project)
.getFullPath().isPrefixOf(path))) {
return true;
}
Declaration decl =
javaSourceElementToTypeDeclaration(
javaElement, project);
if (decl != null) {
return true;
}
}
return false;
}
private static Declaration javaSourceElementToTypeDeclaration(
IJavaElement javaElement, IProject project) {
if (javaElement instanceof IMember) {
IMember member = (IMember) javaElement;
if (member.getTypeRoot()
instanceof ICompilationUnit) {
IType javaType = null;
if (member instanceof IType) {
javaType = (IType) member;
} else {
IJavaElement parent = member.getParent();
while (parent instanceof IMember) {
if (parent instanceof IType) {
javaType = (IType) parent;
break;
}
parent = parent.getParent();
}
}
if (javaType != null) {
JDTModelLoader modelLoader =
CeylonBuilder.getProjectModelLoader(
project);
if (modelLoader != null) {
IJavaModelAware javaUnit =
CeylonBuilder.getUnit(
javaType);
if (javaUnit != null) {
JDTModule module =
javaUnit.getModule();
if (module != null) {
return modelLoader.convertToDeclaration(
module,
javaType.getFullyQualifiedName('.'),
DeclarationType.TYPE);
}
}
}
}
}
}
return null;
}
}
| plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/util/JavaSearch.java | package com.redhat.ceylon.eclipse.util;
import static com.redhat.ceylon.compiler.java.codegen.CodegenUtil.getJavaNameOfDeclaration;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.getCeylonClassesOutputFolder;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.getProjectTypeChecker;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.isExplodeModulesEnabled;
import static com.redhat.ceylon.model.loader.AbstractModelLoader.CEYLON_ATTRIBUTE_ANNOTATION;
import static com.redhat.ceylon.model.loader.AbstractModelLoader.CEYLON_CEYLON_ANNOTATION;
import static com.redhat.ceylon.model.loader.AbstractModelLoader.CEYLON_LOCAL_DECLARATION_ANNOTATION;
import static com.redhat.ceylon.model.loader.AbstractModelLoader.CEYLON_METHOD_ANNOTATION;
import static com.redhat.ceylon.model.loader.AbstractModelLoader.CEYLON_NAME_ANNOTATION;
import static com.redhat.ceylon.model.loader.AbstractModelLoader.CEYLON_OBJECT_ANNOTATION;
import static org.eclipse.jdt.core.IJavaElement.PACKAGE_FRAGMENT;
import static org.eclipse.jdt.core.search.IJavaSearchConstants.CLASS_AND_INTERFACE;
import static org.eclipse.jdt.core.search.IJavaSearchConstants.FIELD;
import static org.eclipse.jdt.core.search.IJavaSearchConstants.METHOD;
import static org.eclipse.jdt.core.search.SearchPattern.R_EXACT_MATCH;
import static org.eclipse.jdt.core.search.SearchPattern.createOrPattern;
import static org.eclipse.jdt.core.search.SearchPattern.createPattern;
import static org.eclipse.jdt.internal.core.util.Util.getUnresolvedJavaElement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IAnnotatable;
import org.eclipse.jdt.core.IAnnotation;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.ILocalVariable;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMemberValuePair;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.core.search.SearchPattern;
import org.eclipse.jdt.core.search.SearchRequestor;
import org.eclipse.jdt.internal.compiler.env.IBinaryType;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.core.JavaElement;
import org.eclipse.jdt.internal.corext.util.SearchUtils;
import com.redhat.ceylon.compiler.java.codegen.Naming;
import com.redhat.ceylon.compiler.java.language.AbstractCallable;
import com.redhat.ceylon.compiler.typechecker.TypeChecker;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.eclipse.core.builder.CeylonBuilder;
import com.redhat.ceylon.eclipse.core.builder.CeylonNature;
import com.redhat.ceylon.eclipse.core.model.CeylonBinaryUnit;
import com.redhat.ceylon.eclipse.core.model.CeylonUnit;
import com.redhat.ceylon.eclipse.core.model.IJavaModelAware;
import com.redhat.ceylon.eclipse.core.model.JDTModelLoader;
import com.redhat.ceylon.eclipse.core.model.JDTModelLoader.ActionOnResolvedGeneratedType;
import com.redhat.ceylon.eclipse.core.model.JDTModule;
import com.redhat.ceylon.model.loader.ModelLoader.DeclarationType;
import com.redhat.ceylon.model.loader.NamingBase;
import com.redhat.ceylon.model.loader.NamingBase.Prefix;
import com.redhat.ceylon.model.loader.NamingBase.Suffix;
import com.redhat.ceylon.model.typechecker.model.Declaration;
import com.redhat.ceylon.model.typechecker.model.Function;
import com.redhat.ceylon.model.typechecker.model.ModelUtil;
import com.redhat.ceylon.model.typechecker.model.Module;
import com.redhat.ceylon.model.typechecker.model.Modules;
import com.redhat.ceylon.model.typechecker.model.Package;
import com.redhat.ceylon.model.typechecker.model.Scope;
import com.redhat.ceylon.model.typechecker.model.Specification;
import com.redhat.ceylon.model.typechecker.model.Unit;
import com.redhat.ceylon.model.typechecker.model.Value;
public class JavaSearch {
public static SearchPattern createSearchPattern(
Declaration declaration, int limitTo) {
String pattern;
try {
pattern = getJavaNameOfDeclaration(declaration);
}
catch (IllegalArgumentException iae) {
return null;
}
if (declaration instanceof Function) {
return createPattern(pattern, METHOD,
limitTo, R_EXACT_MATCH);
}
else if (declaration instanceof Value) {
int loc = pattern.lastIndexOf('.') + 1;
if (pattern.substring(loc).startsWith("get")) {
String setter = pattern.substring(0,loc) +
"set" + pattern.substring(loc+3);
SearchPattern getterPattern =
createPattern(pattern, METHOD,
limitTo, R_EXACT_MATCH);
SearchPattern setterPattern =
createPattern(setter, METHOD,
limitTo, R_EXACT_MATCH);
switch (limitTo) {
case IJavaSearchConstants.WRITE_ACCESSES:
return setterPattern;
case IJavaSearchConstants.READ_ACCESSES:
return getterPattern;
default:
return createOrPattern(getterPattern,
setterPattern);
}
}
else {
SearchPattern fieldPattern =
createPattern(pattern, FIELD,
limitTo, R_EXACT_MATCH);
return fieldPattern;
}
}
else {
SearchPattern searchPattern =
createPattern(pattern, CLASS_AND_INTERFACE,
limitTo, R_EXACT_MATCH);
//weirdly, ALL_OCCURRENCES doesn't return all occurrences
/*if (limitTo==IJavaSearchConstants.ALL_OCCURRENCES) {
searchPattern = createOrPattern(createPattern(pattern, CLASS_AND_INTERFACE,
IJavaSearchConstants.IMPLEMENTORS, R_EXACT_MATCH),
searchPattern);
}*/
return searchPattern;
}
}
public static IProject[] getProjectAndReferencingProjects(
IProject project) {
IProject[] referencingProjects =
project.getReferencingProjects();
IProject[] projects =
new IProject[referencingProjects.length+1];
projects[0] = project;
System.arraycopy(referencingProjects, 0,
projects, 1, referencingProjects.length);
return projects;
}
public static IProject[] getProjectAndReferencedProjects(
IProject project) {
try {
IProject[] referencedProjects =
project.getReferencedProjects();
IProject[] projects =
new IProject[referencedProjects.length+1];
projects[0] = project;
System.arraycopy(referencedProjects, 0,
projects, 1, referencedProjects.length);
return projects;
}
catch (Exception e) {
e.printStackTrace();
return new IProject[] { project };
}
}
@SuppressWarnings("deprecation")
public static void runSearch(
IProgressMonitor pm,
SearchEngine searchEngine,
SearchPattern searchPattern,
IProject[] projects,
SearchRequestor requestor)
throws OperationCanceledException {
try {
searchEngine.search(searchPattern,
SearchUtils.getDefaultSearchParticipants(),
SearchEngine.createJavaSearchScope(projects),
requestor, pm);
}
catch (OperationCanceledException oce) {
throw oce;
}
catch (Exception e) {
e.printStackTrace();
}
}
public static String getJavaQualifiedName(IMember dec) {
IPackageFragment packageFragment =
(IPackageFragment)
dec.getAncestor(PACKAGE_FRAGMENT);
IType type =
(IType)
dec.getAncestor(IJavaElement.TYPE);
String qualifier = packageFragment.getElementName();
if (! qualifier.isEmpty()) {
qualifier += '.';
}
String name = dec.getElementName();
if (dec instanceof IMethod && name.equals("get_")) {
return getJavaQualifiedName(type);
}
else if (dec instanceof IType && name.endsWith("_")) {
return qualifier +
name.substring(0, name.length()-1);
}
if (dec instanceof IMethod) {
if (name.startsWith("$")) {
name = name.substring(1);
}
else if (name.startsWith("get") ||
name.startsWith("set")) {
name = Escaping.toInitialLowercase(name.substring(3));
}
}
if (dec!=type) {
String fullyQualifiedTypeName =
type.getFullyQualifiedName();
String[] parts =
fullyQualifiedTypeName.split("\\.");
String typeName =
parts.length == 0 ?
fullyQualifiedTypeName :
parts[parts.length-1];
if (typeName.endsWith(name + "_")) {
return qualifier + name;
}
else {
return qualifier +
typeName + '.' + name;
}
}
else {
return qualifier + name;
}
}
private static boolean isCeylon(IMember element) {
if (element instanceof IAnnotatable) {
IAnnotatable annotatable =
(IAnnotatable) element;
IAnnotation ceylonAnnotation =
annotatable.getAnnotation(
CEYLON_CEYLON_ANNOTATION);
return ceylonAnnotation.exists();
}
return false;
}
private static boolean isCeylonObject(IMember element) {
if (element instanceof IAnnotatable) {
IAnnotatable annotatable = (IAnnotatable) element;
IAnnotation ceylonAnnotation =
annotatable.getAnnotation(
CEYLON_OBJECT_ANNOTATION);
return ceylonAnnotation.exists();
}
return false;
}
private static boolean isCeylonAttribute(IMember element) {
if (element instanceof IAnnotatable) {
IAnnotatable annotatable = (IAnnotatable) element;
IAnnotation ceylonAnnotation =
annotatable.getAnnotation(
CEYLON_ATTRIBUTE_ANNOTATION);
return ceylonAnnotation.exists();
}
return false;
}
private static boolean isCeylonMethod(IMember element) {
if (element instanceof IAnnotatable) {
IAnnotatable annotatable =
(IAnnotatable) element;
IAnnotation ceylonAnnotation =
annotatable.getAnnotation(
CEYLON_METHOD_ANNOTATION);
return ceylonAnnotation.exists();
}
return false;
}
private static String getCeylonNameAnnotationValue(
IMember element) {
if (element instanceof IAnnotatable) {
IAnnotatable annotatable =
(IAnnotatable) element;
IAnnotation nameAnnotation =
annotatable.getAnnotation(
CEYLON_NAME_ANNOTATION);
if (nameAnnotation.exists()) {
try {
for (IMemberValuePair mvp:
nameAnnotation.getMemberValuePairs()) {
if ("value".equals(mvp.getMemberName())) {
Object value = mvp.getValue();
if ((value instanceof String)
&& ! "".equals(value)) {
return (String) value;
}
}
}
} catch (JavaModelException e) {
e.printStackTrace();
}
}
}
return null;
}
private static String getLocalDeclarationQualifier(
IMember element) {
if (element instanceof IAnnotatable) {
IAnnotatable annotatable =
(IAnnotatable) element;
IAnnotation nameAnnotation =
annotatable.getAnnotation(
CEYLON_LOCAL_DECLARATION_ANNOTATION);
if (nameAnnotation.exists()) {
try {
for (IMemberValuePair mvp:
nameAnnotation.getMemberValuePairs()) {
if ("qualifier".equals(mvp.getMemberName())) {
Object value = mvp.getValue();
if ((value instanceof String)
&& ! "".equals(value)) {
return (String) value;
}
}
}
} catch (JavaModelException e) {
e.printStackTrace();
}
}
}
return null;
}
public static class JdtDefaultArgumentMethodSearch
extends DefaultArgumentMethodSearch<IMethod> {
@Override
protected String getMethodName(IMethod method) {
return method.getElementName();
}
@Override
protected boolean isMethodPrivate(IMethod method) {
try {
return (method.getFlags() &
Flags.AccPrivate)
!= 0;
} catch (JavaModelException e) {
e.printStackTrace();
return false;
}
}
@Override
protected List<IMethod> getMethodsOfDeclaringType(
IMethod method, String searchedName) {
IType declaringType = method.getDeclaringType();
if (declaringType == null) {
return Collections.emptyList();
}
List<IMethod> foundMethods = new ArrayList<>();
try {
for (IMethod m: declaringType.getMethods()) {
if (searchedName == null ||
searchedName.equals(
m.getElementName())) {
foundMethods.add(m);
}
}
} catch (JavaModelException e) {
e.printStackTrace();
return Collections.emptyList();
}
return foundMethods;
}
@Override
protected List<String> getParameterNames(IMethod method) {
List<String> paramNames = new ArrayList<>();
try {
for (ILocalVariable param:
method.getParameters()) {
String paramName = null;
IAnnotation nameAnnotation =
param.getAnnotation(
CEYLON_NAME_ANNOTATION);
if (nameAnnotation != null &&
nameAnnotation.exists()) {
IMemberValuePair[] valuePairs =
nameAnnotation.getMemberValuePairs();
if (valuePairs != null &&
valuePairs.length > 0) {
paramName =
(String)
valuePairs[0].getValue();
}
}
if (paramName == null) {
paramName = param.getElementName();
}
paramNames.add(paramName);
}
return Arrays.asList(method.getParameterNames());
} catch (JavaModelException e) {
e.printStackTrace();
return Collections.emptyList();
}
}
}
public static abstract class DefaultArgumentMethodSearch<MethodType> {
public class Result {
public Result(MethodType defaultArgumentMethod,
String defaultArgumentName,
MethodType overloadedMethod,
MethodType implementationMethod) {
this.defaultArgumentMethod = defaultArgumentMethod;
this.defaultArgumentName = defaultArgumentName;
this.overloadedMethod = overloadedMethod;
this.implementationMethod = implementationMethod;
}
public MethodType defaultArgumentMethod;
public String defaultArgumentName;
public MethodType overloadedMethod;
public MethodType implementationMethod;
}
protected abstract String getMethodName(
MethodType method);
protected abstract boolean isMethodPrivate(
MethodType method);
protected abstract List<MethodType> getMethodsOfDeclaringType(
MethodType method, String name);
protected abstract List<String> getParameterNames(
MethodType method);
public Result search(MethodType method) {
String methodName = getMethodName(method);
if (methodName.endsWith(
NamingBase.Suffix.$canonical$.name())) {
return new Result(null, null, null, method);
}
String[] parts = methodName.split("\\$");
if (methodName.startsWith("$") &&
parts.length > 0) {
parts[0] = "$" + parts[0];
}
String searchedMethodName = "";
boolean canBeADefaultArgumentMethod;
if (parts.length == 2 &&
! methodName.endsWith("$")) {
canBeADefaultArgumentMethod = true;
searchedMethodName = parts[0];
if (isMethodPrivate(method)) {
searchedMethodName +=
NamingBase.Suffix.$priv$.name();
}
} else {
canBeADefaultArgumentMethod = false;
searchedMethodName = methodName;
}
MethodType canonicalMethod = null;
List<MethodType> canonicalMethodSearchResult =
getMethodsOfDeclaringType(method,
searchedMethodName +
NamingBase.Suffix.$canonical$.name());
if (canonicalMethodSearchResult != null &&
! canonicalMethodSearchResult.isEmpty()) {
canonicalMethod =
canonicalMethodSearchResult.get(0);
} else {
List<String> defaultArguments =
new ArrayList<>();
List<MethodType> defaultArgumentMethods =
new ArrayList<>();
for (MethodType m:
getMethodsOfDeclaringType(method, null)) {
if (getMethodName(m)
.startsWith(parts[0] + "$")) {
defaultArgumentMethods.add(m);
}
}
if (! defaultArgumentMethods.isEmpty()) {
for (MethodType defaultArgumentMethod:
defaultArgumentMethods) {
String argumentName =
getMethodName(
defaultArgumentMethod)
.substring(parts[0].length() + 1);
if (! argumentName.isEmpty()) {
defaultArguments.add(argumentName);
}
}
}
if (! defaultArguments.isEmpty()) {
List<MethodType> overloadedMethods =
getMethodsOfDeclaringType(method,
parts[0]);
if (overloadedMethods.size() > 1) {
for (MethodType overloadedMethod:
overloadedMethods) {
List<String> argumentNames =
getParameterNames(
overloadedMethod);
if (argumentNames.size()
< defaultArguments.size()) {
continue;
}
if (! argumentNames.containsAll(
defaultArguments)) {
continue;
}
canonicalMethod = overloadedMethod;
break;
}
}
}
}
if (canonicalMethod != null) {
if (canBeADefaultArgumentMethod) {
if (getParameterNames(canonicalMethod)
.contains(parts[1])) {
return new Result(method, parts[1],
null, canonicalMethod);
}
} else {
if (canonicalMethod.equals(method)) {
return new Result(null, null, null,
canonicalMethod);
} else {
return new Result(null, null, method,
canonicalMethod);
}
}
}
return new Result(null, null, null, null);
}
}
/*
* returns null if it's a method with no Ceylon equivalent
* (internal getter of a Ceylon object value)
*/
public static String getCeylonSimpleName(IMember dec) {
String name = dec.getElementName();
String nameAnnotationValue =
getCeylonNameAnnotationValue(dec);
if (nameAnnotationValue != null) {
return nameAnnotationValue;
}
if (dec instanceof IMethod) {
if (name.startsWith(Prefix.$default$.name())) {
name = name.substring(
Prefix.$default$.name()
.length());
} else if (name.equals("get_")) {
boolean isStatic = false;
int parameterCount = 0;
IMethod method = (IMethod) dec;
try {
isStatic =
(method.getFlags() &
Flags.AccStatic)
!= 0;
parameterCount =
method.getParameterNames()
.length;
} catch (JavaModelException e) {
e.printStackTrace();
}
if (isStatic && parameterCount == 0) {
name = null;
}
} else if (name.startsWith("$")) {
name = name.substring(1);
} else if ((name.startsWith("get") ||
name.startsWith("set")) && name.length() > 3) {
StringBuffer newName =
new StringBuffer(Character.toLowerCase(name.charAt(3)));
if (name.length() > 4) {
newName.append(name.substring(4));
}
name = newName.toString();
} else if (name.equals("toString")) {
name = "string";
} else if (name.equals("hashCode")) {
name = "hash";
} else if (name.contains("$")) {
JdtDefaultArgumentMethodSearch.Result searchResult =
new JdtDefaultArgumentMethodSearch()
.search((IMethod)dec);
if (searchResult.defaultArgumentName != null) {
name = searchResult.defaultArgumentName;
}
}
if (name.endsWith(Suffix.$canonical$.name())) {
name = name.substring(0,
name.length() -
Suffix.$canonical$.name().length());
}
if (name.endsWith(Suffix.$priv$.name())) {
name = name.substring(0,
name.length() -
Suffix.$priv$.name().length());
}
} else if (dec instanceof IType) {
IType type = (IType) dec;
if (name.endsWith("_")) {
if (isCeylonObject(type) ||
isCeylonMethod(type)) {
name = name.substring(0, name.length()-1);
}
}
}
return name;
}
public static boolean elementEqualsDeclaration(
IMember typeOrMethod, Declaration declaration) {
// loadAllAnnotations(typeOrMethod); // Uncomment to easily load all annotations while debugging
String javaElementSimpleName =
getCeylonSimpleName(typeOrMethod);
String ceylonDeclarationSimpleName =
declaration.getName();
if (javaElementSimpleName == null) {
return false;
}
if (!javaElementSimpleName.equals(
ceylonDeclarationSimpleName)) {
if ( javaElementSimpleName.isEmpty()) {
try {
if (!(typeOrMethod instanceof IType
&& ((IType)typeOrMethod).isAnonymous()
&& (declaration instanceof Function)
&& ! isCeylonObject(typeOrMethod)
&& AbstractCallable.class.getName()
.equals(((IType) typeOrMethod)
.getSuperclassName()))) {
return false;
}
} catch (JavaModelException e) {
e.printStackTrace();
return false;
}
} else {
return false;
}
}
if (typeOrMethod instanceof IType) {
String localDeclarationQualifier =
getLocalDeclarationQualifier(
typeOrMethod);
if (localDeclarationQualifier != null) {
if (!localDeclarationQualifier.equals(
declaration.getQualifier())) {
return false;
}
}
if (isCeylonObject(typeOrMethod)
&& declaration.isToplevel()
&& !(declaration instanceof Value)) {
return false;
}
}
IMember declaringElement =
getDeclaringElement(typeOrMethod);
if (declaringElement != null) {
declaringElement =
toCeylonDeclarationElement(
declaringElement);
Declaration ceylonContainingDeclaration =
getContainingDeclaration(declaration);
if (ceylonContainingDeclaration != null) {
return elementEqualsDeclaration(
declaringElement,
(Declaration)
ceylonContainingDeclaration);
}
} else {
Scope scope = declaration.getScope();
if (scope instanceof Package) {
String ceylonDeclarationPkgName =
scope.getQualifiedNameString();
IPackageFragment pkgFragment =
(IPackageFragment)
typeOrMethod.getAncestor(
PACKAGE_FRAGMENT);
String pkgFragmentName = pkgFragment != null ?
pkgFragment.getElementName() : null;
return ceylonDeclarationPkgName.equals(
pkgFragmentName);
}
}
return false;
}
public static void loadAllAnnotations(IMember typeOrMethod) {
Map<String, Map<String, Object>> memberAnnotations =
new HashMap<String, Map<String, Object>>();
if (typeOrMethod instanceof IAnnotatable) {
try {
IAnnotatable annotatable =
(IAnnotatable) typeOrMethod;
for (IAnnotation annotation:
annotatable.getAnnotations()) {
String annotationName =
annotation.getElementName();
if (!memberAnnotations.containsKey(
annotationName)) {
memberAnnotations.put(annotationName,
new HashMap<String, Object>());
}
Map<String, Object> annotationMembers =
memberAnnotations.get(
annotationName);
for (IMemberValuePair pair:
annotation.getMemberValuePairs()) {
annotationMembers.put(
pair.getMemberName(),
pair.getValue());
}
}
} catch (JavaModelException e) {
e.printStackTrace();
}
}
Map<String, Map<String, Object>> typeAnnotations =
new HashMap<String, Map<String, Object>>();
if (typeOrMethod instanceof IType) {
IType type = (IType) typeOrMethod;
try {
IAnnotatable annotatable =
(IAnnotatable) type;
for (IAnnotation annotation:
annotatable.getAnnotations()) {
String annotationName =
annotation.getElementName();
if (! typeAnnotations.containsKey(
annotationName)) {
typeAnnotations.put(annotationName,
new HashMap<String, Object>());
}
Map<String, Object> annotationMembers =
typeAnnotations.get(annotationName);
for (IMemberValuePair pair:
annotation.getMemberValuePairs()) {
annotationMembers.put(
pair.getMemberName(),
pair.getValue());
}
}
} catch (JavaModelException e) {
e.printStackTrace();
}
}
}
public static Declaration getContainingDeclaration(
Declaration declaration) {
Declaration ceylonContainingDeclaration = null;
if (declaration == null) {
return null;
}
if (! declaration.isToplevel()) {
Scope scope = declaration.getContainer();
while (!(scope instanceof Package)) {
if (scope instanceof Declaration) {
ceylonContainingDeclaration =
(Declaration) scope;
break;
}
if (scope instanceof Specification) {
Specification specification =
(Specification) scope;
ceylonContainingDeclaration =
specification.getDeclaration();
break;
}
scope = scope.getContainer();
}
}
return ceylonContainingDeclaration;
}
public static IMember getDeclaringElement(IMember typeOrMethod) {
// TODO : also manage the case of local declarations that are
// wrongly top-level (specific retrieval of the parent IMember)
IMember declaringElement = typeOrMethod.getDeclaringType();
if (declaringElement == null) {
if (typeOrMethod instanceof IType) {
IType type = (IType) typeOrMethod;
try {
if (type.isLocal() ||type.isAnonymous() || false) {
final MethodBinding[] enclosingMethodBinding =
new MethodBinding[1];
JDTModelLoader.doOnResolvedGeneratedType(type,
new ActionOnResolvedGeneratedType() {
@Override
public void doWithBinding(IType classModel,
ReferenceBinding classBinding,
IBinaryType binaryType) {
char[] enclosingMethodSignature =
binaryType.getEnclosingMethod();
if (enclosingMethodSignature != null
&& enclosingMethodSignature.length > 0) {
ReferenceBinding enclosingType =
classBinding.enclosingType();
if (enclosingType != null) {
for (MethodBinding method:
enclosingType.methods()) {
if (CharOperation.equals(
CharOperation.concat(
method.selector,
method.signature()),
enclosingMethodSignature)) {
enclosingMethodBinding[0] = method;
break;
}
}
}
}
}
});
if (enclosingMethodBinding[0] != null) {
IMethod enclosingMethod = (IMethod)
getUnresolvedJavaElement(
enclosingMethodBinding[0],
null, null);
if (enclosingMethod != null &&
!enclosingMethod.isResolved()) {
enclosingMethod = (IMethod)
((JavaElement)enclosingMethod)
.resolved(enclosingMethodBinding[0]);
if (enclosingMethod != null) {
declaringElement = enclosingMethod;
}
}
}
}
} catch (JavaModelException e) {
e.printStackTrace();
}
}
} else {
if (typeOrMethod instanceof IMethod) {
IMethod method = (IMethod) typeOrMethod;
String methodName = method.getElementName();
if (declaringElement.getElementName() != null
&& declaringElement.getElementName()
.equals(methodName + "_")
&& isCeylonMethod(declaringElement)) {
IMember declaringElementDeclaringElement =
getDeclaringElement(declaringElement);
return declaringElementDeclaringElement;
} else if (methodName.contains("$")) {
if (declaringElement instanceof IType) {
JdtDefaultArgumentMethodSearch.Result searchResult =
new JdtDefaultArgumentMethodSearch()
.search(method);
if (searchResult.defaultArgumentMethod != null) {
return searchResult.implementationMethod;
}
}
}
}
}
return declaringElement;
}
public static IProject[] getProjectsToSearch(IProject project) {
if (project == null ||
project.getName()
.equals("Ceylon Source Archives")) {
return CeylonBuilder.getProjects()
.toArray(new IProject[0]);
}
else {
return getProjectAndReferencingProjects(project);
}
}
public static IMember toCeylonDeclarationElement(
IMember typeOrMethod) {
if (typeOrMethod instanceof IMethod) {
IMethod method = (IMethod)typeOrMethod;
String methodName = method.getElementName();
if (methodName == null) {
return typeOrMethod;
}
try {
IType parentType = method.getDeclaringType();
if (parentType != null) {
if ("get_".equals(methodName)
&& ((method.getFlags() & Flags.AccStatic) > 0)
&& (isCeylonObject(parentType) ||
isCeylonAttribute(parentType))) {
return toCeylonDeclarationElement(
parentType);
}
if (methodName.equals(
parentType.getElementName())
&& method.isConstructor()
&& isCeylon(parentType)) {
String constructorName =
getCeylonNameAnnotationValue(method);
if (constructorName != null) {
return method;
} else {
return toCeylonDeclarationElement(
parentType);
}
}
if (methodName.equals(Naming.Unfix.$call$.name()) ||
methodName.equals(Naming.Unfix.$calltyped$.name()) ||
methodName.equals(Naming.Unfix.$callvariadic$.name())) {
return toCeylonDeclarationElement(parentType);
}
if (methodName.equals("$evaluate$")) {
return toCeylonDeclarationElement(
getDeclaringElement(parentType));
}
}
} catch (JavaModelException e) {
e.printStackTrace();
}
}
if (typeOrMethod instanceof IType) {
IType type = (IType) typeOrMethod;
String fullyQualifiedTypeName =
type.getFullyQualifiedName();
if (fullyQualifiedTypeName.endsWith("$impl")) {
IType interfaceType = null;
try {
String name =
fullyQualifiedTypeName.substring(0,
fullyQualifiedTypeName.length() - 5);
interfaceType =
type.getJavaProject()
.findType(name,
(IProgressMonitor) null);
} catch (JavaModelException e) {
e.printStackTrace();
}
if (interfaceType != null) {
return toCeylonDeclarationElement(
interfaceType);
}
}
}
return typeOrMethod;
}
public static Declaration toCeylonDeclaration(
IJavaElement javaElement,
List<? extends PhasedUnit> phasedUnits) {
if (! (javaElement instanceof IMember)) {
return null;
}
IMember member = (IMember) javaElement;
IMember declarationElement =
toCeylonDeclarationElement(member);
IProject project =
javaElement.getJavaProject()
.getProject();
Declaration javaSourceTypeDeclaration =
javaSourceElementToTypeDeclaration(
javaElement, project);
if (javaSourceTypeDeclaration != null &&
javaSourceTypeDeclaration.isNative()) {
Declaration headerDeclaration =
ModelUtil.getNativeHeader(
javaSourceTypeDeclaration.getContainer(),
javaSourceTypeDeclaration.getName());
if (headerDeclaration != null) {
if (elementEqualsDeclaration(
declarationElement,
headerDeclaration)) {
return headerDeclaration;
}
Unit nativeHeaderUnit =
headerDeclaration.getUnit();
if (nativeHeaderUnit instanceof CeylonUnit) {
CeylonUnit unit =
(CeylonUnit) nativeHeaderUnit;
PhasedUnit phasedUnit =
unit.getPhasedUnit();
if (phasedUnit != null) {
phasedUnits =
Arrays.asList(phasedUnit);
}
}
}
}
for (PhasedUnit pu: phasedUnits) {
for (Declaration declaration:
pu.getDeclarations()) {
if (elementEqualsDeclaration(
declarationElement, declaration)) {
return declaration;
}
}
}
return null;
}
private static boolean belongsToModule(
IJavaElement javaElement, JDTModule module) {
return javaElement.getAncestor(PACKAGE_FRAGMENT)
.getElementName()
.startsWith(module.getNameAsString());
}
public static Declaration toCeylonDeclaration(
IProject project, IJavaElement javaElement) {
Set<String> searchedArchives = new HashSet<String>();
for (IProject referencedProject:
getProjectAndReferencedProjects(project)) {
if (CeylonNature.isEnabled(referencedProject)) {
TypeChecker typeChecker =
getProjectTypeChecker(referencedProject);
if (typeChecker!=null) {
List<PhasedUnit> phasedUnits =
typeChecker.getPhasedUnits()
.getPhasedUnits();
Declaration result =
toCeylonDeclaration(javaElement,
phasedUnits);
if (result!=null) return result;
Modules modules =
typeChecker.getContext()
.getModules();
for (Module m: modules.getListOfModules()) {
if (m instanceof JDTModule) {
JDTModule module = (JDTModule) m;
if (module.isCeylonArchive() &&
!module.isProjectModule() &&
module.getArtifact()!=null) {
String archivePath =
module.getArtifact()
.getAbsolutePath();
if (searchedArchives.add(archivePath) &&
belongsToModule(javaElement, module)) {
result =
toCeylonDeclaration(
javaElement,
module.getPhasedUnits());
if (result!=null) {
return result;
}
}
}
}
}
}
}
}
return null;
}
public static boolean isCeylonDeclaration(
IJavaElement javaElement) {
IProject project =
javaElement.getJavaProject()
.getProject();
IJavaModelAware unit =
CeylonBuilder.getUnit(javaElement);
IPath path = javaElement.getPath();
if (path!=null) {
if (unit instanceof CeylonBinaryUnit ||
(isExplodeModulesEnabled(project)
&& getCeylonClassesOutputFolder(project)
.getFullPath().isPrefixOf(path))) {
return true;
}
Declaration decl =
javaSourceElementToTypeDeclaration(
javaElement, project);
if (decl != null) {
return true;
}
}
return false;
}
private static Declaration javaSourceElementToTypeDeclaration(
IJavaElement javaElement, IProject project) {
if (javaElement instanceof IMember) {
IMember member = (IMember) javaElement;
if (member.getTypeRoot()
instanceof ICompilationUnit) {
IType javaType = null;
if (member instanceof IType) {
javaType = (IType) member;
} else {
IJavaElement parent = member.getParent();
while (parent instanceof IMember) {
if (parent instanceof IType) {
javaType = (IType) parent;
break;
}
parent = parent.getParent();
}
}
if (javaType != null) {
JDTModelLoader modelLoader =
CeylonBuilder.getProjectModelLoader(
project);
if (modelLoader != null) {
IJavaModelAware javaUnit =
CeylonBuilder.getUnit(
javaType);
if (javaUnit != null) {
JDTModule module =
javaUnit.getModule();
if (module != null) {
return modelLoader.convertToDeclaration(
module,
javaType.getFullyQualifiedName('.'),
DeclarationType.TYPE);
}
}
}
}
}
}
return null;
}
}
| minor changes | plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/util/JavaSearch.java | minor changes |
|
Java | mpl-2.0 | cb5b5e7e8efd56fafb51fbc76b53b49a126b7514 | 0 | hserv/coordinated-entry,hserv/coordinated-entry | package com.servinglynk.hmis.warehouse.service.converter;
import java.time.ZoneId;
import java.util.Date;
import com.servinglynk.hmis.warehouse.core.model.Client;
import com.servinglynk.hmis.warehouse.core.model.Response;
import com.servinglynk.hmis.warehouse.model.ClientEntity;
import com.servinglynk.hmis.warehouse.model.QuestionEntity;
import com.servinglynk.hmis.warehouse.model.ResponseEntity;
public class ResponseConverterV3 {
public static ResponseEntity modelToEntity (Response model ,ResponseEntity entity) {
if(entity==null) entity = new ResponseEntity();
entity.setId(model.getResponseId());
entity.setRefused(model.isRefused());
entity.setResponseText(model.getResponseText());
entity.setAppId(model.getAppId());
entity.setEffectiveDate(model.getEffectiveDate());
if(model.getDedupClientId()!=null) entity.setDedupClientId(model.getDedupClientId());
// entity.setClientId(model.getClientId());
return entity;
}
public static Response entityToModel (ResponseEntity entity, ClientEntity clientEntity) {
Response model = new Response();
model.setResponseId(entity.getId());
model.setRefused(entity.isRefused());
model.setResponseText(entity.getResponseText());
QuestionEntity questionEntity = entity.getQuestionEntity();
if(questionEntity != null) {
model.setQuestionId(questionEntity.getId());
}
model.setQuestionScore(entity.getQuestionScore());
model.setAppId(entity.getAppId());
if(entity.getSurveySectionEntity()!=null) model.setSectionId(entity.getSurveySectionEntity().getId());
if(entity.getQuestionEntity()!=null) model.setQuestionId(entity.getQuestionEntity().getId());
model.setClientId(clientEntity.getId());
model.setSurveyId(entity.getSurveyEntity().getId());
model.setSubmissionId(entity.getSubmissionId());
model.setEffectiveDate(entity.getEffectiveDate());
model.setDedupClientId(entity.getDedupClientId());
return model;
}
public static Response entityToModelDetail (ResponseEntity entity, ClientEntity clientEntity) {
Response model = new Response();
model.setResponseId(entity.getId());
model.setRefused(entity.isRefused());
model.setResponseText(entity.getResponseText());
model.setQuestionScore(entity.getQuestionScore());
model.setAppId(entity.getAppId());
if(entity.getSurveySectionEntity()!=null) model.setSectionId(entity.getSurveySectionEntity().getId());
if(entity.getQuestionEntity()!=null) model.setQuestionId(entity.getQuestionEntity().getId());
model.setClientId(clientEntity.getId());
model.setSurveyId(entity.getSurveyEntity().getId());
model.setSubmissionId(entity.getSubmissionId());
model.setEffectiveDate(entity.getEffectiveDate());
model.setDedupClientId(clientEntity.getDedupClientId());
if(entity.getClient()!=null) {
Client client = new Client();
if(clientEntity.getDob()!=null) client.setDob(Date.from(clientEntity.getDob().atZone(ZoneId.systemDefault()).toInstant()));
client.setEmailAddress(clientEntity.getEmailAddress());
client.setFirstName(clientEntity.getFirstName());
client.setLastName(clientEntity.getLastName());
client.setMiddleName(clientEntity.getMiddleName());
client.setPhoneNumber(clientEntity.getPhoneNumber());
client.setId(clientEntity.getId());
model.setClient(client);
}
return model;
}
}
| hmis-survey-api/src/main/java/com/servinglynk/hmis/warehouse/service/converter/ResponseConverterV3.java | package com.servinglynk.hmis.warehouse.service.converter;
import java.time.ZoneId;
import java.util.Date;
import com.servinglynk.hmis.warehouse.core.model.Client;
import com.servinglynk.hmis.warehouse.core.model.Response;
import com.servinglynk.hmis.warehouse.model.ClientEntity;
import com.servinglynk.hmis.warehouse.model.ResponseEntity;
public class ResponseConverterV3 {
public static ResponseEntity modelToEntity (Response model ,ResponseEntity entity) {
if(entity==null) entity = new ResponseEntity();
entity.setId(model.getResponseId());
entity.setRefused(model.isRefused());
entity.setResponseText(model.getResponseText());
entity.setAppId(model.getAppId());
entity.setEffectiveDate(model.getEffectiveDate());
if(model.getDedupClientId()!=null) entity.setDedupClientId(model.getDedupClientId());
// entity.setClientId(model.getClientId());
return entity;
}
public static Response entityToModel (ResponseEntity entity, ClientEntity clientEntity) {
Response model = new Response();
model.setResponseId(entity.getId());
model.setRefused(entity.isRefused());
model.setResponseText(entity.getResponseText());
model.setQuestionScore(entity.getQuestionScore());
model.setAppId(entity.getAppId());
if(entity.getSurveySectionEntity()!=null) model.setSectionId(entity.getSurveySectionEntity().getId());
if(entity.getQuestionEntity()!=null) model.setQuestionId(entity.getQuestionEntity().getId());
model.setClientId(clientEntity.getId());
model.setSurveyId(entity.getSurveyEntity().getId());
model.setSubmissionId(entity.getSubmissionId());
model.setEffectiveDate(entity.getEffectiveDate());
model.setDedupClientId(entity.getDedupClientId());
return model;
}
public static Response entityToModelDetail (ResponseEntity entity, ClientEntity clientEntity) {
Response model = new Response();
model.setResponseId(entity.getId());
model.setRefused(entity.isRefused());
model.setResponseText(entity.getResponseText());
model.setQuestionScore(entity.getQuestionScore());
model.setAppId(entity.getAppId());
if(entity.getSurveySectionEntity()!=null) model.setSectionId(entity.getSurveySectionEntity().getId());
if(entity.getQuestionEntity()!=null) model.setQuestionId(entity.getQuestionEntity().getId());
model.setClientId(clientEntity.getId());
model.setSurveyId(entity.getSurveyEntity().getId());
model.setSubmissionId(entity.getSubmissionId());
model.setEffectiveDate(entity.getEffectiveDate());
model.setDedupClientId(clientEntity.getDedupClientId());
if(entity.getClient()!=null) {
Client client = new Client();
if(clientEntity.getDob()!=null) client.setDob(Date.from(clientEntity.getDob().atZone(ZoneId.systemDefault()).toInstant()));
client.setEmailAddress(clientEntity.getEmailAddress());
client.setFirstName(clientEntity.getFirstName());
client.setLastName(clientEntity.getLastName());
client.setMiddleName(clientEntity.getMiddleName());
client.setPhoneNumber(clientEntity.getPhoneNumber());
client.setId(clientEntity.getId());
model.setClient(client);
}
return model;
}
}
| Fix API/v3/clients/{dedupclientid}/surveys/{surveyid}/submissions/{submissionid} to return questionId
| hmis-survey-api/src/main/java/com/servinglynk/hmis/warehouse/service/converter/ResponseConverterV3.java | Fix API/v3/clients/{dedupclientid}/surveys/{surveyid}/submissions/{submissionid} to return questionId |
|
Java | agpl-3.0 | 9914d288acae5d13d1d2aa1b0ba7473f6719328f | 0 | jrochas/scale-proactive,lpellegr/programming,paraita/programming,PaulKh/scale-proactive,ow2-proactive/programming,mnip91/proactive-component-monitoring,mnip91/programming-multiactivities,mnip91/programming-multiactivities,PaulKh/scale-proactive,ow2-proactive/programming,mnip91/proactive-component-monitoring,mnip91/proactive-component-monitoring,paraita/programming,lpellegr/programming,ow2-proactive/programming,paraita/programming,mnip91/proactive-component-monitoring,jrochas/scale-proactive,mnip91/proactive-component-monitoring,mnip91/programming-multiactivities,acontes/programming,ow2-proactive/programming,paraita/programming,acontes/programming,mnip91/programming-multiactivities,PaulKh/scale-proactive,jrochas/scale-proactive,paraita/programming,acontes/programming,fviale/programming,lpellegr/programming,mnip91/proactive-component-monitoring,lpellegr/programming,ow2-proactive/programming,mnip91/programming-multiactivities,jrochas/scale-proactive,PaulKh/scale-proactive,acontes/programming,paraita/programming,fviale/programming,acontes/programming,ow2-proactive/programming,fviale/programming,jrochas/scale-proactive,PaulKh/scale-proactive,fviale/programming,PaulKh/scale-proactive,lpellegr/programming,fviale/programming,mnip91/programming-multiactivities,acontes/programming,lpellegr/programming,fviale/programming,PaulKh/scale-proactive,acontes/programming,jrochas/scale-proactive,jrochas/scale-proactive | /*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2008 INRIA/University of Nice-Sophia Antipolis
* Contact: [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or 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
* General Public License for more details.
*
* You should have received a copy of the GNU 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
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.objectweb.proactive.core;
import org.apache.log4j.Logger;
import org.objectweb.proactive.annotation.PublicAPI;
import org.objectweb.proactive.core.util.log.Loggers;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
/**
* <p>
* UniqueID is a unique object identifier across all jvm. It is made of a unique VMID combined
* with a unique UID on that VM.
* </p><p>
* The UniqueID is used to identify object globally, even in case of migration.
* </p>
* @author The ProActive Team
* @version 1.0, 2001/10/23
* @since ProActive 0.9
*
*/
@PublicAPI
public class UniqueID implements java.io.Serializable, Comparable<UniqueID> {
private java.rmi.server.UID id;
private java.rmi.dgc.VMID vmID;
//the Unique ID of the JVM
private static java.rmi.dgc.VMID uniqueVMID = new java.rmi.dgc.VMID();
final protected static Logger logger = ProActiveLogger.getLogger(Loggers.CORE);
// Optim
private transient String cachedShortString;
private transient String cachedCanonString;
//
// -- CONSTRUCTORS -----------------------------------------------
//
/**
* Creates a new UniqueID
*/
public UniqueID() {
this.id = new java.rmi.server.UID();
this.vmID = uniqueVMID;
}
//
// -- PUBLIC STATIC METHODS -----------------------------------------------
//
/**
* Returns the VMID of the current VM in which this class has been loaded.
* @return the VMID of the current VM
*/
public static java.rmi.dgc.VMID getCurrentVMID() {
return uniqueVMID;
}
//
// -- PUBLIC METHODS -----------------------------------------------
//
/**
* Returns the VMID of this UniqueID. Note that the VMID of one UniqueID may differ
* from the local VMID (that one can get using <code>getCurrentVMID()</code> in case
* this UniqueID is attached to an object that has migrated.
* @return the VMID part of this UniqueID
*/
public java.rmi.dgc.VMID getVMID() {
return this.vmID;
}
/**
* Returns the UID part of this UniqueID.
* @return the UID part of this UniqueID
*/
public java.rmi.server.UID getUID() {
return this.id;
}
/**
* Returns a string representation of this UniqueID.
* @return a string representation of this UniqueID
*/
@Override
public String toString() {
if (logger.isDebugEnabled()) {
return shortString();
} else {
return getCanonString();
}
}
public String shortString() {
if (this.cachedShortString == null) {
this.cachedShortString = "" + Math.abs(this.getCanonString().hashCode() % 100000);
}
return this.cachedShortString;
}
public String getCanonString() {
if (this.cachedCanonString == null) {
this.cachedCanonString = ("" + this.id + "--" + this.vmID).replace(':', '-');
}
return this.cachedCanonString;
}
public int compareTo(UniqueID u) {
return getCanonString().compareTo(u.getCanonString());
}
/**
* Overrides hashCode to take into account the two part of this UniqueID.
* @return the hashcode of this object
*/
@Override
public int hashCode() {
return this.id.hashCode() + this.vmID.hashCode();
}
/**
* Overrides equals to take into account the two part of this UniqueID.
* @return the true if and only if o is an UniqueID equals to this UniqueID
*/
@Override
public boolean equals(Object o) {
//System.out.println("Now checking for equality");
if (o instanceof UniqueID) {
return ((this.id.equals(((UniqueID) o).getUID())) && (this.vmID.equals(((UniqueID) o).getVMID())));
} else {
return false;
}
}
/**
* for debug purpose
*/
public void echo() {
logger.info("UniqueID The Id is " + this.id + " and the address is " + this.vmID);
}
}
| src/Core/org/objectweb/proactive/core/UniqueID.java | /*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2008 INRIA/University of Nice-Sophia Antipolis
* Contact: [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or 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
* General Public License for more details.
*
* You should have received a copy of the GNU 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
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.objectweb.proactive.core;
import org.apache.log4j.Logger;
import org.objectweb.proactive.annotation.PublicAPI;
import org.objectweb.proactive.core.util.log.Loggers;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
/**
* <p>
* UniqueID is a unique object identifier across all jvm. It is made of a unique VMID combined
* with a unique UID on that VM.
* </p><p>
* The UniqueID is used to identify object globally, even in case of migration.
* </p>
* @author The ProActive Team
* @version 1.0, 2001/10/23
* @since ProActive 0.9
*
*/
@PublicAPI
public class UniqueID implements java.io.Serializable, Comparable<UniqueID> {
private java.rmi.server.UID id;
private java.rmi.dgc.VMID vmID;
//the Unique ID of the JVM
private static java.rmi.dgc.VMID uniqueVMID = new java.rmi.dgc.VMID();
final protected static Logger logger = ProActiveLogger.getLogger(Loggers.CORE);
// Optim
private transient String cachedShortString;
private transient String cachedCanonString;
//
// -- CONSTRUCTORS -----------------------------------------------
//
/**
* Creates a new UniqueID
*/
public UniqueID() {
this.id = new java.rmi.server.UID();
this.vmID = uniqueVMID;
}
//
// -- PUBLIC STATIC METHODS -----------------------------------------------
//
/**
* Returns the VMID of the current VM in which this class has been loaded.
* @return the VMID of the current VM
*/
public static java.rmi.dgc.VMID getCurrentVMID() {
return uniqueVMID;
}
//
// -- PUBLIC METHODS -----------------------------------------------
//
/**
* Returns the VMID of this UniqueID. Note that the VMID of one UniqueID may differ
* from the local VMID (that one can get using <code>getCurrentVMID()</code> in case
* this UniqueID is attached to an object that has migrated.
* @return the VMID part of this UniqueID
*/
public java.rmi.dgc.VMID getVMID() {
return this.vmID;
}
/**
* Returns the UID part of this UniqueID.
* @return the UID part of this UniqueID
*/
public java.rmi.server.UID getUID() {
return this.id;
}
/**
* Returns a string representation of this UniqueID.
* @return a string representation of this UniqueID
*/
@Override
public String toString() {
if (logger.isDebugEnabled()) {
return shortString();
} else {
return getCanonString();
}
}
public String shortString() {
if (this.cachedShortString == null) {
this.cachedShortString = "" + Math.abs(this.getCanonString().hashCode() % 100000);
}
return this.cachedShortString;
}
public String getCanonString() {
if (this.cachedCanonString == null) {
this.cachedCanonString = ("" + this.id + "--" + this.vmID).replace(':', '-');
}
return this.cachedCanonString;
}
public int compareTo(UniqueID u) {
return getCanonString().compareTo(u.getCanonString());
}
/**
* Overrides hashCode to take into account the two part of this UniqueID.
* @return the hashcode of this object
*/
@Override
public int hashCode() {
return this.id.hashCode() + this.vmID.hashCode();
}
/**
* Overrides equals to take into account the two part of this UniqueID.
* @return the true if and only if o is an UniqueID equals to this UniqueID
*/
@Override
public boolean equals(Object o) {
//System.out.println("Now checking for equality");
if (o instanceof UniqueID) {
return ((this.id.equals(((UniqueID) o).id)) && (this.vmID.equals(((UniqueID) o).vmID)));
} else {
return false;
}
}
/**
* for debug purpose
*/
public void echo() {
logger.info("UniqueID The Id is " + this.id + " and the address is " + this.vmID);
}
}
| Fix for PROACTIVE-545
git-svn-id: 9146c88ff6d39b48099bf954d15d68f687b3fa69@10633 28e8926c-6b08-0410-baaa-805c5e19b8d6
| src/Core/org/objectweb/proactive/core/UniqueID.java | Fix for PROACTIVE-545 |
|
Java | agpl-3.0 | d358ed81d2295d0fa1c0dbe091242a9229e219ce | 0 | Freeyourgadget/Gadgetbridge,ivanovlev/Gadgetbridge,Freeyourgadget/Gadgetbridge,rosenpin/Gadgetbridge,roidelapluie/Gadgetbridge,rosenpin/Gadgetbridge,ivanovlev/Gadgetbridge,roidelapluie/Gadgetbridge,rosenpin/Gadgetbridge,roidelapluie/Gadgetbridge,ivanovlev/Gadgetbridge,Freeyourgadget/Gadgetbridge,Freeyourgadget/Gadgetbridge | package nodomain.freeyourgadget.gadgetbridge.service.devices.pebble;
import android.util.Base64;
import android.util.Pair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.SimpleTimeZone;
import java.util.UUID;
import nodomain.freeyourgadget.gadgetbridge.GBApplication;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEvent;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventAppInfo;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventAppManagement;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventAppMessage;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventCallControl;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventMusicControl;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventNotificationControl;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventScreenshot;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventSendBytes;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventVersionInfo;
import nodomain.freeyourgadget.gadgetbridge.devices.pebble.PebbleColor;
import nodomain.freeyourgadget.gadgetbridge.devices.pebble.PebbleIconID;
import nodomain.freeyourgadget.gadgetbridge.impl.GBDeviceApp;
import nodomain.freeyourgadget.gadgetbridge.model.NotificationSpec;
import nodomain.freeyourgadget.gadgetbridge.model.NotificationType;
import nodomain.freeyourgadget.gadgetbridge.model.ServiceCommand;
import nodomain.freeyourgadget.gadgetbridge.service.serial.GBDeviceProtocol;
public class PebbleProtocol extends GBDeviceProtocol {
private static final Logger LOG = LoggerFactory.getLogger(PebbleProtocol.class);
static final short ENDPOINT_TIME = 11;
static final short ENDPOINT_FIRMWAREVERSION = 16;
public static final short ENDPOINT_PHONEVERSION = 17;
static final short ENDPOINT_SYSTEMMESSAGE = 18;
static final short ENDPOINT_MUSICCONTROL = 32;
static final short ENDPOINT_PHONECONTROL = 33;
static final short ENDPOINT_APPLICATIONMESSAGE = 48;
static final short ENDPOINT_LAUNCHER = 49;
static final short ENDPOINT_APPRUNSTATE = 52; // 3.x only
static final short ENDPOINT_LOGS = 2000;
static final short ENDPOINT_PING = 2001;
static final short ENDPOINT_LOGDUMP = 2002;
static final short ENDPOINT_RESET = 2003;
static final short ENDPOINT_APP = 2004;
static final short ENDPOINT_APPLOGS = 2006;
static final short ENDPOINT_NOTIFICATION = 3000;
static final short ENDPOINT_EXTENSIBLENOTIFS = 3010;
static final short ENDPOINT_RESOURCE = 4000;
static final short ENDPOINT_SYSREG = 5000;
static final short ENDPOINT_FCTREG = 5001;
static final short ENDPOINT_APPMANAGER = 6000;
static final short ENDPOINT_APPFETCH = 6001; // 3.x only
public static final short ENDPOINT_DATALOG = 6778;
static final short ENDPOINT_RUNKEEPER = 7000;
static final short ENDPOINT_SCREENSHOT = 8000;
static final short ENDPOINT_NOTIFICATIONACTION = 11440; // 3.x only, TODO: find a better name
static final short ENDPOINT_BLOBDB = (short) 45531; // 3.x only
static final short ENDPOINT_PUTBYTES = (short) 48879;
static final byte APPRUNSTATE_START = 1;
static final byte APPRUNSTATE_STOP = 2;
static final byte BLOBDB_INSERT = 1;
static final byte BLOBDB_DELETE = 4;
static final byte BLOBDB_CLEAR = 5;
static final byte BLOBDB_PIN = 1;
static final byte BLOBDB_APP = 2;
static final byte BLOBDB_REMINDER = 3;
static final byte BLOBDB_NOTIFICATION = 4;
static final byte BLOBDB_SUCCESS = 1;
static final byte BLOBDB_GENERALFAILURE = 2;
static final byte BLOBDB_INVALIDOPERATION = 3;
static final byte BLOBDB_INVALIDDATABASEID = 4;
static final byte BLOBDB_INVALIDDATA = 5;
static final byte BLOBDB_KEYDOESNOTEXIST = 6;
static final byte BLOBDB_DATABASEFULL = 7;
static final byte BLOBDB_DATASTALE = 8;
// This is not in the Pebble protocol
static final byte NOTIFICATION_UNDEFINED = -1;
static final byte NOTIFICATION_EMAIL = 0;
static final byte NOTIFICATION_SMS = 1;
static final byte NOTIFICATION_TWITTER = 2;
static final byte NOTIFICATION_FACEBOOK = 3;
static final byte PHONECONTROL_ANSWER = 1;
static final byte PHONECONTROL_HANGUP = 2;
static final byte PHONECONTROL_GETSTATE = 3;
static final byte PHONECONTROL_INCOMINGCALL = 4;
static final byte PHONECONTROL_OUTGOINGCALL = 5;
static final byte PHONECONTROL_MISSEDCALL = 6;
static final byte PHONECONTROL_RING = 7;
static final byte PHONECONTROL_START = 8;
static final byte PHONECONTROL_END = 9;
static final byte MUSICCONTROL_SETMUSICINFO = 16;
static final byte MUSICCONTROL_PLAYPAUSE = 1;
static final byte MUSICCONTROL_PAUSE = 2;
static final byte MUSICCONTROL_PLAY = 3;
static final byte MUSICCONTROL_NEXT = 4;
static final byte MUSICCONTROL_PREVIOUS = 5;
static final byte MUSICCONTROL_VOLUMEUP = 6;
static final byte MUSICCONTROL_VOLUMEDOWN = 7;
static final byte MUSICCONTROL_GETNOWPLAYING = 7;
static final byte NOTIFICATIONACTION_ACK = 0;
static final byte NOTIFICATIONACTION_NACK = 1;
static final byte NOTIFICATIONACTION_INVOKE = 0x02;
static final byte NOTIFICATIONACTION_RESPONSE = 0x11;
static final byte TIME_GETTIME = 0;
static final byte TIME_SETTIME = 2;
static final byte TIME_SETTIME_UTC = 3;
static final byte FIRMWAREVERSION_GETVERSION = 0;
static final byte APPMANAGER_GETAPPBANKSTATUS = 1;
static final byte APPMANAGER_REMOVEAPP = 2;
static final byte APPMANAGER_REFRESHAPP = 3;
static final byte APPMANAGER_GETUUIDS = 5;
static final int APPMANAGER_RES_SUCCESS = 1;
static final byte APPLICATIONMESSAGE_PUSH = 1;
static final byte APPLICATIONMESSAGE_REQUEST = 2;
static final byte APPLICATIONMESSAGE_ACK = (byte) 0xff;
static final byte APPLICATIONMESSAGE_NACK = (byte) 0x7f;
static final byte DATALOG_OPENSESSION = 0x01;
static final byte DATALOG_SENDDATA = 0x02;
static final byte DATALOG_CLOSE = 0x03;
static final byte DATALOG_TIMEOUT = 0x07;
static final byte DATALOG_REPORTSESSIONS = (byte) 0x84;
static final byte DATALOG_ACK = (byte) 0x85;
static final byte DATALOG_NACK = (byte) 0x86;
static final byte PING_PING = 0;
static final byte PING_PONG = 1;
static final byte PUTBYTES_INIT = 1;
static final byte PUTBYTES_SEND = 2;
static final byte PUTBYTES_COMMIT = 3;
static final byte PUTBYTES_ABORT = 4;
static final byte PUTBYTES_COMPLETE = 5;
public static final byte PUTBYTES_TYPE_FIRMWARE = 1;
public static final byte PUTBYTES_TYPE_RECOVERY = 2;
public static final byte PUTBYTES_TYPE_SYSRESOURCES = 3;
public static final byte PUTBYTES_TYPE_RESOURCES = 4;
public static final byte PUTBYTES_TYPE_BINARY = 5;
public static final byte PUTBYTES_TYPE_FILE = 6;
public static final byte PUTBYTES_TYPE_WORKER = 7;
static final byte RESET_REBOOT = 0;
static final byte SCREENSHOT_TAKE = 0;
static final byte SYSTEMMESSAGE_NEWFIRMWAREAVAILABLE = 0;
static final byte SYSTEMMESSAGE_FIRMWARESTART = 1;
static final byte SYSTEMMESSAGE_FIRMWARECOMPLETE = 2;
static final byte SYSTEMMESSAGE_FIRMWAREFAIL = 3;
static final byte SYSTEMMESSAGE_FIRMWARE_UPTODATE = 4;
static final byte SYSTEMMESSAGE_FIRMWARE_OUTOFDATE = 5;
static final byte SYSTEMMESSAGE_STOPRECONNECTING = 6;
static final byte SYSTEMMESSAGE_STARTRECONNECTING = 7;
static final byte PHONEVERSION_REQUEST = 0;
static final byte PHONEVERSION_APPVERSION_MAGIC = 2; // increase this if pebble complains
static final byte PHONEVERSION_APPVERSION_MAJOR = 2;
static final byte PHONEVERSION_APPVERSION_MINOR = 3;
static final byte PHONEVERSION_APPVERSION_PATCH = 0;
static final int PHONEVERSION_SESSION_CAPS_GAMMARAY = 0x80000000;
static final int PHONEVERSION_REMOTE_CAPS_TELEPHONY = 0x00000010;
static final int PHONEVERSION_REMOTE_CAPS_SMS = 0x00000020;
static final int PHONEVERSION_REMOTE_CAPS_GPS = 0x00000040;
static final int PHONEVERSION_REMOTE_CAPS_BTLE = 0x00000080;
static final int PHONEVERSION_REMOTE_CAPS_REARCAMERA = 0x00000100;
static final int PHONEVERSION_REMOTE_CAPS_ACCEL = 0x00000200;
static final int PHONEVERSION_REMOTE_CAPS_GYRO = 0x00000400;
static final int PHONEVERSION_REMOTE_CAPS_COMPASS = 0x00000800;
static final byte PHONEVERSION_REMOTE_OS_UNKNOWN = 0;
static final byte PHONEVERSION_REMOTE_OS_IOS = 1;
static final byte PHONEVERSION_REMOTE_OS_ANDROID = 2;
static final byte PHONEVERSION_REMOTE_OS_OSX = 3;
static final byte PHONEVERSION_REMOTE_OS_LINUX = 4;
static final byte PHONEVERSION_REMOTE_OS_WINDOWS = 5;
static final byte TYPE_BYTEARRAY = 0;
static final byte TYPE_CSTRING = 1;
static final byte TYPE_UINT = 2;
static final byte TYPE_INT = 3;
static final short LENGTH_PREFIX = 4;
static final short LENGTH_SIMPLEMESSAGE = 1;
static final short LENGTH_APPFETCH = 2;
static final short LENGTH_APPRUNSTATE = 17;
static final short LENGTH_BLOBDB = 21;
static final short LENGTH_PING = 5;
static final short LENGTH_PHONEVERSION = 17;
static final short LENGTH_REMOVEAPP_2X = 17;
static final short LENGTH_REFRESHAPP = 5;
static final short LENGTH_SETTIME = 5;
static final short LENGTH_SYSTEMMESSAGE = 2;
static final short LENGTH_UPLOADSTART_2X = 7;
static final short LENGTH_UPLOADSTART_3X = 10;
static final short LENGTH_UPLOADCHUNK = 9;
static final short LENGTH_UPLOADCOMMIT = 9;
static final short LENGTH_UPLOADCOMPLETE = 5;
static final short LENGTH_UPLOADCANCEL = 5;
static final byte LENGTH_UUID = 16;
// base is -5
private static final String[] hwRevisions = {
// Emulator
"spalding_bb2", "snowy_bb2", "snowy_bb", "bb2", "bb",
"unknown",
// Pebble
"ev1", "ev2", "ev2_3", "ev2_4", "v1_5", "v2_0",
// Pebble Time
"snowy_evt2", "snowy_dvt", "spalding_dvt", "snowy_s3", "spalding"
};
private static final Random mRandom = new Random();
boolean isFw3x = false;
boolean mForceProtocol = false;
GBDeviceEventScreenshot mDevEventScreenshot = null;
int mScreenshotRemaining = -1;
//monochrome black + white
static final byte[] clut_pebble = {
0x00, 0x00, 0x00, 0x00,
(byte) 0xff, (byte) 0xff, (byte) 0xff, 0x00
};
// linear BGR222 (6 bit, 64 entries)
static final byte[] clut_pebbletime = new byte[]{
0x00, 0x00, 0x00, 0x00,
0x55, 0x00, 0x00, 0x00,
(byte) 0xaa, 0x00, 0x00, 0x00,
(byte) 0xff, 0x00, 0x00, 0x00,
0x00, 0x55, 0x00, 0x00,
0x55, 0x55, 0x00, 0x00,
(byte) 0xaa, 0x55, 0x00, 0x00,
(byte) 0xff, 0x55, 0x00, 0x00,
0x00, (byte) 0xaa, 0x00, 0x00,
0x55, (byte) 0xaa, 0x00, 0x00,
(byte) 0xaa, (byte) 0xaa, 0x00, 0x00,
(byte) 0xff, (byte) 0xaa, 0x00, 0x00,
0x00, (byte) 0xff, 0x00, 0x00,
0x55, (byte) 0xff, 0x00, 0x00,
(byte) 0xaa, (byte) 0xff, 0x00, 0x00,
(byte) 0xff, (byte) 0xff, 0x00, 0x00,
0x00, 0x00, 0x55, 0x00,
0x55, 0x00, 0x55, 0x00,
(byte) 0xaa, 0x00, 0x55, 0x00,
(byte) 0xff, 0x00, 0x55, 0x00,
0x00, 0x55, 0x55, 0x00,
0x55, 0x55, 0x55, 0x00,
(byte) 0xaa, 0x55, 0x55, 0x00,
(byte) 0xff, 0x55, 0x55, 0x00,
0x00, (byte) 0xaa, 0x55, 0x00,
0x55, (byte) 0xaa, 0x55, 0x00,
(byte) 0xaa, (byte) 0xaa, 0x55, 0x00,
(byte) 0xff, (byte) 0xaa, 0x55, 0x00,
0x00, (byte) 0xff, 0x55, 0x00,
0x55, (byte) 0xff, 0x55, 0x00,
(byte) 0xaa, (byte) 0xff, 0x55, 0x00,
(byte) 0xff, (byte) 0xff, 0x55, 0x00,
0x00, 0x00, (byte) 0xaa, 0x00,
0x55, 0x00, (byte) 0xaa, 0x00,
(byte) 0xaa, 0x00, (byte) 0xaa, 0x00,
(byte) 0xff, 0x00, (byte) 0xaa, 0x00,
0x00, 0x55, (byte) 0xaa, 0x00,
0x55, 0x55, (byte) 0xaa, 0x00,
(byte) 0xaa, 0x55, (byte) 0xaa, 0x00,
(byte) 0xff, 0x55, (byte) 0xaa, 0x00,
0x00, (byte) 0xaa, (byte) 0xaa, 0x00,
0x55, (byte) 0xaa, (byte) 0xaa, 0x00,
(byte) 0xaa, (byte) 0xaa, (byte) 0xaa, 0x00,
(byte) 0xff, (byte) 0xaa, (byte) 0xaa, 0x00,
0x00, (byte) 0xff, (byte) 0xaa, 0x00,
0x55, (byte) 0xff, (byte) 0xaa, 0x00,
(byte) 0xaa, (byte) 0xff, (byte) 0xaa, 0x00,
(byte) 0xff, (byte) 0xff, (byte) 0xaa, 0x00,
0x00, 0x00, (byte) 0xff, 0x00,
0x55, 0x00, (byte) 0xff, 0x00,
(byte) 0xaa, 0x00, (byte) 0xff, 0x00,
(byte) 0xff, 0x00, (byte) 0xff, 0x00,
0x00, 0x55, (byte) 0xff, 0x00,
0x55, 0x55, (byte) 0xff, 0x00,
(byte) 0xaa, 0x55, (byte) 0xff, 0x00,
(byte) 0xff, 0x55, (byte) 0xff, 0x00,
0x00, (byte) 0xaa, (byte) 0xff, 0x00,
0x55, (byte) 0xaa, (byte) 0xff, 0x00,
(byte) 0xaa, (byte) 0xaa, (byte) 0xff, 0x00,
(byte) 0xff, (byte) 0xaa, (byte) 0xff, 0x00,
0x00, (byte) 0xff, (byte) 0xff, 0x00,
0x55, (byte) 0xff, (byte) 0xff, 0x00,
(byte) 0xaa, (byte) 0xff, (byte) 0xff, 0x00,
(byte) 0xff, (byte) 0xff, (byte) 0xff, 0x00,
};
byte last_id = -1;
private final ArrayList<UUID> tmpUUIDS = new ArrayList<>();
private static final UUID UUID_GBPEBBLE = UUID.fromString("61476764-7465-7262-6469-656775527a6c");
private static final UUID UUID_MORPHEUZ = UUID.fromString("5be44f1d-d262-4ea6-aa30-ddbec1e3cab2");
private static final UUID UUID_WHETHERNEAT = UUID.fromString("3684003b-a685-45f9-a713-abc6364ba051");
private static final UUID UUID_MISFIT = UUID.fromString("0b73b76a-cd65-4dc2-9585-aaa213320858");
private static final UUID UUID_PEBBLE_HEALTH = UUID.fromString("36d8c6ed-4c83-4fa1-a9e2-8f12dc941f8c");
private static final UUID UUID_PEBBLE_TIMESTYLE = UUID.fromString("4368ffa4-f0fb-4823-90be-f754b076bdaa");
private static final UUID UUID_PEBSTYLE = UUID.fromString("da05e84d-e2a2-4020-a2dc-9cdcf265fcdd");
private static final Map<UUID, AppMessageHandler> mAppMessageHandlers = new HashMap<>();
{
mAppMessageHandlers.put(UUID_GBPEBBLE, new AppMessageHandlerGBPebble(UUID_GBPEBBLE, PebbleProtocol.this));
mAppMessageHandlers.put(UUID_MORPHEUZ, new AppMessageHandlerMorpheuz(UUID_MORPHEUZ, PebbleProtocol.this));
mAppMessageHandlers.put(UUID_WHETHERNEAT, new AppMessageHandlerWeatherNeat(UUID_WHETHERNEAT, PebbleProtocol.this));
mAppMessageHandlers.put(UUID_MISFIT, new AppMessageHandlerMisfit(UUID_MISFIT, PebbleProtocol.this));
mAppMessageHandlers.put(UUID_PEBBLE_TIMESTYLE, new AppMessageHandlerTimeStylePebble(UUID_PEBBLE_TIMESTYLE, PebbleProtocol.this));
mAppMessageHandlers.put(UUID_PEBSTYLE, new AppMessageHandlerPebStyle(UUID_PEBSTYLE, PebbleProtocol.this));
}
private static byte[] encodeSimpleMessage(short endpoint, byte command) {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_SIMPLEMESSAGE);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_SIMPLEMESSAGE);
buf.putShort(endpoint);
buf.put(command);
return buf.array();
}
private static byte[] encodeMessage(short endpoint, byte type, int cookie, String[] parts) {
// Calculate length first
int length = LENGTH_PREFIX + 1;
if (parts != null) {
for (String s : parts) {
if (s == null || s.equals("")) {
length++; // encode null or empty strings as 0x00 later
continue;
}
length += (1 + s.getBytes().length);
}
}
if (endpoint == ENDPOINT_PHONECONTROL) {
length += 4; //for cookie;
}
// Encode Prefix
ByteBuffer buf = ByteBuffer.allocate(length);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort((short) (length - LENGTH_PREFIX));
buf.putShort(endpoint);
buf.put(type);
if (endpoint == ENDPOINT_PHONECONTROL) {
buf.putInt(cookie);
}
// Encode Pascal-Style Strings
if (parts != null) {
for (String s : parts) {
if (s == null || s.equals("")) {
//buf.put((byte)0x01);
buf.put((byte) 0x00);
continue;
}
int partlength = s.getBytes().length;
if (partlength > 255) partlength = 255;
buf.put((byte) partlength);
buf.put(s.getBytes(), 0, partlength);
}
}
return buf.array();
}
@Override
public byte[] encodeNotification(NotificationSpec notificationSpec) {
boolean hasHandle = notificationSpec.id != -1 && notificationSpec.phoneNumber == null;
int id = notificationSpec.id != -1 ? notificationSpec.id : mRandom.nextInt();
String title;
String subtitle = null;
// for SMS and EMAIL that came in though SMS or K9 receiver
if (notificationSpec.sender != null) {
title = notificationSpec.sender;
subtitle = notificationSpec.subject;
} else {
title = notificationSpec.title;
}
Long ts = System.currentTimeMillis();
if (!isFw3x) {
ts += (SimpleTimeZone.getDefault().getOffset(ts));
}
ts /= 1000;
if (isFw3x) {
// 3.x notification
//return encodeTimelinePin(id, (int) ((ts + 600) & 0xffffffffL), (short) 90, PebbleIconID.TIMELINE_CALENDAR, title); // really, this is just for testing
return encodeBlobdbNotification(id, (int) (ts & 0xffffffffL), title, subtitle, notificationSpec.body, notificationSpec.sourceName, hasHandle, notificationSpec.type, notificationSpec.cannedReplies);
} else if (mForceProtocol || notificationSpec.type != NotificationType.EMAIL) {
// 2.x notification
return encodeExtensibleNotification(id, (int) (ts & 0xffffffffL), title, subtitle, notificationSpec.body, notificationSpec.sourceName, hasHandle, notificationSpec.cannedReplies);
} else {
// 1.x notification on FW 2.X
String[] parts = {title, notificationSpec.body, ts.toString(), subtitle};
// be aware that type is at this point always NOTIFICATION_EMAIL
return encodeMessage(ENDPOINT_NOTIFICATION, NOTIFICATION_EMAIL, 0, parts);
}
}
@Override
public byte[] encodeSetTime() {
long ts = System.currentTimeMillis();
long ts_offset = (SimpleTimeZone.getDefault().getOffset(ts));
ByteBuffer buf;
if (isFw3x) {
String timezone = SimpleTimeZone.getDefault().getID();
short length = (short) (LENGTH_SETTIME + timezone.getBytes().length + 3);
buf = ByteBuffer.allocate(LENGTH_PREFIX + length);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(length);
buf.putShort(ENDPOINT_TIME);
buf.put(TIME_SETTIME_UTC);
buf.putInt((int) (ts / 1000));
buf.putShort((short) (ts_offset / 60000));
buf.put((byte) timezone.getBytes().length);
buf.put(timezone.getBytes());
LOG.info(timezone);
} else {
buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_SETTIME);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_SETTIME);
buf.putShort(ENDPOINT_TIME);
buf.put(TIME_SETTIME);
buf.putInt((int) ((ts + ts_offset) / 1000));
}
return buf.array();
}
@Override
public byte[] encodeFindDevice(boolean start) {
return encodeSetCallState("Where are you?", "Gadgetbridge", start ? ServiceCommand.CALL_INCOMING : ServiceCommand.CALL_END);
}
private static byte[] encodeExtensibleNotification(int id, int timestamp, String title, String subtitle, String body, String sourceName, boolean hasHandle, String[] cannedReplies) {
final short ACTION_LENGTH_MIN = 10;
String[] parts = {title, subtitle, body};
// Calculate length first
byte actions_count;
short actions_length;
String dismiss_string;
String open_string = "Open on phone";
String mute_string = "Mute";
String reply_string = "Reply";
if (sourceName != null) {
mute_string += " " + sourceName;
}
byte dismiss_action_id;
if (hasHandle) {
actions_count = 3;
dismiss_string = "Dismiss";
dismiss_action_id = 0x02;
actions_length = (short) (ACTION_LENGTH_MIN * actions_count + dismiss_string.getBytes().length + open_string.getBytes().length + mute_string.getBytes().length);
} else {
actions_count = 1;
dismiss_string = "Dismiss all";
dismiss_action_id = 0x03;
actions_length = (short) (ACTION_LENGTH_MIN * actions_count + dismiss_string.getBytes().length);
}
int replies_length = -1;
if (cannedReplies != null && cannedReplies.length > 0) {
actions_count++;
for (String reply : cannedReplies) {
replies_length += reply.getBytes().length + 1;
}
actions_length += ACTION_LENGTH_MIN + reply_string.getBytes().length + replies_length + 3; // 3 = attribute id (byte) + length(short)
}
byte attributes_count = 0;
int length = 21 + 10 + actions_length;
if (parts != null) {
for (String s : parts) {
if (s == null || s.equals("")) {
continue;
}
attributes_count++;
length += (3 + s.getBytes().length);
}
}
// Encode Prefix
ByteBuffer buf = ByteBuffer.allocate(length + LENGTH_PREFIX);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort((short) (length));
buf.putShort(ENDPOINT_EXTENSIBLENOTIFS);
buf.order(ByteOrder.LITTLE_ENDIAN); // !
buf.put((byte) 0x00); // ?
buf.put((byte) 0x01); // add notifications
buf.putInt(0x00000000); // flags - ?
buf.putInt(id);
buf.putInt(0x00000000); // ANCS id
buf.putInt(timestamp);
buf.put((byte) 0x01); // layout - ?
buf.put(attributes_count);
buf.put(actions_count);
byte attribute_id = 0;
// Encode Pascal-Style Strings
if (parts != null) {
for (String s : parts) {
attribute_id++;
if (s == null || s.equals("")) {
continue;
}
int partlength = s.getBytes().length;
if (partlength > 255) partlength = 255;
buf.put(attribute_id);
buf.putShort((short) partlength);
buf.put(s.getBytes(), 0, partlength);
}
}
// dismiss action
buf.put(dismiss_action_id);
buf.put((byte) 0x04); // dismiss
buf.put((byte) 0x01); // number attributes
buf.put((byte) 0x01); // attribute id (title)
buf.putShort((short) dismiss_string.getBytes().length);
buf.put(dismiss_string.getBytes());
// open and mute actions
if (hasHandle) {
buf.put((byte) 0x01);
buf.put((byte) 0x02); // generic
buf.put((byte) 0x01); // number attributes
buf.put((byte) 0x01); // attribute id (title)
buf.putShort((short) open_string.getBytes().length);
buf.put(open_string.getBytes());
buf.put((byte) 0x04);
buf.put((byte) 0x02); // generic
buf.put((byte) 0x01); // number attributes
buf.put((byte) 0x01); // attribute id (title)
buf.putShort((short) mute_string.getBytes().length);
buf.put(mute_string.getBytes());
}
if (cannedReplies != null && replies_length > 0) {
buf.put((byte) 0x05);
buf.put((byte) 0x03); // reply action
buf.put((byte) 0x02); // number attributes
buf.put((byte) 0x01); // title
buf.putShort((short) reply_string.getBytes().length);
buf.put(reply_string.getBytes());
buf.put((byte) 0x08); // canned replies
buf.putShort((short) replies_length);
for (int i = 0; i < cannedReplies.length - 1; i++) {
buf.put(cannedReplies[i].getBytes());
buf.put((byte) 0x00);
}
// last one must not be zero terminated, else we get an additional emply reply
buf.put(cannedReplies[cannedReplies.length - 1].getBytes());
}
return buf.array();
}
private byte[] encodeBlobdb(UUID uuid, byte command, byte db, byte[] blob) {
int length = LENGTH_BLOBDB;
if (blob != null) {
length += blob.length + 2;
}
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + length);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort((short) length);
buf.putShort(ENDPOINT_BLOBDB);
buf.order(ByteOrder.LITTLE_ENDIAN);
buf.put(command);
buf.putShort((short) mRandom.nextInt()); // token
buf.put(db);
buf.put(LENGTH_UUID);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putLong(uuid.getMostSignificantBits());
buf.putLong(uuid.getLeastSignificantBits());
buf.order(ByteOrder.LITTLE_ENDIAN);
if (blob != null) {
buf.putShort((short) blob.length);
buf.put(blob);
}
return buf.array();
}
private byte[] encodeBlobDBClear(byte database) {
final short LENGTH_BLOBDB_CLEAR = 4;
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_BLOBDB_CLEAR);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_BLOBDB_CLEAR);
buf.putShort(ENDPOINT_BLOBDB);
buf.order(ByteOrder.LITTLE_ENDIAN);
buf.put(BLOBDB_CLEAR);
buf.putShort((short) mRandom.nextInt()); // token
buf.put(database);
return buf.array();
}
private byte[] encodeTimelinePin(int id, int timestamp, short duration, int icon_id, String title, String subtitle) {
final short TIMELINE_PIN_LENGTH = 46;
icon_id |= 0x80000000;
UUID uuid = new UUID(mRandom.nextLong(), ((long) mRandom.nextInt() << 32) | id);
byte attributes_count = 2;
byte actions_count = 0;
int attributes_length = 10 + title.getBytes().length;
if (subtitle != null && !subtitle.isEmpty()) {
attributes_length += 3 + subtitle.getBytes().length;
attributes_count += 1;
}
int pin_length = TIMELINE_PIN_LENGTH + attributes_length;
ByteBuffer buf = ByteBuffer.allocate(pin_length);
// pin - 46 bytes
buf.order(ByteOrder.BIG_ENDIAN);
buf.putLong(uuid.getMostSignificantBits());
buf.putLong(uuid.getLeastSignificantBits());
buf.putLong(0); // parent
buf.putLong(0);
buf.order(ByteOrder.LITTLE_ENDIAN);
buf.putInt(timestamp); // 32-bit timestamp
buf.putShort(duration);
buf.put((byte) 0x02); // type (0x02 = pin)
buf.putShort((short) 0x0001); // flags 0x0001 = ?
buf.put((byte) 0x01); // layout was (0x02 = pin?), 0x01 needed for subtitle aber seems to do no harm if there isn't one
buf.putShort((short) attributes_length); // total length of all attributes and actions in bytes
buf.put(attributes_count);
buf.put(actions_count);
buf.put((byte) 4); // icon
buf.putShort((short) 4); // length of int
buf.putInt(icon_id);
buf.put((byte) 1); // title
buf.putShort((short) title.getBytes().length);
buf.put(title.getBytes());
if (subtitle != null && !subtitle.isEmpty()) {
buf.put((byte) 2); //subtitle
buf.putShort((short) subtitle.getBytes().length);
buf.put(subtitle.getBytes());
}
return encodeBlobdb(uuid, BLOBDB_INSERT, BLOBDB_PIN, buf.array());
}
private byte[] encodeBlobdbNotification(int id, int timestamp, String title, String subtitle, String body, String sourceName, boolean hasHandle, NotificationType notificationType, String[] cannedReplies) {
final short NOTIFICATION_PIN_LENGTH = 46;
final short ACTION_LENGTH_MIN = 10;
String[] parts = {title, subtitle, body};
int icon_id;
byte color_id;
switch (notificationType) {
case EMAIL:
icon_id = PebbleIconID.GENERIC_EMAIL;
color_id = PebbleColor.JaegerGreen;
break;
case SMS:
icon_id = PebbleIconID.GENERIC_SMS;
color_id = PebbleColor.VividViolet;
break;
default:
switch (notificationType) {
case TWITTER:
icon_id = PebbleIconID.NOTIFICATION_TWITTER;
color_id = PebbleColor.BlueMoon;
break;
case EMAIL:
icon_id = PebbleIconID.GENERIC_EMAIL;
color_id = PebbleColor.JaegerGreen;
break;
case SMS:
icon_id = PebbleIconID.GENERIC_SMS;
color_id = PebbleColor.VividViolet;
break;
case FACEBOOK:
icon_id = PebbleIconID.NOTIFICATION_FACEBOOK;
color_id = PebbleColor.VeryLightBlue;
break;
case CHAT:
icon_id = PebbleIconID.NOTIFICATION_HIPCHAT;
color_id = PebbleColor.Inchworm;
break;
default:
icon_id = PebbleIconID.NOTIFICATION_GENERIC;
color_id = PebbleColor.Red;
break;
}
break;
}
// Calculate length first
byte actions_count;
short actions_length;
String dismiss_string;
String open_string = "Open on phone";
String mute_string = "Mute";
String reply_string = "Reply";
if (sourceName != null) {
mute_string += " " + sourceName;
}
byte dismiss_action_id;
if (hasHandle) {
actions_count = 3;
dismiss_string = "Dismiss";
dismiss_action_id = 0x02;
actions_length = (short) (ACTION_LENGTH_MIN * actions_count + dismiss_string.getBytes().length + open_string.getBytes().length + mute_string.getBytes().length);
} else {
actions_count = 1;
dismiss_string = "Dismiss all";
dismiss_action_id = 0x03;
actions_length = (short) (ACTION_LENGTH_MIN * actions_count + dismiss_string.getBytes().length);
}
int replies_length = -1;
if (cannedReplies != null && cannedReplies.length > 0) {
actions_count++;
for (String reply : cannedReplies) {
replies_length += reply.getBytes().length + 1;
}
actions_length += ACTION_LENGTH_MIN + reply_string.getBytes().length + replies_length + 3; // 3 = attribute id (byte) + length(short)
}
byte attributes_count = 2; // icon
short attributes_length = (short) (11 + actions_length);
if (parts != null) {
for (String s : parts) {
if (s == null || s.equals("")) {
continue;
}
attributes_count++;
attributes_length += (3 + s.getBytes().length);
}
}
UUID uuid = UUID.randomUUID();
short pin_length = (short) (NOTIFICATION_PIN_LENGTH + attributes_length);
ByteBuffer buf = ByteBuffer.allocate(pin_length);
// pin - 46 bytes
buf.order(ByteOrder.BIG_ENDIAN);
buf.putLong(uuid.getMostSignificantBits());
buf.putInt((int) (uuid.getLeastSignificantBits() >>> 32));
buf.putInt(id);
buf.putLong(uuid.getMostSignificantBits());
buf.putInt((int) (uuid.getLeastSignificantBits() >>> 32));
buf.putInt(id);
buf.order(ByteOrder.LITTLE_ENDIAN);
buf.putInt(timestamp); // 32-bit timestamp
buf.putShort((short) 0); // duration
buf.put((byte) 0x01); // type (0x01 = notification)
buf.putShort((short) 0x0001); // flags 0x0001 = ?
buf.put((byte) 0x04); // layout (0x04 = notification?)
buf.putShort(attributes_length); // total length of all attributes and actions in bytes
buf.put(attributes_count);
buf.put(actions_count);
byte attribute_id = 0;
// Encode Pascal-Style Strings
if (parts != null) {
for (String s : parts) {
attribute_id++;
if (s == null || s.equals("")) {
continue;
}
int partlength = s.getBytes().length;
if (partlength > 512) partlength = 512;
buf.put(attribute_id);
buf.putShort((short) partlength);
buf.put(s.getBytes(), 0, partlength);
}
}
buf.put((byte) 4); // icon
buf.putShort((short) 4); // length of int
buf.putInt(0x80000000 | icon_id);
buf.put((byte) 28); // background_color
buf.putShort((short) 1); // length of int
buf.put(color_id);
// dismiss action
buf.put(dismiss_action_id);
buf.put((byte) 0x02); // generic action, dismiss did not do anything
buf.put((byte) 0x01); // number attributes
buf.put((byte) 0x01); // attribute id (title)
buf.putShort((short) dismiss_string.getBytes().length);
buf.put(dismiss_string.getBytes());
// open and mute actions
if (hasHandle) {
buf.put((byte) 0x01);
buf.put((byte) 0x02); // generic action
buf.put((byte) 0x01); // number attributes
buf.put((byte) 0x01); // attribute id (title)
buf.putShort((short) open_string.getBytes().length);
buf.put(open_string.getBytes());
buf.put((byte) 0x04);
buf.put((byte) 0x02); // generic action
buf.put((byte) 0x01); // number attributes
buf.put((byte) 0x01); // attribute id (title)
buf.putShort((short) mute_string.getBytes().length);
buf.put(mute_string.getBytes());
}
if (cannedReplies != null && replies_length > 0) {
buf.put((byte) 0x05);
buf.put((byte) 0x03); // reply action
buf.put((byte) 0x02); // number attributes
buf.put((byte) 0x01); // title
buf.putShort((short) reply_string.getBytes().length);
buf.put(reply_string.getBytes());
buf.put((byte) 0x08); // canned replies
buf.putShort((short) replies_length);
for (int i = 0; i < cannedReplies.length - 1; i++) {
buf.put(cannedReplies[i].getBytes());
buf.put((byte) 0x00);
}
// last one must not be zero terminated, else we get an additional emply reply
buf.put(cannedReplies[cannedReplies.length - 1].getBytes());
}
return encodeBlobdb(UUID.randomUUID(), BLOBDB_INSERT, BLOBDB_NOTIFICATION, buf.array());
}
public byte[] encodeActionResponse2x(int id, byte actionId, int iconId, String caption) {
short length = (short) (18 + caption.getBytes().length);
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + length);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(length);
buf.putShort(ENDPOINT_EXTENSIBLENOTIFS);
buf.order(ByteOrder.LITTLE_ENDIAN);
buf.put(NOTIFICATIONACTION_RESPONSE);
buf.putInt(id);
buf.put(actionId);
buf.put(NOTIFICATIONACTION_ACK);
buf.put((byte) 2); //nr of attributes
buf.put((byte) 6); // icon
buf.putShort((short) 4); // length
buf.putInt(iconId);
buf.put((byte) 2); // title
buf.putShort((short) caption.getBytes().length);
buf.put(caption.getBytes());
return buf.array();
}
public byte[] encodeActionResponse(UUID uuid, int iconId, String caption) {
short length = (short) (29 + caption.getBytes().length);
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + length);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(length);
buf.putShort(ENDPOINT_NOTIFICATIONACTION);
buf.put(NOTIFICATIONACTION_RESPONSE);
buf.putLong(uuid.getMostSignificantBits());
buf.putLong(uuid.getLeastSignificantBits());
buf.order(ByteOrder.LITTLE_ENDIAN);
buf.put(NOTIFICATIONACTION_ACK);
buf.put((byte) 2); //nr of attributes
buf.put((byte) 6); // icon
buf.putShort((short) 4); // length
buf.putInt(0x80000000 | iconId);
buf.put((byte) 2); // title
buf.putShort((short) caption.getBytes().length);
buf.put(caption.getBytes());
return buf.array();
}
public byte[] encodeInstallMetadata(UUID uuid, String appName, short appVersion, short sdkVersion, int flags, int iconId) {
final short METADATA_LENGTH = 126;
byte[] name_buf = new byte[96];
System.arraycopy(appName.getBytes(), 0, name_buf, 0, appName.getBytes().length);
ByteBuffer buf = ByteBuffer.allocate(METADATA_LENGTH);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putLong(uuid.getMostSignificantBits()); // watchapp uuid
buf.putLong(uuid.getLeastSignificantBits());
buf.order(ByteOrder.LITTLE_ENDIAN);
buf.putInt(flags);
buf.putInt(iconId);
buf.putShort(appVersion);
buf.putShort(sdkVersion);
buf.put((byte) 0); // app_face_bgcolor
buf.put((byte) 0); // app_face_template_id
buf.put(name_buf); // 96 bytes
return encodeBlobdb(uuid, BLOBDB_INSERT, BLOBDB_APP, buf.array());
}
public byte[] encodeAppFetchAck() {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_APPFETCH);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_APPFETCH);
buf.putShort(ENDPOINT_APPFETCH);
buf.put((byte) 0x01);
buf.put((byte) 0x01);
return buf.array();
}
public byte[] encodeGetTime() {
return encodeSimpleMessage(ENDPOINT_TIME, TIME_GETTIME);
}
@Override
public byte[] encodeSetCallState(String number, String name, ServiceCommand command) {
String[] parts = {number, name};
byte pebbleCmd;
switch (command) {
case CALL_START:
pebbleCmd = PHONECONTROL_START;
break;
case CALL_END:
pebbleCmd = PHONECONTROL_END;
break;
case CALL_INCOMING:
pebbleCmd = PHONECONTROL_INCOMINGCALL;
break;
case CALL_OUTGOING:
// pebbleCmd = PHONECONTROL_OUTGOINGCALL;
/*
* HACK/WORKAROUND for non-working outgoing call display.
* Just send a incoming call command immediately followed by a start call command
* This prevents vibration of the Pebble.
*/
byte[] callmsg = encodeMessage(ENDPOINT_PHONECONTROL, PHONECONTROL_INCOMINGCALL, 0, parts);
byte[] startmsg = encodeMessage(ENDPOINT_PHONECONTROL, PHONECONTROL_START, 0, parts);
byte[] msg = new byte[callmsg.length + startmsg.length];
System.arraycopy(callmsg, 0, msg, 0, callmsg.length);
System.arraycopy(startmsg, 0, msg, startmsg.length, startmsg.length);
return msg;
// END HACK
default:
return null;
}
return encodeMessage(ENDPOINT_PHONECONTROL, pebbleCmd, 0, parts);
}
@Override
public byte[] encodeSetMusicInfo(String artist, String album, String track) {
String[] parts = {artist, album, track};
return encodeMessage(ENDPOINT_MUSICCONTROL, MUSICCONTROL_SETMUSICINFO, 0, parts);
}
@Override
public byte[] encodeFirmwareVersionReq() {
return encodeSimpleMessage(ENDPOINT_FIRMWAREVERSION, FIRMWAREVERSION_GETVERSION);
}
@Override
public byte[] encodeAppInfoReq() {
if (isFw3x) {
return null; // can't do this on 3.x :(
}
return encodeSimpleMessage(ENDPOINT_APPMANAGER, APPMANAGER_GETUUIDS);
}
@Override
public byte[] encodeAppStart(UUID uuid, boolean start) {
if (isFw3x) {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_APPRUNSTATE);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_APPRUNSTATE);
buf.putShort(ENDPOINT_APPRUNSTATE);
buf.put(start ? APPRUNSTATE_START : APPRUNSTATE_STOP);
buf.putLong(uuid.getMostSignificantBits());
buf.putLong(uuid.getLeastSignificantBits());
return buf.array();
} else {
ArrayList<Pair<Integer, Object>> pairs = new ArrayList<>();
int param = start ? 1 : 0;
pairs.add(new Pair<>(1, (Object) param));
return encodeApplicationMessagePush(ENDPOINT_LAUNCHER, uuid, pairs);
}
}
@Override
public byte[] encodeAppDelete(UUID uuid) {
if (isFw3x) {
return encodeBlobdb(uuid, BLOBDB_DELETE, BLOBDB_APP, null);
} else {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_REMOVEAPP_2X);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_REMOVEAPP_2X);
buf.putShort(ENDPOINT_APPMANAGER);
buf.put(APPMANAGER_REMOVEAPP);
buf.putLong(uuid.getMostSignificantBits());
buf.putLong(uuid.getLeastSignificantBits());
return buf.array();
}
}
private byte[] encodePhoneVersion2x(byte os) {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_PHONEVERSION);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_PHONEVERSION);
buf.putShort(ENDPOINT_PHONEVERSION);
buf.put((byte) 0x01);
buf.putInt(-1); //0xffffffff
if (os == PHONEVERSION_REMOTE_OS_ANDROID) {
buf.putInt(PHONEVERSION_SESSION_CAPS_GAMMARAY);
} else {
buf.putInt(0);
}
buf.putInt(PHONEVERSION_REMOTE_CAPS_SMS | PHONEVERSION_REMOTE_CAPS_TELEPHONY | os);
buf.put(PHONEVERSION_APPVERSION_MAGIC);
buf.put(PHONEVERSION_APPVERSION_MAJOR);
buf.put(PHONEVERSION_APPVERSION_MINOR);
buf.put(PHONEVERSION_APPVERSION_PATCH);
return buf.array();
}
private byte[] encodePhoneVersion3x(byte os) {
final short LENGTH_PHONEVERSION3X = 25;
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_PHONEVERSION3X);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_PHONEVERSION3X);
buf.putShort(ENDPOINT_PHONEVERSION);
buf.put((byte) 0x01);
buf.putInt(-1); //0xffffffff
buf.putInt(0);
buf.putInt(os);
buf.put(PHONEVERSION_APPVERSION_MAGIC);
buf.put((byte) 3); // major
buf.put((byte) 8); // minor
buf.put((byte) 1); // patch
buf.order(ByteOrder.LITTLE_ENDIAN);
buf.putLong(0x00000000000000af); //flags
return buf.array();
}
public byte[] encodePhoneVersion(byte os) {
return encodePhoneVersion3x(os);
}
@Override
public byte[] encodeReboot() {
return encodeSimpleMessage(ENDPOINT_RESET, RESET_REBOOT);
}
@Override
public byte[] encodeScreenshotReq() {
return encodeSimpleMessage(ENDPOINT_SCREENSHOT, SCREENSHOT_TAKE);
}
/* pebble specific install methods */
public byte[] encodeUploadStart(byte type, int app_id, int size, String filename) {
short length;
if (isFw3x && (type != PUTBYTES_TYPE_FILE)) {
length = LENGTH_UPLOADSTART_3X;
type |= 0b10000000;
} else {
length = LENGTH_UPLOADSTART_2X;
}
if (type == PUTBYTES_TYPE_FILE && filename != null) {
length += filename.getBytes().length + 1;
}
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + length);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(length);
buf.putShort(ENDPOINT_PUTBYTES);
buf.put(PUTBYTES_INIT);
buf.putInt(size);
buf.put(type);
if (isFw3x && (type != PUTBYTES_TYPE_FILE)) {
buf.putInt(app_id);
} else {
// slot
buf.put((byte) app_id);
}
if (type == PUTBYTES_TYPE_FILE && filename != null) {
buf.put(filename.getBytes());
buf.put((byte) 0);
}
return buf.array();
}
public byte[] encodeUploadChunk(int token, byte[] buffer, int size) {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_UPLOADCHUNK + size);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort((short) (LENGTH_UPLOADCHUNK + size));
buf.putShort(ENDPOINT_PUTBYTES);
buf.put(PUTBYTES_SEND);
buf.putInt(token);
buf.putInt(size);
buf.put(buffer, 0, size);
return buf.array();
}
public byte[] encodeUploadCommit(int token, int crc) {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_UPLOADCOMMIT);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_UPLOADCOMMIT);
buf.putShort(ENDPOINT_PUTBYTES);
buf.put(PUTBYTES_COMMIT);
buf.putInt(token);
buf.putInt(crc);
return buf.array();
}
public byte[] encodeUploadComplete(int token) {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_UPLOADCOMPLETE);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_UPLOADCOMPLETE);
buf.putShort(ENDPOINT_PUTBYTES);
buf.put(PUTBYTES_COMPLETE);
buf.putInt(token);
return buf.array();
}
public byte[] encodeUploadCancel(int token) {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_UPLOADCANCEL);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_UPLOADCANCEL);
buf.putShort(ENDPOINT_PUTBYTES);
buf.put(PUTBYTES_ABORT);
buf.putInt(token);
return buf.array();
}
private byte[] encodeSystemMessage(byte systemMessage) {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_SYSTEMMESSAGE);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_SYSTEMMESSAGE);
buf.putShort(ENDPOINT_SYSTEMMESSAGE);
buf.put((byte) 0);
buf.put(systemMessage);
return buf.array();
}
public byte[] encodeInstallFirmwareStart() {
return encodeSystemMessage(SYSTEMMESSAGE_FIRMWARESTART);
}
public byte[] encodeInstallFirmwareComplete() {
return encodeSystemMessage(SYSTEMMESSAGE_FIRMWARECOMPLETE);
}
public byte[] encodeInstallFirmwareError() {
return encodeSystemMessage(SYSTEMMESSAGE_FIRMWAREFAIL);
}
public byte[] encodeAppRefresh(int index) {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_REFRESHAPP);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_REFRESHAPP);
buf.putShort(ENDPOINT_APPMANAGER);
buf.put(APPMANAGER_REFRESHAPP);
buf.putInt(index);
return buf.array();
}
public byte[] encodeDatalog(byte handle, byte reply) {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + 2);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort((short) 2);
buf.putShort(ENDPOINT_DATALOG);
buf.put(reply);
buf.put(handle);
return buf.array();
}
byte[] encodeApplicationMessageAck(UUID uuid, byte id) {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + 18); // +ACK
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort((short) 18);
buf.putShort(ENDPOINT_APPLICATIONMESSAGE);
buf.put(APPLICATIONMESSAGE_ACK);
buf.put(id);
buf.putLong(uuid.getMostSignificantBits());
buf.putLong(uuid.getMostSignificantBits());
return buf.array();
}
private static byte[] encodePing(byte command, int cookie) {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_PING);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_PING);
buf.putShort(ENDPOINT_PING);
buf.put(command);
buf.putInt(cookie);
return buf.array();
}
private ArrayList<Pair<Integer, Object>> decodeDict(ByteBuffer buf) {
ArrayList<Pair<Integer, Object>> dict = new ArrayList<>();
buf.order(ByteOrder.LITTLE_ENDIAN);
byte dictSize = buf.get();
while (dictSize-- > 0) {
Integer key = buf.getInt();
byte type = buf.get();
short length = buf.getShort();
switch (type) {
case TYPE_INT:
case TYPE_UINT:
dict.add(new Pair<Integer, Object>(key, buf.getInt()));
break;
case TYPE_CSTRING:
case TYPE_BYTEARRAY:
byte[] bytes = new byte[length];
buf.get(bytes);
if (type == TYPE_BYTEARRAY) {
dict.add(new Pair<Integer, Object>(key, bytes));
} else {
dict.add(new Pair<Integer, Object>(key, new String(bytes)));
}
break;
default:
}
}
return dict;
}
private GBDeviceEvent[] decodeDictToJSONAppMessage(UUID uuid, ByteBuffer buf) throws JSONException {
buf.order(ByteOrder.LITTLE_ENDIAN);
byte dictSize = buf.get();
if (dictSize == 0) {
LOG.info("dict size is 0, ignoring");
return null;
}
JSONArray jsonArray = new JSONArray();
while (dictSize-- > 0) {
JSONObject jsonObject = new JSONObject();
Integer key = buf.getInt();
byte type = buf.get();
short length = buf.getShort();
jsonObject.put("key", key);
jsonObject.put("length", length);
switch (type) {
case TYPE_UINT:
jsonObject.put("type", "uint");
if (length == 1) {
jsonObject.put("value", buf.get() & 0xff);
} else if (length == 2) {
jsonObject.put("value", buf.getShort() & 0xffff);
} else {
jsonObject.put("value", buf.getInt() & 0xffffffffL);
}
break;
case TYPE_INT:
jsonObject.put("type", "int");
if (length == 1) {
jsonObject.put("value", buf.get());
} else if (length == 2) {
jsonObject.put("value", buf.getShort());
} else {
jsonObject.put("value", buf.getInt());
}
break;
case TYPE_BYTEARRAY:
case TYPE_CSTRING:
byte[] bytes = new byte[length];
buf.get(bytes);
if (type == TYPE_BYTEARRAY) {
jsonObject.put("type", "bytes");
jsonObject.put("value", Base64.encode(bytes, Base64.NO_WRAP));
} else {
jsonObject.put("type", "string");
jsonObject.put("value", new String(bytes));
}
break;
default:
LOG.info("unknown type in appmessage, ignoring");
return null;
}
jsonArray.put(jsonObject);
}
// this is a hack we send an ack to the Pebble immediately because we cannot map the transaction_id from the intent back to a uuid yet
GBDeviceEventSendBytes sendBytesAck = new GBDeviceEventSendBytes();
sendBytesAck.encodedBytes = encodeApplicationMessageAck(uuid, last_id);
GBDeviceEventAppMessage appMessage = new GBDeviceEventAppMessage();
appMessage.appUUID = uuid;
appMessage.id = last_id & 0xff;
appMessage.message = jsonArray.toString();
return new GBDeviceEvent[]{appMessage, sendBytesAck};
}
byte[] encodeApplicationMessagePush(short endpoint, UUID uuid, ArrayList<Pair<Integer, Object>> pairs) {
int length = LENGTH_UUID + 3; // UUID + (PUSH + id + length of dict)
for (Pair<Integer, Object> pair : pairs) {
length += 7; // key + type + length
if (pair.second instanceof Integer) {
length += 4;
} else if (pair.second instanceof Short) {
length += 2;
} else if (pair.second instanceof Byte) {
length += 1;
} else if (pair.second instanceof String) {
length += ((String) pair.second).getBytes().length + 1;
} else if (pair.second instanceof byte[]) {
length += ((byte[]) pair.second).length;
}
}
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + length);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort((short) length);
buf.putShort(endpoint); // 48 or 49
buf.put(APPLICATIONMESSAGE_PUSH);
buf.put(++last_id);
buf.putLong(uuid.getMostSignificantBits());
buf.putLong(uuid.getLeastSignificantBits());
buf.put((byte) pairs.size());
buf.order(ByteOrder.LITTLE_ENDIAN);
for (Pair<Integer, Object> pair : pairs) {
buf.putInt(pair.first);
if (pair.second instanceof Integer) {
buf.put(TYPE_INT);
buf.putShort((short) 4); // length
buf.putInt((int) pair.second);
} else if (pair.second instanceof Short) {
buf.put(TYPE_INT);
buf.putShort((short) 2); // length
buf.putShort((short) pair.second);
} else if (pair.second instanceof Byte) {
buf.put(TYPE_INT);
buf.putShort((short) 1); // length
buf.put((byte) pair.second);
} else if (pair.second instanceof String) {
String str = (String) pair.second;
buf.put(TYPE_CSTRING);
buf.putShort((short) (str.getBytes().length + 1));
buf.put(str.getBytes());
buf.put((byte) 0);
} else if (pair.second instanceof byte[]) {
byte[] bytes = (byte[]) pair.second;
buf.put(TYPE_BYTEARRAY);
buf.putShort((short) bytes.length);
buf.put(bytes);
}
}
return buf.array();
}
public byte[] encodeApplicationMessageFromJSON(UUID uuid, JSONArray jsonArray) {
ArrayList<Pair<Integer, Object>> pairs = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
String type = (String) jsonObject.get("type");
int key = (int) jsonObject.get("key");
int length = (int) jsonObject.get("length");
switch (type) {
case "uint":
case "int":
if (length == 1) {
pairs.add(new Pair<>(key, (Object) (byte) jsonObject.getInt("value")));
} else if (length == 2) {
pairs.add(new Pair<>(key, (Object) (short) jsonObject.getInt("value")));
} else {
if (type.equals("uint")) {
pairs.add(new Pair<>(key, (Object) (int) (jsonObject.getInt("value") & 0xffffffffL)));
} else {
pairs.add(new Pair<>(key, (Object) jsonObject.getInt("value")));
}
}
break;
case "string":
pairs.add(new Pair<>(key, (Object) jsonObject.getString("value")));
break;
case "bytes":
byte[] bytes = Base64.decode(jsonObject.getString("value"), Base64.NO_WRAP);
pairs.add(new Pair<>(key, (Object) bytes));
break;
}
} catch (JSONException e) {
return null;
}
}
return encodeApplicationMessagePush(ENDPOINT_APPLICATIONMESSAGE, uuid, pairs);
}
private static byte reverseBits(byte in) {
byte out = 0;
for (int i = 0; i < 8; i++) {
byte bit = (byte) (in & 1);
out = (byte) ((out << 1) | bit);
in = (byte) (in >> 1);
}
return out;
}
private GBDeviceEventScreenshot decodeScreenshot(ByteBuffer buf, int length) {
if (mDevEventScreenshot == null) {
byte result = buf.get();
mDevEventScreenshot = new GBDeviceEventScreenshot();
int version = buf.getInt();
if (result != 0) {
return null;
}
mDevEventScreenshot.width = buf.getInt();
mDevEventScreenshot.height = buf.getInt();
if (version == 1) {
mDevEventScreenshot.bpp = 1;
mDevEventScreenshot.clut = clut_pebble;
} else {
mDevEventScreenshot.bpp = 8;
mDevEventScreenshot.clut = clut_pebbletime;
}
mScreenshotRemaining = (mDevEventScreenshot.width * mDevEventScreenshot.height * mDevEventScreenshot.bpp) / 8;
mDevEventScreenshot.data = new byte[mScreenshotRemaining];
length -= 13;
}
if (mScreenshotRemaining == -1) {
return null;
}
for (int i = 0; i < length; i++) {
byte corrected = buf.get();
if (mDevEventScreenshot.bpp == 1) {
corrected = reverseBits(corrected);
} else {
corrected = (byte) (corrected & 0b00111111);
}
mDevEventScreenshot.data[mDevEventScreenshot.data.length - mScreenshotRemaining + i] = corrected;
}
mScreenshotRemaining -= length;
LOG.info("Screenshot remaining bytes " + mScreenshotRemaining);
if (mScreenshotRemaining == 0) {
mScreenshotRemaining = -1;
LOG.info("Got screenshot : " + mDevEventScreenshot.width + "x" + mDevEventScreenshot.height + " " + "pixels");
GBDeviceEventScreenshot devEventScreenshot = mDevEventScreenshot;
mDevEventScreenshot = null;
return devEventScreenshot;
}
return null;
}
private GBDeviceEvent[] decodeAction(ByteBuffer buf) {
buf.order(ByteOrder.LITTLE_ENDIAN);
byte command = buf.get();
if (command == NOTIFICATIONACTION_INVOKE) {
int id;
long uuid_high = 0;
long uuid_low = 0;
if (isFw3x) {
buf.order(ByteOrder.BIG_ENDIAN);
uuid_high = buf.getLong();
uuid_low = buf.getLong();
buf.order(ByteOrder.LITTLE_ENDIAN);
id = (int) (uuid_low & 0xffffffffL);
} else {
id = buf.getInt();
}
byte action = buf.get();
if (action >= 0x01 && action <= 0x05) {
GBDeviceEventNotificationControl devEvtNotificationControl = new GBDeviceEventNotificationControl();
devEvtNotificationControl.handle = id;
String caption = "undefined";
int icon_id = 1;
boolean needsAck2x = true;
switch (action) {
case 0x01:
devEvtNotificationControl.event = GBDeviceEventNotificationControl.Event.OPEN;
caption = "Opened";
icon_id = PebbleIconID.DURING_PHONE_CALL;
break;
case 0x02:
devEvtNotificationControl.event = GBDeviceEventNotificationControl.Event.DISMISS;
caption = "Dismissed";
icon_id = PebbleIconID.RESULT_DISMISSED;
needsAck2x = false;
break;
case 0x03:
devEvtNotificationControl.event = GBDeviceEventNotificationControl.Event.DISMISS_ALL;
caption = "All dismissed";
icon_id = PebbleIconID.RESULT_DISMISSED;
needsAck2x = false;
break;
case 0x04:
devEvtNotificationControl.event = GBDeviceEventNotificationControl.Event.MUTE;
caption = "Muted";
icon_id = PebbleIconID.RESULT_MUTE;
break;
case 0x05:
boolean failed = true;
byte attribute_count = buf.get();
if (attribute_count > 0) {
byte attribute = buf.get();
if (attribute == 0x01) { // reply string is in attribute 0x01
short length = buf.getShort();
if (length > 64) length = 64;
byte[] reply = new byte[length];
buf.get(reply);
// FIXME: this does not belong here, but we want at least check if there is no chance at all to send out the SMS later before we report success
String phoneNumber = GBApplication.getIDSenderLookup().lookup(id);
if (phoneNumber != null) {
devEvtNotificationControl.event = GBDeviceEventNotificationControl.Event.REPLY;
devEvtNotificationControl.reply = new String(reply);
caption = "SENT";
icon_id = PebbleIconID.RESULT_SENT;
failed = false;
}
}
}
if (failed) {
caption = "FAILED";
icon_id = PebbleIconID.RESULT_FAILED;
devEvtNotificationControl = null; // error
}
break;
}
GBDeviceEventSendBytes sendBytesAck = null;
if (isFw3x || needsAck2x) {
sendBytesAck = new GBDeviceEventSendBytes();
if (isFw3x) {
sendBytesAck.encodedBytes = encodeActionResponse(new UUID(uuid_high, uuid_low), icon_id, caption);
} else {
sendBytesAck.encodedBytes = encodeActionResponse2x(id, action, 6, caption);
}
}
return new GBDeviceEvent[]{sendBytesAck, devEvtNotificationControl};
}
LOG.info("unexpected action: " + action);
}
return null;
}
private GBDeviceEventSendBytes decodePing(ByteBuffer buf) {
byte command = buf.get();
if (command == PING_PING) {
int cookie = buf.getInt();
LOG.info("Received PING - will reply");
GBDeviceEventSendBytes sendBytes = new GBDeviceEventSendBytes();
sendBytes.encodedBytes = encodePing(PING_PONG, cookie);
return sendBytes;
}
return null;
}
private GBDeviceEvent decodeSystemMessage(ByteBuffer buf) {
buf.get(); // unknown;
byte command = buf.get();
final String ENDPOINT_NAME = "SYSTEM MESSAGE";
switch (command) {
case SYSTEMMESSAGE_STOPRECONNECTING:
LOG.info(ENDPOINT_NAME + ": stop reconnecting");
break;
case SYSTEMMESSAGE_STARTRECONNECTING:
LOG.info(ENDPOINT_NAME + ": start reconnecting");
break;
default:
LOG.info(ENDPOINT_NAME + ": " + command);
break;
}
return null;
}
private GBDeviceEvent decodeAppRunState(ByteBuffer buf) {
byte command = buf.get();
long uuid_high = buf.getLong();
long uuid_low = buf.getLong();
UUID uuid = new UUID(uuid_high, uuid_low);
final String ENDPOINT_NAME = "APPRUNSTATE";
switch (command) {
case APPRUNSTATE_START:
LOG.info(ENDPOINT_NAME + ": started " + uuid);
if (UUID_PEBSTYLE.equals(uuid)) {
AppMessageHandler handler = mAppMessageHandlers.get(uuid);
return handler.pushMessage()[0];
}
break;
case APPRUNSTATE_STOP:
LOG.info(ENDPOINT_NAME + ": stopped " + uuid);
break;
default:
LOG.info(ENDPOINT_NAME + ": (cmd:" + command + ")" + uuid);
break;
}
return null;
}
private GBDeviceEvent decodeBlobDb(ByteBuffer buf) {
final String ENDPOINT_NAME = "BLOBDB";
final String statusString[] = {
"unknown",
"success",
"general failure",
"invalid operation",
"invalid database id",
"invalid data",
"key does not exist",
"database full",
"data stale",
};
buf.order(ByteOrder.LITTLE_ENDIAN);
short token = buf.getShort();
byte status = buf.get();
if (status >= 0 && status < statusString.length) {
LOG.info(ENDPOINT_NAME + ": " + statusString[status] + " (token " + (token & 0xffff) + ")");
} else {
LOG.warn(ENDPOINT_NAME + ": unknown status " + status + " (token " + (token & 0xffff) + ")");
}
return null;
}
private GBDeviceEventAppManagement decodeAppFetch(ByteBuffer buf) {
byte command = buf.get();
if (command == 0x01) {
long uuid_high = buf.getLong();
long uuid_low = buf.getLong();
UUID uuid = new UUID(uuid_high, uuid_low);
buf.order(ByteOrder.LITTLE_ENDIAN);
int app_id = buf.getInt();
GBDeviceEventAppManagement fetchRequest = new GBDeviceEventAppManagement();
fetchRequest.type = GBDeviceEventAppManagement.EventType.INSTALL;
fetchRequest.event = GBDeviceEventAppManagement.Event.REQUEST;
fetchRequest.token = app_id;
fetchRequest.uuid = uuid;
return fetchRequest;
}
return null;
}
private GBDeviceEventSendBytes decodeDatalog(ByteBuffer buf, short length) {
byte command = buf.get();
byte id = buf.get();
switch (command) {
case DATALOG_TIMEOUT:
LOG.info("DATALOG TIMEOUT. id=" + (id & 0xff) + " - ignoring");
return null;
case DATALOG_SENDDATA:
buf.order(ByteOrder.LITTLE_ENDIAN);
int items_left = buf.getInt();
int crc = buf.getInt();
LOG.info("DATALOG SENDDATA. id=" + (id & 0xff) + ", items_left=" + items_left + ", total length=" + (length - 9));
break;
case DATALOG_OPENSESSION:
buf.order(ByteOrder.BIG_ENDIAN);
long uuid_high = buf.getLong();
long uuid_low = buf.getLong();
UUID uuid = new UUID(uuid_high, uuid_low);
buf.order(ByteOrder.LITTLE_ENDIAN);
int timestamp = buf.getInt();
int log_tag = buf.getInt();
byte item_type = buf.get();
short item_size = buf.get();
LOG.info("DATALOG OPENSESSION. id=" + (id & 0xff) + ", App UUID=" + uuid.toString() + ", item_type=" + item_type + ", item_size=" + item_size);
break;
default:
LOG.info("unknown DATALOG command: " + (command & 0xff));
break;
}
LOG.info("sending ACK (0x85)");
GBDeviceEventSendBytes sendBytes = new GBDeviceEventSendBytes();
sendBytes.encodedBytes = encodeDatalog(id, DATALOG_ACK);
return sendBytes;
}
@Override
public GBDeviceEvent[] decodeResponse(byte[] responseData) {
ByteBuffer buf = ByteBuffer.wrap(responseData);
buf.order(ByteOrder.BIG_ENDIAN);
short length = buf.getShort();
short endpoint = buf.getShort();
GBDeviceEvent devEvts[] = null;
byte pebbleCmd = -1;
switch (endpoint) {
case ENDPOINT_MUSICCONTROL:
pebbleCmd = buf.get();
GBDeviceEventMusicControl musicCmd = new GBDeviceEventMusicControl();
switch (pebbleCmd) {
case MUSICCONTROL_NEXT:
musicCmd.event = GBDeviceEventMusicControl.Event.NEXT;
break;
case MUSICCONTROL_PREVIOUS:
musicCmd.event = GBDeviceEventMusicControl.Event.PREVIOUS;
break;
case MUSICCONTROL_PLAY:
musicCmd.event = GBDeviceEventMusicControl.Event.PLAY;
break;
case MUSICCONTROL_PAUSE:
musicCmd.event = GBDeviceEventMusicControl.Event.PAUSE;
break;
case MUSICCONTROL_PLAYPAUSE:
musicCmd.event = GBDeviceEventMusicControl.Event.PLAYPAUSE;
break;
case MUSICCONTROL_VOLUMEUP:
musicCmd.event = GBDeviceEventMusicControl.Event.VOLUMEUP;
break;
case MUSICCONTROL_VOLUMEDOWN:
musicCmd.event = GBDeviceEventMusicControl.Event.VOLUMEDOWN;
break;
default:
break;
}
devEvts = new GBDeviceEvent[]{musicCmd};
break;
case ENDPOINT_PHONECONTROL:
pebbleCmd = buf.get();
GBDeviceEventCallControl callCmd = new GBDeviceEventCallControl();
switch (pebbleCmd) {
case PHONECONTROL_HANGUP:
callCmd.event = GBDeviceEventCallControl.Event.END;
break;
default:
LOG.info("Unknown PHONECONTROL event" + pebbleCmd);
break;
}
devEvts = new GBDeviceEvent[]{callCmd};
break;
case ENDPOINT_FIRMWAREVERSION:
pebbleCmd = buf.get();
GBDeviceEventVersionInfo versionCmd = new GBDeviceEventVersionInfo();
buf.getInt(); // skip
byte[] tmp = new byte[32];
buf.get(tmp, 0, 32);
versionCmd.fwVersion = new String(tmp).trim();
if (versionCmd.fwVersion.startsWith("v3")) {
isFw3x = true;
}
buf.get(tmp, 0, 9);
int hwRev = buf.get() + 5;
if (hwRev >= 0 && hwRev < hwRevisions.length) {
versionCmd.hwVersion = hwRevisions[hwRev];
}
devEvts = new GBDeviceEvent[]{versionCmd};
break;
case ENDPOINT_APPMANAGER:
pebbleCmd = buf.get();
switch (pebbleCmd) {
case APPMANAGER_GETAPPBANKSTATUS:
GBDeviceEventAppInfo appInfoCmd = new GBDeviceEventAppInfo();
int slotCount = buf.getInt();
int slotsUsed = buf.getInt();
byte[] appName = new byte[32];
byte[] appCreator = new byte[32];
appInfoCmd.apps = new GBDeviceApp[slotsUsed];
boolean[] slotInUse = new boolean[slotCount];
for (int i = 0; i < slotsUsed; i++) {
int id = buf.getInt();
int index = buf.getInt();
slotInUse[index] = true;
buf.get(appName, 0, 32);
buf.get(appCreator, 0, 32);
int flags = buf.getInt();
GBDeviceApp.Type appType;
if ((flags & 16) == 16) { // FIXME: verify this assumption
appType = GBDeviceApp.Type.APP_ACTIVITYTRACKER;
} else if ((flags & 1) == 1) { // FIXME: verify this assumption
appType = GBDeviceApp.Type.WATCHFACE;
} else {
appType = GBDeviceApp.Type.APP_GENERIC;
}
Short appVersion = buf.getShort();
appInfoCmd.apps[i] = new GBDeviceApp(tmpUUIDS.get(i), new String(appName).trim(), new String(appCreator).trim(), appVersion.toString(), appType);
}
for (int i = 0; i < slotCount; i++) {
if (!slotInUse[i]) {
appInfoCmd.freeSlot = (byte) i;
LOG.info("found free slot " + i);
break;
}
}
devEvts = new GBDeviceEvent[]{appInfoCmd};
break;
case APPMANAGER_GETUUIDS:
GBDeviceEventSendBytes sendBytes = new GBDeviceEventSendBytes();
sendBytes.encodedBytes = encodeSimpleMessage(ENDPOINT_APPMANAGER, APPMANAGER_GETAPPBANKSTATUS);
devEvts = new GBDeviceEvent[]{sendBytes};
tmpUUIDS.clear();
slotsUsed = buf.getInt();
for (int i = 0; i < slotsUsed; i++) {
long uuid_high = buf.getLong();
long uuid_low = buf.getLong();
UUID uuid = new UUID(uuid_high, uuid_low);
LOG.info("found uuid: " + uuid);
tmpUUIDS.add(uuid);
}
break;
case APPMANAGER_REMOVEAPP:
GBDeviceEventAppManagement deleteRes = new GBDeviceEventAppManagement();
deleteRes.type = GBDeviceEventAppManagement.EventType.DELETE;
int result = buf.getInt();
switch (result) {
case APPMANAGER_RES_SUCCESS:
deleteRes.event = GBDeviceEventAppManagement.Event.SUCCESS;
break;
default:
deleteRes.event = GBDeviceEventAppManagement.Event.FAILURE;
break;
}
devEvts = new GBDeviceEvent[]{deleteRes};
break;
default:
LOG.info("Unknown APPMANAGER event" + pebbleCmd);
break;
}
break;
case ENDPOINT_PUTBYTES:
pebbleCmd = buf.get();
GBDeviceEventAppManagement installRes = new GBDeviceEventAppManagement();
installRes.type = GBDeviceEventAppManagement.EventType.INSTALL;
switch (pebbleCmd) {
case PUTBYTES_INIT:
installRes.token = buf.getInt();
installRes.event = GBDeviceEventAppManagement.Event.SUCCESS;
break;
default:
installRes.token = buf.getInt();
installRes.event = GBDeviceEventAppManagement.Event.FAILURE;
break;
}
devEvts = new GBDeviceEvent[]{installRes};
break;
case ENDPOINT_APPLICATIONMESSAGE:
case ENDPOINT_LAUNCHER:
pebbleCmd = buf.get();
last_id = buf.get();
long uuid_high = buf.getLong();
long uuid_low = buf.getLong();
switch (pebbleCmd) {
case APPLICATIONMESSAGE_PUSH:
UUID uuid = new UUID(uuid_high, uuid_low);
if (endpoint == ENDPOINT_LAUNCHER) {
LOG.info("got LAUNCHER PUSH from UUID " + uuid);
break;
}
LOG.info("got APPLICATIONMESSAGE PUSH from UUID " + uuid);
AppMessageHandler handler = mAppMessageHandlers.get(uuid);
if (handler != null) {
ArrayList<Pair<Integer, Object>> dict = decodeDict(buf);
devEvts = handler.handleMessage(dict);
} else {
try {
devEvts = decodeDictToJSONAppMessage(uuid, buf);
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
break;
case APPLICATIONMESSAGE_ACK:
LOG.info("got APPLICATIONMESSAGE/LAUNCHER (EP " + endpoint + ") ACK");
devEvts = new GBDeviceEvent[]{null};
break;
case APPLICATIONMESSAGE_NACK:
LOG.info("got APPLICATIONMESSAGE/LAUNCHER (EP " + endpoint + ") NACK");
devEvts = new GBDeviceEvent[]{null};
break;
case APPLICATIONMESSAGE_REQUEST:
LOG.info("got APPLICATIONMESSAGE/LAUNCHER (EP " + endpoint + ") REQUEST");
devEvts = new GBDeviceEvent[]{null};
break;
default:
break;
}
break;
case ENDPOINT_PHONEVERSION:
pebbleCmd = buf.get();
switch (pebbleCmd) {
case PHONEVERSION_REQUEST:
LOG.info("Pebble asked for Phone/App Version - repLYING!");
GBDeviceEventSendBytes sendBytes = new GBDeviceEventSendBytes();
sendBytes.encodedBytes = encodePhoneVersion(PHONEVERSION_REMOTE_OS_ANDROID);
devEvts = new GBDeviceEvent[]{sendBytes};
break;
default:
break;
}
break;
case ENDPOINT_DATALOG:
devEvts = new GBDeviceEvent[]{decodeDatalog(buf, length)};
break;
case ENDPOINT_SCREENSHOT:
devEvts = new GBDeviceEvent[]{decodeScreenshot(buf, length)};
break;
case ENDPOINT_EXTENSIBLENOTIFS:
case ENDPOINT_NOTIFICATIONACTION:
devEvts = decodeAction(buf);
break;
case ENDPOINT_PING:
devEvts = new GBDeviceEvent[]{decodePing(buf)};
break;
case ENDPOINT_APPFETCH:
devEvts = new GBDeviceEvent[]{decodeAppFetch(buf)};
break;
case ENDPOINT_SYSTEMMESSAGE:
devEvts = new GBDeviceEvent[]{decodeSystemMessage(buf)};
break;
case ENDPOINT_APPRUNSTATE:
devEvts = new GBDeviceEvent[]{decodeAppRunState(buf)};
break;
case ENDPOINT_BLOBDB:
devEvts = new GBDeviceEvent[]{decodeBlobDb(buf)};
break;
default:
break;
}
return devEvts;
}
public void setForceProtocol(boolean force) {
LOG.info("setting force protocol to " + force);
mForceProtocol = force;
}
}
| app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/devices/pebble/PebbleProtocol.java | package nodomain.freeyourgadget.gadgetbridge.service.devices.pebble;
import android.util.Base64;
import android.util.Pair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.SimpleTimeZone;
import java.util.UUID;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEvent;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventAppInfo;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventAppManagement;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventAppMessage;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventCallControl;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventMusicControl;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventNotificationControl;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventScreenshot;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventSendBytes;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventVersionInfo;
import nodomain.freeyourgadget.gadgetbridge.devices.pebble.PebbleColor;
import nodomain.freeyourgadget.gadgetbridge.devices.pebble.PebbleIconID;
import nodomain.freeyourgadget.gadgetbridge.impl.GBDeviceApp;
import nodomain.freeyourgadget.gadgetbridge.model.NotificationSpec;
import nodomain.freeyourgadget.gadgetbridge.model.NotificationType;
import nodomain.freeyourgadget.gadgetbridge.model.ServiceCommand;
import nodomain.freeyourgadget.gadgetbridge.service.serial.GBDeviceProtocol;
public class PebbleProtocol extends GBDeviceProtocol {
private static final Logger LOG = LoggerFactory.getLogger(PebbleProtocol.class);
static final short ENDPOINT_TIME = 11;
static final short ENDPOINT_FIRMWAREVERSION = 16;
public static final short ENDPOINT_PHONEVERSION = 17;
static final short ENDPOINT_SYSTEMMESSAGE = 18;
static final short ENDPOINT_MUSICCONTROL = 32;
static final short ENDPOINT_PHONECONTROL = 33;
static final short ENDPOINT_APPLICATIONMESSAGE = 48;
static final short ENDPOINT_LAUNCHER = 49;
static final short ENDPOINT_APPRUNSTATE = 52; // 3.x only
static final short ENDPOINT_LOGS = 2000;
static final short ENDPOINT_PING = 2001;
static final short ENDPOINT_LOGDUMP = 2002;
static final short ENDPOINT_RESET = 2003;
static final short ENDPOINT_APP = 2004;
static final short ENDPOINT_APPLOGS = 2006;
static final short ENDPOINT_NOTIFICATION = 3000;
static final short ENDPOINT_EXTENSIBLENOTIFS = 3010;
static final short ENDPOINT_RESOURCE = 4000;
static final short ENDPOINT_SYSREG = 5000;
static final short ENDPOINT_FCTREG = 5001;
static final short ENDPOINT_APPMANAGER = 6000;
static final short ENDPOINT_APPFETCH = 6001; // 3.x only
public static final short ENDPOINT_DATALOG = 6778;
static final short ENDPOINT_RUNKEEPER = 7000;
static final short ENDPOINT_SCREENSHOT = 8000;
static final short ENDPOINT_NOTIFICATIONACTION = 11440; // 3.x only, TODO: find a better name
static final short ENDPOINT_BLOBDB = (short) 45531; // 3.x only
static final short ENDPOINT_PUTBYTES = (short) 48879;
static final byte APPRUNSTATE_START = 1;
static final byte APPRUNSTATE_STOP = 2;
static final byte BLOBDB_INSERT = 1;
static final byte BLOBDB_DELETE = 4;
static final byte BLOBDB_CLEAR = 5;
static final byte BLOBDB_PIN = 1;
static final byte BLOBDB_APP = 2;
static final byte BLOBDB_REMINDER = 3;
static final byte BLOBDB_NOTIFICATION = 4;
static final byte BLOBDB_SUCCESS = 1;
static final byte BLOBDB_GENERALFAILURE = 2;
static final byte BLOBDB_INVALIDOPERATION = 3;
static final byte BLOBDB_INVALIDDATABASEID = 4;
static final byte BLOBDB_INVALIDDATA = 5;
static final byte BLOBDB_KEYDOESNOTEXIST = 6;
static final byte BLOBDB_DATABASEFULL = 7;
static final byte BLOBDB_DATASTALE = 8;
// This is not in the Pebble protocol
static final byte NOTIFICATION_UNDEFINED = -1;
static final byte NOTIFICATION_EMAIL = 0;
static final byte NOTIFICATION_SMS = 1;
static final byte NOTIFICATION_TWITTER = 2;
static final byte NOTIFICATION_FACEBOOK = 3;
static final byte PHONECONTROL_ANSWER = 1;
static final byte PHONECONTROL_HANGUP = 2;
static final byte PHONECONTROL_GETSTATE = 3;
static final byte PHONECONTROL_INCOMINGCALL = 4;
static final byte PHONECONTROL_OUTGOINGCALL = 5;
static final byte PHONECONTROL_MISSEDCALL = 6;
static final byte PHONECONTROL_RING = 7;
static final byte PHONECONTROL_START = 8;
static final byte PHONECONTROL_END = 9;
static final byte MUSICCONTROL_SETMUSICINFO = 16;
static final byte MUSICCONTROL_PLAYPAUSE = 1;
static final byte MUSICCONTROL_PAUSE = 2;
static final byte MUSICCONTROL_PLAY = 3;
static final byte MUSICCONTROL_NEXT = 4;
static final byte MUSICCONTROL_PREVIOUS = 5;
static final byte MUSICCONTROL_VOLUMEUP = 6;
static final byte MUSICCONTROL_VOLUMEDOWN = 7;
static final byte MUSICCONTROL_GETNOWPLAYING = 7;
static final byte NOTIFICATIONACTION_ACK = 0;
static final byte NOTIFICATIONACTION_NACK = 1;
static final byte NOTIFICATIONACTION_INVOKE = 0x02;
static final byte NOTIFICATIONACTION_RESPONSE = 0x11;
static final byte TIME_GETTIME = 0;
static final byte TIME_SETTIME = 2;
static final byte TIME_SETTIME_UTC = 3;
static final byte FIRMWAREVERSION_GETVERSION = 0;
static final byte APPMANAGER_GETAPPBANKSTATUS = 1;
static final byte APPMANAGER_REMOVEAPP = 2;
static final byte APPMANAGER_REFRESHAPP = 3;
static final byte APPMANAGER_GETUUIDS = 5;
static final int APPMANAGER_RES_SUCCESS = 1;
static final byte APPLICATIONMESSAGE_PUSH = 1;
static final byte APPLICATIONMESSAGE_REQUEST = 2;
static final byte APPLICATIONMESSAGE_ACK = (byte) 0xff;
static final byte APPLICATIONMESSAGE_NACK = (byte) 0x7f;
static final byte DATALOG_OPENSESSION = 0x01;
static final byte DATALOG_SENDDATA = 0x02;
static final byte DATALOG_CLOSE = 0x03;
static final byte DATALOG_TIMEOUT = 0x07;
static final byte DATALOG_REPORTSESSIONS = (byte) 0x84;
static final byte DATALOG_ACK = (byte) 0x85;
static final byte DATALOG_NACK = (byte) 0x86;
static final byte PING_PING = 0;
static final byte PING_PONG = 1;
static final byte PUTBYTES_INIT = 1;
static final byte PUTBYTES_SEND = 2;
static final byte PUTBYTES_COMMIT = 3;
static final byte PUTBYTES_ABORT = 4;
static final byte PUTBYTES_COMPLETE = 5;
public static final byte PUTBYTES_TYPE_FIRMWARE = 1;
public static final byte PUTBYTES_TYPE_RECOVERY = 2;
public static final byte PUTBYTES_TYPE_SYSRESOURCES = 3;
public static final byte PUTBYTES_TYPE_RESOURCES = 4;
public static final byte PUTBYTES_TYPE_BINARY = 5;
public static final byte PUTBYTES_TYPE_FILE = 6;
public static final byte PUTBYTES_TYPE_WORKER = 7;
static final byte RESET_REBOOT = 0;
static final byte SCREENSHOT_TAKE = 0;
static final byte SYSTEMMESSAGE_NEWFIRMWAREAVAILABLE = 0;
static final byte SYSTEMMESSAGE_FIRMWARESTART = 1;
static final byte SYSTEMMESSAGE_FIRMWARECOMPLETE = 2;
static final byte SYSTEMMESSAGE_FIRMWAREFAIL = 3;
static final byte SYSTEMMESSAGE_FIRMWARE_UPTODATE = 4;
static final byte SYSTEMMESSAGE_FIRMWARE_OUTOFDATE = 5;
static final byte SYSTEMMESSAGE_STOPRECONNECTING = 6;
static final byte SYSTEMMESSAGE_STARTRECONNECTING = 7;
static final byte PHONEVERSION_REQUEST = 0;
static final byte PHONEVERSION_APPVERSION_MAGIC = 2; // increase this if pebble complains
static final byte PHONEVERSION_APPVERSION_MAJOR = 2;
static final byte PHONEVERSION_APPVERSION_MINOR = 3;
static final byte PHONEVERSION_APPVERSION_PATCH = 0;
static final int PHONEVERSION_SESSION_CAPS_GAMMARAY = 0x80000000;
static final int PHONEVERSION_REMOTE_CAPS_TELEPHONY = 0x00000010;
static final int PHONEVERSION_REMOTE_CAPS_SMS = 0x00000020;
static final int PHONEVERSION_REMOTE_CAPS_GPS = 0x00000040;
static final int PHONEVERSION_REMOTE_CAPS_BTLE = 0x00000080;
static final int PHONEVERSION_REMOTE_CAPS_REARCAMERA = 0x00000100;
static final int PHONEVERSION_REMOTE_CAPS_ACCEL = 0x00000200;
static final int PHONEVERSION_REMOTE_CAPS_GYRO = 0x00000400;
static final int PHONEVERSION_REMOTE_CAPS_COMPASS = 0x00000800;
static final byte PHONEVERSION_REMOTE_OS_UNKNOWN = 0;
static final byte PHONEVERSION_REMOTE_OS_IOS = 1;
static final byte PHONEVERSION_REMOTE_OS_ANDROID = 2;
static final byte PHONEVERSION_REMOTE_OS_OSX = 3;
static final byte PHONEVERSION_REMOTE_OS_LINUX = 4;
static final byte PHONEVERSION_REMOTE_OS_WINDOWS = 5;
static final byte TYPE_BYTEARRAY = 0;
static final byte TYPE_CSTRING = 1;
static final byte TYPE_UINT = 2;
static final byte TYPE_INT = 3;
static final short LENGTH_PREFIX = 4;
static final short LENGTH_SIMPLEMESSAGE = 1;
static final short LENGTH_APPFETCH = 2;
static final short LENGTH_APPRUNSTATE = 17;
static final short LENGTH_BLOBDB = 21;
static final short LENGTH_PING = 5;
static final short LENGTH_PHONEVERSION = 17;
static final short LENGTH_REMOVEAPP_2X = 17;
static final short LENGTH_REFRESHAPP = 5;
static final short LENGTH_SETTIME = 5;
static final short LENGTH_SYSTEMMESSAGE = 2;
static final short LENGTH_UPLOADSTART_2X = 7;
static final short LENGTH_UPLOADSTART_3X = 10;
static final short LENGTH_UPLOADCHUNK = 9;
static final short LENGTH_UPLOADCOMMIT = 9;
static final short LENGTH_UPLOADCOMPLETE = 5;
static final short LENGTH_UPLOADCANCEL = 5;
static final byte LENGTH_UUID = 16;
// base is -5
private static final String[] hwRevisions = {
// Emulator
"spalding_bb2", "snowy_bb2", "snowy_bb", "bb2", "bb",
"unknown",
// Pebble
"ev1", "ev2", "ev2_3", "ev2_4", "v1_5", "v2_0",
// Pebble Time
"snowy_evt2", "snowy_dvt", "spalding_dvt", "snowy_s3", "spalding"
};
private static final Random mRandom = new Random();
boolean isFw3x = false;
boolean mForceProtocol = false;
GBDeviceEventScreenshot mDevEventScreenshot = null;
int mScreenshotRemaining = -1;
//monochrome black + white
static final byte[] clut_pebble = {
0x00, 0x00, 0x00, 0x00,
(byte) 0xff, (byte) 0xff, (byte) 0xff, 0x00
};
// linear BGR222 (6 bit, 64 entries)
static final byte[] clut_pebbletime = new byte[]{
0x00, 0x00, 0x00, 0x00,
0x55, 0x00, 0x00, 0x00,
(byte) 0xaa, 0x00, 0x00, 0x00,
(byte) 0xff, 0x00, 0x00, 0x00,
0x00, 0x55, 0x00, 0x00,
0x55, 0x55, 0x00, 0x00,
(byte) 0xaa, 0x55, 0x00, 0x00,
(byte) 0xff, 0x55, 0x00, 0x00,
0x00, (byte) 0xaa, 0x00, 0x00,
0x55, (byte) 0xaa, 0x00, 0x00,
(byte) 0xaa, (byte) 0xaa, 0x00, 0x00,
(byte) 0xff, (byte) 0xaa, 0x00, 0x00,
0x00, (byte) 0xff, 0x00, 0x00,
0x55, (byte) 0xff, 0x00, 0x00,
(byte) 0xaa, (byte) 0xff, 0x00, 0x00,
(byte) 0xff, (byte) 0xff, 0x00, 0x00,
0x00, 0x00, 0x55, 0x00,
0x55, 0x00, 0x55, 0x00,
(byte) 0xaa, 0x00, 0x55, 0x00,
(byte) 0xff, 0x00, 0x55, 0x00,
0x00, 0x55, 0x55, 0x00,
0x55, 0x55, 0x55, 0x00,
(byte) 0xaa, 0x55, 0x55, 0x00,
(byte) 0xff, 0x55, 0x55, 0x00,
0x00, (byte) 0xaa, 0x55, 0x00,
0x55, (byte) 0xaa, 0x55, 0x00,
(byte) 0xaa, (byte) 0xaa, 0x55, 0x00,
(byte) 0xff, (byte) 0xaa, 0x55, 0x00,
0x00, (byte) 0xff, 0x55, 0x00,
0x55, (byte) 0xff, 0x55, 0x00,
(byte) 0xaa, (byte) 0xff, 0x55, 0x00,
(byte) 0xff, (byte) 0xff, 0x55, 0x00,
0x00, 0x00, (byte) 0xaa, 0x00,
0x55, 0x00, (byte) 0xaa, 0x00,
(byte) 0xaa, 0x00, (byte) 0xaa, 0x00,
(byte) 0xff, 0x00, (byte) 0xaa, 0x00,
0x00, 0x55, (byte) 0xaa, 0x00,
0x55, 0x55, (byte) 0xaa, 0x00,
(byte) 0xaa, 0x55, (byte) 0xaa, 0x00,
(byte) 0xff, 0x55, (byte) 0xaa, 0x00,
0x00, (byte) 0xaa, (byte) 0xaa, 0x00,
0x55, (byte) 0xaa, (byte) 0xaa, 0x00,
(byte) 0xaa, (byte) 0xaa, (byte) 0xaa, 0x00,
(byte) 0xff, (byte) 0xaa, (byte) 0xaa, 0x00,
0x00, (byte) 0xff, (byte) 0xaa, 0x00,
0x55, (byte) 0xff, (byte) 0xaa, 0x00,
(byte) 0xaa, (byte) 0xff, (byte) 0xaa, 0x00,
(byte) 0xff, (byte) 0xff, (byte) 0xaa, 0x00,
0x00, 0x00, (byte) 0xff, 0x00,
0x55, 0x00, (byte) 0xff, 0x00,
(byte) 0xaa, 0x00, (byte) 0xff, 0x00,
(byte) 0xff, 0x00, (byte) 0xff, 0x00,
0x00, 0x55, (byte) 0xff, 0x00,
0x55, 0x55, (byte) 0xff, 0x00,
(byte) 0xaa, 0x55, (byte) 0xff, 0x00,
(byte) 0xff, 0x55, (byte) 0xff, 0x00,
0x00, (byte) 0xaa, (byte) 0xff, 0x00,
0x55, (byte) 0xaa, (byte) 0xff, 0x00,
(byte) 0xaa, (byte) 0xaa, (byte) 0xff, 0x00,
(byte) 0xff, (byte) 0xaa, (byte) 0xff, 0x00,
0x00, (byte) 0xff, (byte) 0xff, 0x00,
0x55, (byte) 0xff, (byte) 0xff, 0x00,
(byte) 0xaa, (byte) 0xff, (byte) 0xff, 0x00,
(byte) 0xff, (byte) 0xff, (byte) 0xff, 0x00,
};
byte last_id = -1;
private final ArrayList<UUID> tmpUUIDS = new ArrayList<>();
private static final UUID UUID_GBPEBBLE = UUID.fromString("61476764-7465-7262-6469-656775527a6c");
private static final UUID UUID_MORPHEUZ = UUID.fromString("5be44f1d-d262-4ea6-aa30-ddbec1e3cab2");
private static final UUID UUID_WHETHERNEAT = UUID.fromString("3684003b-a685-45f9-a713-abc6364ba051");
private static final UUID UUID_MISFIT = UUID.fromString("0b73b76a-cd65-4dc2-9585-aaa213320858");
private static final UUID UUID_PEBBLE_HEALTH = UUID.fromString("36d8c6ed-4c83-4fa1-a9e2-8f12dc941f8c");
private static final UUID UUID_PEBBLE_TIMESTYLE = UUID.fromString("4368ffa4-f0fb-4823-90be-f754b076bdaa");
private static final UUID UUID_PEBSTYLE = UUID.fromString("da05e84d-e2a2-4020-a2dc-9cdcf265fcdd");
private static final Map<UUID, AppMessageHandler> mAppMessageHandlers = new HashMap<>();
{
mAppMessageHandlers.put(UUID_GBPEBBLE, new AppMessageHandlerGBPebble(UUID_GBPEBBLE, PebbleProtocol.this));
mAppMessageHandlers.put(UUID_MORPHEUZ, new AppMessageHandlerMorpheuz(UUID_MORPHEUZ, PebbleProtocol.this));
mAppMessageHandlers.put(UUID_WHETHERNEAT, new AppMessageHandlerWeatherNeat(UUID_WHETHERNEAT, PebbleProtocol.this));
mAppMessageHandlers.put(UUID_MISFIT, new AppMessageHandlerMisfit(UUID_MISFIT, PebbleProtocol.this));
mAppMessageHandlers.put(UUID_PEBBLE_TIMESTYLE, new AppMessageHandlerTimeStylePebble(UUID_PEBBLE_TIMESTYLE, PebbleProtocol.this));
mAppMessageHandlers.put(UUID_PEBSTYLE, new AppMessageHandlerPebStyle(UUID_PEBSTYLE, PebbleProtocol.this));
}
private static byte[] encodeSimpleMessage(short endpoint, byte command) {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_SIMPLEMESSAGE);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_SIMPLEMESSAGE);
buf.putShort(endpoint);
buf.put(command);
return buf.array();
}
private static byte[] encodeMessage(short endpoint, byte type, int cookie, String[] parts) {
// Calculate length first
int length = LENGTH_PREFIX + 1;
if (parts != null) {
for (String s : parts) {
if (s == null || s.equals("")) {
length++; // encode null or empty strings as 0x00 later
continue;
}
length += (1 + s.getBytes().length);
}
}
if (endpoint == ENDPOINT_PHONECONTROL) {
length += 4; //for cookie;
}
// Encode Prefix
ByteBuffer buf = ByteBuffer.allocate(length);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort((short) (length - LENGTH_PREFIX));
buf.putShort(endpoint);
buf.put(type);
if (endpoint == ENDPOINT_PHONECONTROL) {
buf.putInt(cookie);
}
// Encode Pascal-Style Strings
if (parts != null) {
for (String s : parts) {
if (s == null || s.equals("")) {
//buf.put((byte)0x01);
buf.put((byte) 0x00);
continue;
}
int partlength = s.getBytes().length;
if (partlength > 255) partlength = 255;
buf.put((byte) partlength);
buf.put(s.getBytes(), 0, partlength);
}
}
return buf.array();
}
@Override
public byte[] encodeNotification(NotificationSpec notificationSpec) {
boolean hasHandle = notificationSpec.id != -1 && notificationSpec.phoneNumber == null;
int id = notificationSpec.id != -1 ? notificationSpec.id : mRandom.nextInt();
String title;
String subtitle = null;
// for SMS and EMAIL that came in though SMS or K9 receiver
if (notificationSpec.sender != null) {
title = notificationSpec.sender;
subtitle = notificationSpec.subject;
} else {
title = notificationSpec.title;
}
Long ts = System.currentTimeMillis();
if (!isFw3x) {
ts += (SimpleTimeZone.getDefault().getOffset(ts));
}
ts /= 1000;
if (isFw3x) {
// 3.x notification
//return encodeTimelinePin(id, (int) ((ts + 600) & 0xffffffffL), (short) 90, PebbleIconID.TIMELINE_CALENDAR, title); // really, this is just for testing
return encodeBlobdbNotification(id, (int) (ts & 0xffffffffL), title, subtitle, notificationSpec.body, notificationSpec.sourceName, hasHandle, notificationSpec.type, notificationSpec.cannedReplies);
} else if (mForceProtocol || notificationSpec.type != NotificationType.EMAIL) {
// 2.x notification
return encodeExtensibleNotification(id, (int) (ts & 0xffffffffL), title, subtitle, notificationSpec.body, notificationSpec.sourceName, hasHandle, notificationSpec.cannedReplies);
} else {
// 1.x notification on FW 2.X
String[] parts = {title, notificationSpec.body, ts.toString(), subtitle};
// be aware that type is at this point always NOTIFICATION_EMAIL
return encodeMessage(ENDPOINT_NOTIFICATION, NOTIFICATION_EMAIL, 0, parts);
}
}
@Override
public byte[] encodeSetTime() {
long ts = System.currentTimeMillis();
long ts_offset = (SimpleTimeZone.getDefault().getOffset(ts));
ByteBuffer buf;
if (isFw3x) {
String timezone = SimpleTimeZone.getDefault().getID();
short length = (short) (LENGTH_SETTIME + timezone.getBytes().length + 3);
buf = ByteBuffer.allocate(LENGTH_PREFIX + length);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(length);
buf.putShort(ENDPOINT_TIME);
buf.put(TIME_SETTIME_UTC);
buf.putInt((int) (ts / 1000));
buf.putShort((short) (ts_offset / 60000));
buf.put((byte) timezone.getBytes().length);
buf.put(timezone.getBytes());
LOG.info(timezone);
} else {
buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_SETTIME);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_SETTIME);
buf.putShort(ENDPOINT_TIME);
buf.put(TIME_SETTIME);
buf.putInt((int) ((ts + ts_offset) / 1000));
}
return buf.array();
}
@Override
public byte[] encodeFindDevice(boolean start) {
return encodeSetCallState("Where are you?", "Gadgetbridge", start ? ServiceCommand.CALL_INCOMING : ServiceCommand.CALL_END);
}
private static byte[] encodeExtensibleNotification(int id, int timestamp, String title, String subtitle, String body, String sourceName, boolean hasHandle, String[] cannedReplies) {
final short ACTION_LENGTH_MIN = 10;
String[] parts = {title, subtitle, body};
// Calculate length first
byte actions_count;
short actions_length;
String dismiss_string;
String open_string = "Open on phone";
String mute_string = "Mute";
String reply_string = "Reply";
if (sourceName != null) {
mute_string += " " + sourceName;
}
byte dismiss_action_id;
if (hasHandle) {
actions_count = 3;
dismiss_string = "Dismiss";
dismiss_action_id = 0x02;
actions_length = (short) (ACTION_LENGTH_MIN * actions_count + dismiss_string.getBytes().length + open_string.getBytes().length + mute_string.getBytes().length);
} else {
actions_count = 1;
dismiss_string = "Dismiss all";
dismiss_action_id = 0x03;
actions_length = (short) (ACTION_LENGTH_MIN * actions_count + dismiss_string.getBytes().length);
}
int replies_length = -1;
if (cannedReplies != null && cannedReplies.length > 0) {
actions_count++;
for (String reply : cannedReplies) {
replies_length += reply.getBytes().length + 1;
}
actions_length += ACTION_LENGTH_MIN + reply_string.getBytes().length + replies_length + 3; // 3 = attribute id (byte) + length(short)
}
byte attributes_count = 0;
int length = 21 + 10 + actions_length;
if (parts != null) {
for (String s : parts) {
if (s == null || s.equals("")) {
continue;
}
attributes_count++;
length += (3 + s.getBytes().length);
}
}
// Encode Prefix
ByteBuffer buf = ByteBuffer.allocate(length + LENGTH_PREFIX);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort((short) (length));
buf.putShort(ENDPOINT_EXTENSIBLENOTIFS);
buf.order(ByteOrder.LITTLE_ENDIAN); // !
buf.put((byte) 0x00); // ?
buf.put((byte) 0x01); // add notifications
buf.putInt(0x00000000); // flags - ?
buf.putInt(id);
buf.putInt(0x00000000); // ANCS id
buf.putInt(timestamp);
buf.put((byte) 0x01); // layout - ?
buf.put(attributes_count);
buf.put(actions_count);
byte attribute_id = 0;
// Encode Pascal-Style Strings
if (parts != null) {
for (String s : parts) {
attribute_id++;
if (s == null || s.equals("")) {
continue;
}
int partlength = s.getBytes().length;
if (partlength > 255) partlength = 255;
buf.put(attribute_id);
buf.putShort((short) partlength);
buf.put(s.getBytes(), 0, partlength);
}
}
// dismiss action
buf.put(dismiss_action_id);
buf.put((byte) 0x04); // dismiss
buf.put((byte) 0x01); // number attributes
buf.put((byte) 0x01); // attribute id (title)
buf.putShort((short) dismiss_string.getBytes().length);
buf.put(dismiss_string.getBytes());
// open and mute actions
if (hasHandle) {
buf.put((byte) 0x01);
buf.put((byte) 0x02); // generic
buf.put((byte) 0x01); // number attributes
buf.put((byte) 0x01); // attribute id (title)
buf.putShort((short) open_string.getBytes().length);
buf.put(open_string.getBytes());
buf.put((byte) 0x04);
buf.put((byte) 0x02); // generic
buf.put((byte) 0x01); // number attributes
buf.put((byte) 0x01); // attribute id (title)
buf.putShort((short) mute_string.getBytes().length);
buf.put(mute_string.getBytes());
}
if (cannedReplies != null && replies_length > 0) {
buf.put((byte) 0x05);
buf.put((byte) 0x03); // reply action
buf.put((byte) 0x02); // number attributes
buf.put((byte) 0x01); // title
buf.putShort((short) reply_string.getBytes().length);
buf.put(reply_string.getBytes());
buf.put((byte) 0x08); // canned replies
buf.putShort((short) replies_length);
for (int i = 0; i < cannedReplies.length - 1; i++) {
buf.put(cannedReplies[i].getBytes());
buf.put((byte) 0x00);
}
// last one must not be zero terminated, else we get an additional emply reply
buf.put(cannedReplies[cannedReplies.length - 1].getBytes());
}
return buf.array();
}
private byte[] encodeBlobdb(UUID uuid, byte command, byte db, byte[] blob) {
int length = LENGTH_BLOBDB;
if (blob != null) {
length += blob.length + 2;
}
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + length);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort((short) length);
buf.putShort(ENDPOINT_BLOBDB);
buf.order(ByteOrder.LITTLE_ENDIAN);
buf.put(command);
buf.putShort((short) mRandom.nextInt()); // token
buf.put(db);
buf.put(LENGTH_UUID);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putLong(uuid.getMostSignificantBits());
buf.putLong(uuid.getLeastSignificantBits());
buf.order(ByteOrder.LITTLE_ENDIAN);
if (blob != null) {
buf.putShort((short) blob.length);
buf.put(blob);
}
return buf.array();
}
private byte[] encodeBlobDBClear(byte database) {
final short LENGTH_BLOBDB_CLEAR = 4;
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_BLOBDB_CLEAR);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_BLOBDB_CLEAR);
buf.putShort(ENDPOINT_BLOBDB);
buf.order(ByteOrder.LITTLE_ENDIAN);
buf.put(BLOBDB_CLEAR);
buf.putShort((short) mRandom.nextInt()); // token
buf.put(database);
return buf.array();
}
private byte[] encodeTimelinePin(int id, int timestamp, short duration, int icon_id, String title, String subtitle) {
final short TIMELINE_PIN_LENGTH = 46;
icon_id |= 0x80000000;
UUID uuid = new UUID(mRandom.nextLong(), ((long) mRandom.nextInt() << 32) | id);
byte attributes_count = 2;
byte actions_count = 0;
int attributes_length = 10 + title.getBytes().length;
if (subtitle != null && !subtitle.isEmpty()) {
attributes_length += 3 + subtitle.getBytes().length;
attributes_count += 1;
}
int pin_length = TIMELINE_PIN_LENGTH + attributes_length;
ByteBuffer buf = ByteBuffer.allocate(pin_length);
// pin - 46 bytes
buf.order(ByteOrder.BIG_ENDIAN);
buf.putLong(uuid.getMostSignificantBits());
buf.putLong(uuid.getLeastSignificantBits());
buf.putLong(0); // parent
buf.putLong(0);
buf.order(ByteOrder.LITTLE_ENDIAN);
buf.putInt(timestamp); // 32-bit timestamp
buf.putShort(duration);
buf.put((byte) 0x02); // type (0x02 = pin)
buf.putShort((short) 0x0001); // flags 0x0001 = ?
buf.put((byte) 0x01); // layout was (0x02 = pin?), 0x01 needed for subtitle aber seems to do no harm if there isn't one
buf.putShort((short) attributes_length); // total length of all attributes and actions in bytes
buf.put(attributes_count);
buf.put(actions_count);
buf.put((byte) 4); // icon
buf.putShort((short) 4); // length of int
buf.putInt(icon_id);
buf.put((byte) 1); // title
buf.putShort((short) title.getBytes().length);
buf.put(title.getBytes());
if (subtitle != null && !subtitle.isEmpty()) {
buf.put((byte) 2); //subtitle
buf.putShort((short) subtitle.getBytes().length);
buf.put(subtitle.getBytes());
}
return encodeBlobdb(uuid, BLOBDB_INSERT, BLOBDB_PIN, buf.array());
}
private byte[] encodeBlobdbNotification(int id, int timestamp, String title, String subtitle, String body, String sourceName, boolean hasHandle, NotificationType notificationType, String[] cannedReplies) {
final short NOTIFICATION_PIN_LENGTH = 46;
final short ACTION_LENGTH_MIN = 10;
String[] parts = {title, subtitle, body};
int icon_id;
byte color_id;
switch (notificationType) {
case EMAIL:
icon_id = PebbleIconID.GENERIC_EMAIL;
color_id = PebbleColor.JaegerGreen;
break;
case SMS:
icon_id = PebbleIconID.GENERIC_SMS;
color_id = PebbleColor.VividViolet;
break;
default:
switch (notificationType) {
case TWITTER:
icon_id = PebbleIconID.NOTIFICATION_TWITTER;
color_id = PebbleColor.BlueMoon;
break;
case EMAIL:
icon_id = PebbleIconID.GENERIC_EMAIL;
color_id = PebbleColor.JaegerGreen;
break;
case SMS:
icon_id = PebbleIconID.GENERIC_SMS;
color_id = PebbleColor.VividViolet;
break;
case FACEBOOK:
icon_id = PebbleIconID.NOTIFICATION_FACEBOOK;
color_id = PebbleColor.VeryLightBlue;
break;
case CHAT:
icon_id = PebbleIconID.NOTIFICATION_HIPCHAT;
color_id = PebbleColor.Inchworm;
break;
default:
icon_id = PebbleIconID.NOTIFICATION_GENERIC;
color_id = PebbleColor.Red;
break;
}
break;
}
// Calculate length first
byte actions_count;
short actions_length;
String dismiss_string;
String open_string = "Open on phone";
String mute_string = "Mute";
String reply_string = "Reply";
if (sourceName != null) {
mute_string += " " + sourceName;
}
byte dismiss_action_id;
if (hasHandle) {
actions_count = 3;
dismiss_string = "Dismiss";
dismiss_action_id = 0x02;
actions_length = (short) (ACTION_LENGTH_MIN * actions_count + dismiss_string.getBytes().length + open_string.getBytes().length + mute_string.getBytes().length);
} else {
actions_count = 1;
dismiss_string = "Dismiss all";
dismiss_action_id = 0x03;
actions_length = (short) (ACTION_LENGTH_MIN * actions_count + dismiss_string.getBytes().length);
}
int replies_length = -1;
if (cannedReplies != null && cannedReplies.length > 0) {
actions_count++;
for (String reply : cannedReplies) {
replies_length += reply.getBytes().length + 1;
}
actions_length += ACTION_LENGTH_MIN + reply_string.getBytes().length + replies_length + 3; // 3 = attribute id (byte) + length(short)
}
byte attributes_count = 2; // icon
short attributes_length = (short) (11 + actions_length);
if (parts != null) {
for (String s : parts) {
if (s == null || s.equals("")) {
continue;
}
attributes_count++;
attributes_length += (3 + s.getBytes().length);
}
}
UUID uuid = UUID.randomUUID();
short pin_length = (short) (NOTIFICATION_PIN_LENGTH + attributes_length);
ByteBuffer buf = ByteBuffer.allocate(pin_length);
// pin - 46 bytes
buf.order(ByteOrder.BIG_ENDIAN);
buf.putLong(uuid.getMostSignificantBits());
buf.putInt((int) (uuid.getLeastSignificantBits() >>> 32));
buf.putInt(id);
buf.putLong(uuid.getMostSignificantBits());
buf.putInt((int) (uuid.getLeastSignificantBits() >>> 32));
buf.putInt(id);
buf.order(ByteOrder.LITTLE_ENDIAN);
buf.putInt(timestamp); // 32-bit timestamp
buf.putShort((short) 0); // duration
buf.put((byte) 0x01); // type (0x01 = notification)
buf.putShort((short) 0x0001); // flags 0x0001 = ?
buf.put((byte) 0x04); // layout (0x04 = notification?)
buf.putShort(attributes_length); // total length of all attributes and actions in bytes
buf.put(attributes_count);
buf.put(actions_count);
byte attribute_id = 0;
// Encode Pascal-Style Strings
if (parts != null) {
for (String s : parts) {
attribute_id++;
if (s == null || s.equals("")) {
continue;
}
int partlength = s.getBytes().length;
if (partlength > 512) partlength = 512;
buf.put(attribute_id);
buf.putShort((short) partlength);
buf.put(s.getBytes(), 0, partlength);
}
}
buf.put((byte) 4); // icon
buf.putShort((short) 4); // length of int
buf.putInt(0x80000000 | icon_id);
buf.put((byte) 28); // background_color
buf.putShort((short) 1); // length of int
buf.put(color_id);
// dismiss action
buf.put(dismiss_action_id);
buf.put((byte) 0x02); // generic action, dismiss did not do anything
buf.put((byte) 0x01); // number attributes
buf.put((byte) 0x01); // attribute id (title)
buf.putShort((short) dismiss_string.getBytes().length);
buf.put(dismiss_string.getBytes());
// open and mute actions
if (hasHandle) {
buf.put((byte) 0x01);
buf.put((byte) 0x02); // generic action
buf.put((byte) 0x01); // number attributes
buf.put((byte) 0x01); // attribute id (title)
buf.putShort((short) open_string.getBytes().length);
buf.put(open_string.getBytes());
buf.put((byte) 0x04);
buf.put((byte) 0x02); // generic action
buf.put((byte) 0x01); // number attributes
buf.put((byte) 0x01); // attribute id (title)
buf.putShort((short) mute_string.getBytes().length);
buf.put(mute_string.getBytes());
}
if (cannedReplies != null && replies_length > 0) {
buf.put((byte) 0x05);
buf.put((byte) 0x03); // reply action
buf.put((byte) 0x02); // number attributes
buf.put((byte) 0x01); // title
buf.putShort((short) reply_string.getBytes().length);
buf.put(reply_string.getBytes());
buf.put((byte) 0x08); // canned replies
buf.putShort((short) replies_length);
for (int i = 0; i < cannedReplies.length - 1; i++) {
buf.put(cannedReplies[i].getBytes());
buf.put((byte) 0x00);
}
// last one must not be zero terminated, else we get an additional emply reply
buf.put(cannedReplies[cannedReplies.length - 1].getBytes());
}
return encodeBlobdb(UUID.randomUUID(), BLOBDB_INSERT, BLOBDB_NOTIFICATION, buf.array());
}
public byte[] encodeActionResponse2x(int id, byte actionId, int iconId, String caption) {
short length = (short) (18 + caption.getBytes().length);
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + length);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(length);
buf.putShort(ENDPOINT_EXTENSIBLENOTIFS);
buf.order(ByteOrder.LITTLE_ENDIAN);
buf.put(NOTIFICATIONACTION_RESPONSE);
buf.putInt(id);
buf.put(actionId);
buf.put(NOTIFICATIONACTION_ACK);
buf.put((byte) 2); //nr of attributes
buf.put((byte) 6); // icon
buf.putShort((short) 4); // length
buf.putInt(iconId);
buf.put((byte) 2); // title
buf.putShort((short) caption.getBytes().length);
buf.put(caption.getBytes());
return buf.array();
}
public byte[] encodeActionResponse(UUID uuid, int iconId, String caption) {
short length = (short) (29 + caption.getBytes().length);
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + length);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(length);
buf.putShort(ENDPOINT_NOTIFICATIONACTION);
buf.put(NOTIFICATIONACTION_RESPONSE);
buf.putLong(uuid.getMostSignificantBits());
buf.putLong(uuid.getLeastSignificantBits());
buf.order(ByteOrder.LITTLE_ENDIAN);
buf.put(NOTIFICATIONACTION_ACK);
buf.put((byte) 2); //nr of attributes
buf.put((byte) 6); // icon
buf.putShort((short) 4); // length
buf.putInt(0x80000000 | iconId);
buf.put((byte) 2); // title
buf.putShort((short) caption.getBytes().length);
buf.put(caption.getBytes());
return buf.array();
}
public byte[] encodeInstallMetadata(UUID uuid, String appName, short appVersion, short sdkVersion, int flags, int iconId) {
final short METADATA_LENGTH = 126;
byte[] name_buf = new byte[96];
System.arraycopy(appName.getBytes(), 0, name_buf, 0, appName.getBytes().length);
ByteBuffer buf = ByteBuffer.allocate(METADATA_LENGTH);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putLong(uuid.getMostSignificantBits()); // watchapp uuid
buf.putLong(uuid.getLeastSignificantBits());
buf.order(ByteOrder.LITTLE_ENDIAN);
buf.putInt(flags);
buf.putInt(iconId);
buf.putShort(appVersion);
buf.putShort(sdkVersion);
buf.put((byte) 0); // app_face_bgcolor
buf.put((byte) 0); // app_face_template_id
buf.put(name_buf); // 96 bytes
return encodeBlobdb(uuid, BLOBDB_INSERT, BLOBDB_APP, buf.array());
}
public byte[] encodeAppFetchAck() {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_APPFETCH);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_APPFETCH);
buf.putShort(ENDPOINT_APPFETCH);
buf.put((byte) 0x01);
buf.put((byte) 0x01);
return buf.array();
}
public byte[] encodeGetTime() {
return encodeSimpleMessage(ENDPOINT_TIME, TIME_GETTIME);
}
@Override
public byte[] encodeSetCallState(String number, String name, ServiceCommand command) {
String[] parts = {number, name};
byte pebbleCmd;
switch (command) {
case CALL_START:
pebbleCmd = PHONECONTROL_START;
break;
case CALL_END:
pebbleCmd = PHONECONTROL_END;
break;
case CALL_INCOMING:
pebbleCmd = PHONECONTROL_INCOMINGCALL;
break;
case CALL_OUTGOING:
// pebbleCmd = PHONECONTROL_OUTGOINGCALL;
/*
* HACK/WORKAROUND for non-working outgoing call display.
* Just send a incoming call command immediately followed by a start call command
* This prevents vibration of the Pebble.
*/
byte[] callmsg = encodeMessage(ENDPOINT_PHONECONTROL, PHONECONTROL_INCOMINGCALL, 0, parts);
byte[] startmsg = encodeMessage(ENDPOINT_PHONECONTROL, PHONECONTROL_START, 0, parts);
byte[] msg = new byte[callmsg.length + startmsg.length];
System.arraycopy(callmsg, 0, msg, 0, callmsg.length);
System.arraycopy(startmsg, 0, msg, startmsg.length, startmsg.length);
return msg;
// END HACK
default:
return null;
}
return encodeMessage(ENDPOINT_PHONECONTROL, pebbleCmd, 0, parts);
}
@Override
public byte[] encodeSetMusicInfo(String artist, String album, String track) {
String[] parts = {artist, album, track};
return encodeMessage(ENDPOINT_MUSICCONTROL, MUSICCONTROL_SETMUSICINFO, 0, parts);
}
@Override
public byte[] encodeFirmwareVersionReq() {
return encodeSimpleMessage(ENDPOINT_FIRMWAREVERSION, FIRMWAREVERSION_GETVERSION);
}
@Override
public byte[] encodeAppInfoReq() {
if (isFw3x) {
return null; // can't do this on 3.x :(
}
return encodeSimpleMessage(ENDPOINT_APPMANAGER, APPMANAGER_GETUUIDS);
}
@Override
public byte[] encodeAppStart(UUID uuid, boolean start) {
if (isFw3x) {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_APPRUNSTATE);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_APPRUNSTATE);
buf.putShort(ENDPOINT_APPRUNSTATE);
buf.put(start ? APPRUNSTATE_START : APPRUNSTATE_STOP);
buf.putLong(uuid.getMostSignificantBits());
buf.putLong(uuid.getLeastSignificantBits());
return buf.array();
} else {
ArrayList<Pair<Integer, Object>> pairs = new ArrayList<>();
int param = start ? 1 : 0;
pairs.add(new Pair<>(1, (Object) param));
return encodeApplicationMessagePush(ENDPOINT_LAUNCHER, uuid, pairs);
}
}
@Override
public byte[] encodeAppDelete(UUID uuid) {
if (isFw3x) {
return encodeBlobdb(uuid, BLOBDB_DELETE, BLOBDB_APP, null);
} else {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_REMOVEAPP_2X);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_REMOVEAPP_2X);
buf.putShort(ENDPOINT_APPMANAGER);
buf.put(APPMANAGER_REMOVEAPP);
buf.putLong(uuid.getMostSignificantBits());
buf.putLong(uuid.getLeastSignificantBits());
return buf.array();
}
}
private byte[] encodePhoneVersion2x(byte os) {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_PHONEVERSION);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_PHONEVERSION);
buf.putShort(ENDPOINT_PHONEVERSION);
buf.put((byte) 0x01);
buf.putInt(-1); //0xffffffff
if (os == PHONEVERSION_REMOTE_OS_ANDROID) {
buf.putInt(PHONEVERSION_SESSION_CAPS_GAMMARAY);
} else {
buf.putInt(0);
}
buf.putInt(PHONEVERSION_REMOTE_CAPS_SMS | PHONEVERSION_REMOTE_CAPS_TELEPHONY | os);
buf.put(PHONEVERSION_APPVERSION_MAGIC);
buf.put(PHONEVERSION_APPVERSION_MAJOR);
buf.put(PHONEVERSION_APPVERSION_MINOR);
buf.put(PHONEVERSION_APPVERSION_PATCH);
return buf.array();
}
private byte[] encodePhoneVersion3x(byte os) {
final short LENGTH_PHONEVERSION3X = 25;
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_PHONEVERSION3X);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_PHONEVERSION3X);
buf.putShort(ENDPOINT_PHONEVERSION);
buf.put((byte) 0x01);
buf.putInt(-1); //0xffffffff
buf.putInt(0);
buf.putInt(os);
buf.put(PHONEVERSION_APPVERSION_MAGIC);
buf.put((byte) 3); // major
buf.put((byte) 8); // minor
buf.put((byte) 1); // patch
buf.order(ByteOrder.LITTLE_ENDIAN);
buf.putLong(0x00000000000000af); //flags
return buf.array();
}
public byte[] encodePhoneVersion(byte os) {
return encodePhoneVersion3x(os);
}
@Override
public byte[] encodeReboot() {
return encodeSimpleMessage(ENDPOINT_RESET, RESET_REBOOT);
}
@Override
public byte[] encodeScreenshotReq() {
return encodeSimpleMessage(ENDPOINT_SCREENSHOT, SCREENSHOT_TAKE);
}
/* pebble specific install methods */
public byte[] encodeUploadStart(byte type, int app_id, int size, String filename) {
short length;
if (isFw3x && (type != PUTBYTES_TYPE_FILE)) {
length = LENGTH_UPLOADSTART_3X;
type |= 0b10000000;
} else {
length = LENGTH_UPLOADSTART_2X;
}
if (type == PUTBYTES_TYPE_FILE && filename != null) {
length += filename.getBytes().length + 1;
}
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + length);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(length);
buf.putShort(ENDPOINT_PUTBYTES);
buf.put(PUTBYTES_INIT);
buf.putInt(size);
buf.put(type);
if (isFw3x && (type != PUTBYTES_TYPE_FILE)) {
buf.putInt(app_id);
} else {
// slot
buf.put((byte) app_id);
}
if (type == PUTBYTES_TYPE_FILE && filename != null) {
buf.put(filename.getBytes());
buf.put((byte) 0);
}
return buf.array();
}
public byte[] encodeUploadChunk(int token, byte[] buffer, int size) {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_UPLOADCHUNK + size);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort((short) (LENGTH_UPLOADCHUNK + size));
buf.putShort(ENDPOINT_PUTBYTES);
buf.put(PUTBYTES_SEND);
buf.putInt(token);
buf.putInt(size);
buf.put(buffer, 0, size);
return buf.array();
}
public byte[] encodeUploadCommit(int token, int crc) {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_UPLOADCOMMIT);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_UPLOADCOMMIT);
buf.putShort(ENDPOINT_PUTBYTES);
buf.put(PUTBYTES_COMMIT);
buf.putInt(token);
buf.putInt(crc);
return buf.array();
}
public byte[] encodeUploadComplete(int token) {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_UPLOADCOMPLETE);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_UPLOADCOMPLETE);
buf.putShort(ENDPOINT_PUTBYTES);
buf.put(PUTBYTES_COMPLETE);
buf.putInt(token);
return buf.array();
}
public byte[] encodeUploadCancel(int token) {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_UPLOADCANCEL);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_UPLOADCANCEL);
buf.putShort(ENDPOINT_PUTBYTES);
buf.put(PUTBYTES_ABORT);
buf.putInt(token);
return buf.array();
}
private byte[] encodeSystemMessage(byte systemMessage) {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_SYSTEMMESSAGE);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_SYSTEMMESSAGE);
buf.putShort(ENDPOINT_SYSTEMMESSAGE);
buf.put((byte) 0);
buf.put(systemMessage);
return buf.array();
}
public byte[] encodeInstallFirmwareStart() {
return encodeSystemMessage(SYSTEMMESSAGE_FIRMWARESTART);
}
public byte[] encodeInstallFirmwareComplete() {
return encodeSystemMessage(SYSTEMMESSAGE_FIRMWARECOMPLETE);
}
public byte[] encodeInstallFirmwareError() {
return encodeSystemMessage(SYSTEMMESSAGE_FIRMWAREFAIL);
}
public byte[] encodeAppRefresh(int index) {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_REFRESHAPP);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_REFRESHAPP);
buf.putShort(ENDPOINT_APPMANAGER);
buf.put(APPMANAGER_REFRESHAPP);
buf.putInt(index);
return buf.array();
}
public byte[] encodeDatalog(byte handle, byte reply) {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + 2);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort((short) 2);
buf.putShort(ENDPOINT_DATALOG);
buf.put(reply);
buf.put(handle);
return buf.array();
}
byte[] encodeApplicationMessageAck(UUID uuid, byte id) {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + 18); // +ACK
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort((short) 18);
buf.putShort(ENDPOINT_APPLICATIONMESSAGE);
buf.put(APPLICATIONMESSAGE_ACK);
buf.put(id);
buf.putLong(uuid.getMostSignificantBits());
buf.putLong(uuid.getMostSignificantBits());
return buf.array();
}
private static byte[] encodePing(byte command, int cookie) {
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_PING);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort(LENGTH_PING);
buf.putShort(ENDPOINT_PING);
buf.put(command);
buf.putInt(cookie);
return buf.array();
}
private ArrayList<Pair<Integer, Object>> decodeDict(ByteBuffer buf) {
ArrayList<Pair<Integer, Object>> dict = new ArrayList<>();
buf.order(ByteOrder.LITTLE_ENDIAN);
byte dictSize = buf.get();
while (dictSize-- > 0) {
Integer key = buf.getInt();
byte type = buf.get();
short length = buf.getShort();
switch (type) {
case TYPE_INT:
case TYPE_UINT:
dict.add(new Pair<Integer, Object>(key, buf.getInt()));
break;
case TYPE_CSTRING:
case TYPE_BYTEARRAY:
byte[] bytes = new byte[length];
buf.get(bytes);
if (type == TYPE_BYTEARRAY) {
dict.add(new Pair<Integer, Object>(key, bytes));
} else {
dict.add(new Pair<Integer, Object>(key, new String(bytes)));
}
break;
default:
}
}
return dict;
}
private GBDeviceEvent[] decodeDictToJSONAppMessage(UUID uuid, ByteBuffer buf) throws JSONException {
buf.order(ByteOrder.LITTLE_ENDIAN);
byte dictSize = buf.get();
if (dictSize == 0) {
LOG.info("dict size is 0, ignoring");
return null;
}
JSONArray jsonArray = new JSONArray();
while (dictSize-- > 0) {
JSONObject jsonObject = new JSONObject();
Integer key = buf.getInt();
byte type = buf.get();
short length = buf.getShort();
jsonObject.put("key", key);
jsonObject.put("length", length);
switch (type) {
case TYPE_UINT:
jsonObject.put("type", "uint");
if (length == 1) {
jsonObject.put("value", buf.get() & 0xff);
} else if (length == 2) {
jsonObject.put("value", buf.getShort() & 0xffff);
} else {
jsonObject.put("value", buf.getInt() & 0xffffffffL);
}
break;
case TYPE_INT:
jsonObject.put("type", "int");
if (length == 1) {
jsonObject.put("value", buf.get());
} else if (length == 2) {
jsonObject.put("value", buf.getShort());
} else {
jsonObject.put("value", buf.getInt());
}
break;
case TYPE_BYTEARRAY:
case TYPE_CSTRING:
byte[] bytes = new byte[length];
buf.get(bytes);
if (type == TYPE_BYTEARRAY) {
jsonObject.put("type", "bytes");
jsonObject.put("value", Base64.encode(bytes, Base64.NO_WRAP));
} else {
jsonObject.put("type", "string");
jsonObject.put("value", new String(bytes));
}
break;
default:
LOG.info("unknown type in appmessage, ignoring");
return null;
}
jsonArray.put(jsonObject);
}
// this is a hack we send an ack to the Pebble immediately because we cannot map the transaction_id from the intent back to a uuid yet
GBDeviceEventSendBytes sendBytesAck = new GBDeviceEventSendBytes();
sendBytesAck.encodedBytes = encodeApplicationMessageAck(uuid, last_id);
GBDeviceEventAppMessage appMessage = new GBDeviceEventAppMessage();
appMessage.appUUID = uuid;
appMessage.id = last_id & 0xff;
appMessage.message = jsonArray.toString();
return new GBDeviceEvent[]{appMessage, sendBytesAck};
}
byte[] encodeApplicationMessagePush(short endpoint, UUID uuid, ArrayList<Pair<Integer, Object>> pairs) {
int length = LENGTH_UUID + 3; // UUID + (PUSH + id + length of dict)
for (Pair<Integer, Object> pair : pairs) {
length += 7; // key + type + length
if (pair.second instanceof Integer) {
length += 4;
} else if (pair.second instanceof Short) {
length += 2;
} else if (pair.second instanceof Byte) {
length += 1;
} else if (pair.second instanceof String) {
length += ((String) pair.second).getBytes().length + 1;
} else if (pair.second instanceof byte[]) {
length += ((byte[]) pair.second).length;
}
}
ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + length);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort((short) length);
buf.putShort(endpoint); // 48 or 49
buf.put(APPLICATIONMESSAGE_PUSH);
buf.put(++last_id);
buf.putLong(uuid.getMostSignificantBits());
buf.putLong(uuid.getLeastSignificantBits());
buf.put((byte) pairs.size());
buf.order(ByteOrder.LITTLE_ENDIAN);
for (Pair<Integer, Object> pair : pairs) {
buf.putInt(pair.first);
if (pair.second instanceof Integer) {
buf.put(TYPE_INT);
buf.putShort((short) 4); // length
buf.putInt((int) pair.second);
} else if (pair.second instanceof Short) {
buf.put(TYPE_INT);
buf.putShort((short) 2); // length
buf.putShort((short) pair.second);
} else if (pair.second instanceof Byte) {
buf.put(TYPE_INT);
buf.putShort((short) 1); // length
buf.put((byte) pair.second);
} else if (pair.second instanceof String) {
String str = (String) pair.second;
buf.put(TYPE_CSTRING);
buf.putShort((short) (str.getBytes().length + 1));
buf.put(str.getBytes());
buf.put((byte) 0);
} else if (pair.second instanceof byte[]) {
byte[] bytes = (byte[]) pair.second;
buf.put(TYPE_BYTEARRAY);
buf.putShort((short) bytes.length);
buf.put(bytes);
}
}
return buf.array();
}
public byte[] encodeApplicationMessageFromJSON(UUID uuid, JSONArray jsonArray) {
ArrayList<Pair<Integer, Object>> pairs = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
String type = (String) jsonObject.get("type");
int key = (int) jsonObject.get("key");
int length = (int) jsonObject.get("length");
switch (type) {
case "uint":
case "int":
if (length == 1) {
pairs.add(new Pair<>(key, (Object) (byte) jsonObject.getInt("value")));
} else if (length == 2) {
pairs.add(new Pair<>(key, (Object) (short) jsonObject.getInt("value")));
} else {
if (type.equals("uint")) {
pairs.add(new Pair<>(key, (Object) (int) (jsonObject.getInt("value") & 0xffffffffL)));
} else {
pairs.add(new Pair<>(key, (Object) jsonObject.getInt("value")));
}
}
break;
case "string":
pairs.add(new Pair<>(key, (Object) jsonObject.getString("value")));
break;
case "bytes":
byte[] bytes = Base64.decode(jsonObject.getString("value"), Base64.NO_WRAP);
pairs.add(new Pair<>(key, (Object) bytes));
break;
}
} catch (JSONException e) {
return null;
}
}
return encodeApplicationMessagePush(ENDPOINT_APPLICATIONMESSAGE, uuid, pairs);
}
private static byte reverseBits(byte in) {
byte out = 0;
for (int i = 0; i < 8; i++) {
byte bit = (byte) (in & 1);
out = (byte) ((out << 1) | bit);
in = (byte) (in >> 1);
}
return out;
}
private GBDeviceEventScreenshot decodeScreenshot(ByteBuffer buf, int length) {
if (mDevEventScreenshot == null) {
byte result = buf.get();
mDevEventScreenshot = new GBDeviceEventScreenshot();
int version = buf.getInt();
if (result != 0) {
return null;
}
mDevEventScreenshot.width = buf.getInt();
mDevEventScreenshot.height = buf.getInt();
if (version == 1) {
mDevEventScreenshot.bpp = 1;
mDevEventScreenshot.clut = clut_pebble;
} else {
mDevEventScreenshot.bpp = 8;
mDevEventScreenshot.clut = clut_pebbletime;
}
mScreenshotRemaining = (mDevEventScreenshot.width * mDevEventScreenshot.height * mDevEventScreenshot.bpp) / 8;
mDevEventScreenshot.data = new byte[mScreenshotRemaining];
length -= 13;
}
if (mScreenshotRemaining == -1) {
return null;
}
for (int i = 0; i < length; i++) {
byte corrected = buf.get();
if (mDevEventScreenshot.bpp == 1) {
corrected = reverseBits(corrected);
} else {
corrected = (byte) (corrected & 0b00111111);
}
mDevEventScreenshot.data[mDevEventScreenshot.data.length - mScreenshotRemaining + i] = corrected;
}
mScreenshotRemaining -= length;
LOG.info("Screenshot remaining bytes " + mScreenshotRemaining);
if (mScreenshotRemaining == 0) {
mScreenshotRemaining = -1;
LOG.info("Got screenshot : " + mDevEventScreenshot.width + "x" + mDevEventScreenshot.height + " " + "pixels");
GBDeviceEventScreenshot devEventScreenshot = mDevEventScreenshot;
mDevEventScreenshot = null;
return devEventScreenshot;
}
return null;
}
private GBDeviceEvent[] decodeAction(ByteBuffer buf) {
buf.order(ByteOrder.LITTLE_ENDIAN);
byte command = buf.get();
if (command == NOTIFICATIONACTION_INVOKE) {
int id;
long uuid_high = 0;
long uuid_low = 0;
if (isFw3x) {
buf.order(ByteOrder.BIG_ENDIAN);
uuid_high = buf.getLong();
uuid_low = buf.getLong();
buf.order(ByteOrder.LITTLE_ENDIAN);
id = (int) (uuid_low & 0xffffffffL);
} else {
id = buf.getInt();
}
byte action = buf.get();
if (action >= 0x01 && action <= 0x05) {
GBDeviceEventNotificationControl devEvtNotificationControl = new GBDeviceEventNotificationControl();
devEvtNotificationControl.handle = id;
String caption = "undefined";
int icon_id = 1;
boolean needsAck2x = true;
switch (action) {
case 0x01:
devEvtNotificationControl.event = GBDeviceEventNotificationControl.Event.OPEN;
caption = "Opened";
icon_id = PebbleIconID.DURING_PHONE_CALL;
break;
case 0x02:
devEvtNotificationControl.event = GBDeviceEventNotificationControl.Event.DISMISS;
caption = "Dismissed";
icon_id = PebbleIconID.RESULT_DISMISSED;
needsAck2x = false;
break;
case 0x03:
devEvtNotificationControl.event = GBDeviceEventNotificationControl.Event.DISMISS_ALL;
caption = "All dismissed";
icon_id = PebbleIconID.RESULT_DISMISSED;
needsAck2x = false;
break;
case 0x04:
devEvtNotificationControl.event = GBDeviceEventNotificationControl.Event.MUTE;
caption = "Muted";
icon_id = PebbleIconID.RESULT_MUTE;
break;
case 0x05:
byte attribute_count = buf.get();
if (attribute_count > 0) {
byte attribute = buf.get();
if (attribute == 0x01) { // reply string is in attribute 0x01
short length = buf.getShort();
if (length > 64) length = 64;
byte[] reply = new byte[length];
buf.get(reply);
devEvtNotificationControl.event = GBDeviceEventNotificationControl.Event.REPLY;
devEvtNotificationControl.reply = new String(reply);
caption = "SENT";
icon_id = PebbleIconID.RESULT_SENT;
} else {
devEvtNotificationControl = null; // error
caption = "FAILED";
icon_id = PebbleIconID.RESULT_FAILED;
}
} else {
caption = "FAILED";
icon_id = PebbleIconID.RESULT_FAILED;
devEvtNotificationControl = null; // error
}
break;
}
GBDeviceEventSendBytes sendBytesAck = null;
if (isFw3x || needsAck2x) {
sendBytesAck = new GBDeviceEventSendBytes();
if (isFw3x) {
sendBytesAck.encodedBytes = encodeActionResponse(new UUID(uuid_high, uuid_low), icon_id, caption);
} else {
sendBytesAck.encodedBytes = encodeActionResponse2x(id, action, 6, caption);
}
}
return new GBDeviceEvent[]{sendBytesAck, devEvtNotificationControl};
}
LOG.info("unexpected action: " + action);
}
return null;
}
private GBDeviceEventSendBytes decodePing(ByteBuffer buf) {
byte command = buf.get();
if (command == PING_PING) {
int cookie = buf.getInt();
LOG.info("Received PING - will reply");
GBDeviceEventSendBytes sendBytes = new GBDeviceEventSendBytes();
sendBytes.encodedBytes = encodePing(PING_PONG, cookie);
return sendBytes;
}
return null;
}
private GBDeviceEvent decodeSystemMessage(ByteBuffer buf) {
buf.get(); // unknown;
byte command = buf.get();
final String ENDPOINT_NAME = "SYSTEM MESSAGE";
switch (command) {
case SYSTEMMESSAGE_STOPRECONNECTING:
LOG.info(ENDPOINT_NAME + ": stop reconnecting");
break;
case SYSTEMMESSAGE_STARTRECONNECTING:
LOG.info(ENDPOINT_NAME + ": start reconnecting");
break;
default:
LOG.info(ENDPOINT_NAME + ": " + command);
break;
}
return null;
}
private GBDeviceEvent decodeAppRunState(ByteBuffer buf) {
byte command = buf.get();
long uuid_high = buf.getLong();
long uuid_low = buf.getLong();
UUID uuid = new UUID(uuid_high, uuid_low);
final String ENDPOINT_NAME = "APPRUNSTATE";
switch (command) {
case APPRUNSTATE_START:
LOG.info(ENDPOINT_NAME + ": started " + uuid);
if (UUID_PEBSTYLE.equals(uuid)) {
AppMessageHandler handler = mAppMessageHandlers.get(uuid);
return handler.pushMessage()[0];
}
break;
case APPRUNSTATE_STOP:
LOG.info(ENDPOINT_NAME + ": stopped " + uuid);
break;
default:
LOG.info(ENDPOINT_NAME + ": (cmd:" + command + ")" + uuid);
break;
}
return null;
}
private GBDeviceEvent decodeBlobDb(ByteBuffer buf) {
final String ENDPOINT_NAME = "BLOBDB";
final String statusString[] = {
"unknown",
"success",
"general failure",
"invalid operation",
"invalid database id",
"invalid data",
"key does not exist",
"database full",
"data stale",
};
buf.order(ByteOrder.LITTLE_ENDIAN);
short token = buf.getShort();
byte status = buf.get();
if (status >= 0 && status < statusString.length) {
LOG.info(ENDPOINT_NAME + ": " + statusString[status] + " (token " + (token & 0xffff) + ")");
} else {
LOG.warn(ENDPOINT_NAME + ": unknown status " + status + " (token " + (token & 0xffff) + ")");
}
return null;
}
private GBDeviceEventAppManagement decodeAppFetch(ByteBuffer buf) {
byte command = buf.get();
if (command == 0x01) {
long uuid_high = buf.getLong();
long uuid_low = buf.getLong();
UUID uuid = new UUID(uuid_high, uuid_low);
buf.order(ByteOrder.LITTLE_ENDIAN);
int app_id = buf.getInt();
GBDeviceEventAppManagement fetchRequest = new GBDeviceEventAppManagement();
fetchRequest.type = GBDeviceEventAppManagement.EventType.INSTALL;
fetchRequest.event = GBDeviceEventAppManagement.Event.REQUEST;
fetchRequest.token = app_id;
fetchRequest.uuid = uuid;
return fetchRequest;
}
return null;
}
private GBDeviceEventSendBytes decodeDatalog(ByteBuffer buf, short length) {
byte command = buf.get();
byte id = buf.get();
switch (command) {
case DATALOG_TIMEOUT:
LOG.info("DATALOG TIMEOUT. id=" + (id & 0xff) + " - ignoring");
return null;
case DATALOG_SENDDATA:
buf.order(ByteOrder.LITTLE_ENDIAN);
int items_left = buf.getInt();
int crc = buf.getInt();
LOG.info("DATALOG SENDDATA. id=" + (id & 0xff) + ", items_left=" + items_left + ", total length=" + (length - 9));
break;
case DATALOG_OPENSESSION:
buf.order(ByteOrder.BIG_ENDIAN);
long uuid_high = buf.getLong();
long uuid_low = buf.getLong();
UUID uuid = new UUID(uuid_high, uuid_low);
buf.order(ByteOrder.LITTLE_ENDIAN);
int timestamp = buf.getInt();
int log_tag = buf.getInt();
byte item_type = buf.get();
short item_size = buf.get();
LOG.info("DATALOG OPENSESSION. id=" + (id & 0xff) + ", App UUID=" + uuid.toString() + ", item_type=" + item_type + ", item_size=" + item_size);
break;
default:
LOG.info("unknown DATALOG command: " + (command & 0xff));
break;
}
LOG.info("sending ACK (0x85)");
GBDeviceEventSendBytes sendBytes = new GBDeviceEventSendBytes();
sendBytes.encodedBytes = encodeDatalog(id, DATALOG_ACK);
return sendBytes;
}
@Override
public GBDeviceEvent[] decodeResponse(byte[] responseData) {
ByteBuffer buf = ByteBuffer.wrap(responseData);
buf.order(ByteOrder.BIG_ENDIAN);
short length = buf.getShort();
short endpoint = buf.getShort();
GBDeviceEvent devEvts[] = null;
byte pebbleCmd = -1;
switch (endpoint) {
case ENDPOINT_MUSICCONTROL:
pebbleCmd = buf.get();
GBDeviceEventMusicControl musicCmd = new GBDeviceEventMusicControl();
switch (pebbleCmd) {
case MUSICCONTROL_NEXT:
musicCmd.event = GBDeviceEventMusicControl.Event.NEXT;
break;
case MUSICCONTROL_PREVIOUS:
musicCmd.event = GBDeviceEventMusicControl.Event.PREVIOUS;
break;
case MUSICCONTROL_PLAY:
musicCmd.event = GBDeviceEventMusicControl.Event.PLAY;
break;
case MUSICCONTROL_PAUSE:
musicCmd.event = GBDeviceEventMusicControl.Event.PAUSE;
break;
case MUSICCONTROL_PLAYPAUSE:
musicCmd.event = GBDeviceEventMusicControl.Event.PLAYPAUSE;
break;
case MUSICCONTROL_VOLUMEUP:
musicCmd.event = GBDeviceEventMusicControl.Event.VOLUMEUP;
break;
case MUSICCONTROL_VOLUMEDOWN:
musicCmd.event = GBDeviceEventMusicControl.Event.VOLUMEDOWN;
break;
default:
break;
}
devEvts = new GBDeviceEvent[]{musicCmd};
break;
case ENDPOINT_PHONECONTROL:
pebbleCmd = buf.get();
GBDeviceEventCallControl callCmd = new GBDeviceEventCallControl();
switch (pebbleCmd) {
case PHONECONTROL_HANGUP:
callCmd.event = GBDeviceEventCallControl.Event.END;
break;
default:
LOG.info("Unknown PHONECONTROL event" + pebbleCmd);
break;
}
devEvts = new GBDeviceEvent[]{callCmd};
break;
case ENDPOINT_FIRMWAREVERSION:
pebbleCmd = buf.get();
GBDeviceEventVersionInfo versionCmd = new GBDeviceEventVersionInfo();
buf.getInt(); // skip
byte[] tmp = new byte[32];
buf.get(tmp, 0, 32);
versionCmd.fwVersion = new String(tmp).trim();
if (versionCmd.fwVersion.startsWith("v3")) {
isFw3x = true;
}
buf.get(tmp, 0, 9);
int hwRev = buf.get() + 5;
if (hwRev >= 0 && hwRev < hwRevisions.length) {
versionCmd.hwVersion = hwRevisions[hwRev];
}
devEvts = new GBDeviceEvent[]{versionCmd};
break;
case ENDPOINT_APPMANAGER:
pebbleCmd = buf.get();
switch (pebbleCmd) {
case APPMANAGER_GETAPPBANKSTATUS:
GBDeviceEventAppInfo appInfoCmd = new GBDeviceEventAppInfo();
int slotCount = buf.getInt();
int slotsUsed = buf.getInt();
byte[] appName = new byte[32];
byte[] appCreator = new byte[32];
appInfoCmd.apps = new GBDeviceApp[slotsUsed];
boolean[] slotInUse = new boolean[slotCount];
for (int i = 0; i < slotsUsed; i++) {
int id = buf.getInt();
int index = buf.getInt();
slotInUse[index] = true;
buf.get(appName, 0, 32);
buf.get(appCreator, 0, 32);
int flags = buf.getInt();
GBDeviceApp.Type appType;
if ((flags & 16) == 16) { // FIXME: verify this assumption
appType = GBDeviceApp.Type.APP_ACTIVITYTRACKER;
} else if ((flags & 1) == 1) { // FIXME: verify this assumption
appType = GBDeviceApp.Type.WATCHFACE;
} else {
appType = GBDeviceApp.Type.APP_GENERIC;
}
Short appVersion = buf.getShort();
appInfoCmd.apps[i] = new GBDeviceApp(tmpUUIDS.get(i), new String(appName).trim(), new String(appCreator).trim(), appVersion.toString(), appType);
}
for (int i = 0; i < slotCount; i++) {
if (!slotInUse[i]) {
appInfoCmd.freeSlot = (byte) i;
LOG.info("found free slot " + i);
break;
}
}
devEvts = new GBDeviceEvent[]{appInfoCmd};
break;
case APPMANAGER_GETUUIDS:
GBDeviceEventSendBytes sendBytes = new GBDeviceEventSendBytes();
sendBytes.encodedBytes = encodeSimpleMessage(ENDPOINT_APPMANAGER, APPMANAGER_GETAPPBANKSTATUS);
devEvts = new GBDeviceEvent[]{sendBytes};
tmpUUIDS.clear();
slotsUsed = buf.getInt();
for (int i = 0; i < slotsUsed; i++) {
long uuid_high = buf.getLong();
long uuid_low = buf.getLong();
UUID uuid = new UUID(uuid_high, uuid_low);
LOG.info("found uuid: " + uuid);
tmpUUIDS.add(uuid);
}
break;
case APPMANAGER_REMOVEAPP:
GBDeviceEventAppManagement deleteRes = new GBDeviceEventAppManagement();
deleteRes.type = GBDeviceEventAppManagement.EventType.DELETE;
int result = buf.getInt();
switch (result) {
case APPMANAGER_RES_SUCCESS:
deleteRes.event = GBDeviceEventAppManagement.Event.SUCCESS;
break;
default:
deleteRes.event = GBDeviceEventAppManagement.Event.FAILURE;
break;
}
devEvts = new GBDeviceEvent[]{deleteRes};
break;
default:
LOG.info("Unknown APPMANAGER event" + pebbleCmd);
break;
}
break;
case ENDPOINT_PUTBYTES:
pebbleCmd = buf.get();
GBDeviceEventAppManagement installRes = new GBDeviceEventAppManagement();
installRes.type = GBDeviceEventAppManagement.EventType.INSTALL;
switch (pebbleCmd) {
case PUTBYTES_INIT:
installRes.token = buf.getInt();
installRes.event = GBDeviceEventAppManagement.Event.SUCCESS;
break;
default:
installRes.token = buf.getInt();
installRes.event = GBDeviceEventAppManagement.Event.FAILURE;
break;
}
devEvts = new GBDeviceEvent[]{installRes};
break;
case ENDPOINT_APPLICATIONMESSAGE:
case ENDPOINT_LAUNCHER:
pebbleCmd = buf.get();
last_id = buf.get();
long uuid_high = buf.getLong();
long uuid_low = buf.getLong();
switch (pebbleCmd) {
case APPLICATIONMESSAGE_PUSH:
UUID uuid = new UUID(uuid_high, uuid_low);
if (endpoint == ENDPOINT_LAUNCHER) {
LOG.info("got LAUNCHER PUSH from UUID " + uuid);
break;
}
LOG.info("got APPLICATIONMESSAGE PUSH from UUID " + uuid);
AppMessageHandler handler = mAppMessageHandlers.get(uuid);
if (handler != null) {
ArrayList<Pair<Integer, Object>> dict = decodeDict(buf);
devEvts = handler.handleMessage(dict);
} else {
try {
devEvts = decodeDictToJSONAppMessage(uuid, buf);
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
break;
case APPLICATIONMESSAGE_ACK:
LOG.info("got APPLICATIONMESSAGE/LAUNCHER (EP " + endpoint + ") ACK");
devEvts = new GBDeviceEvent[]{null};
break;
case APPLICATIONMESSAGE_NACK:
LOG.info("got APPLICATIONMESSAGE/LAUNCHER (EP " + endpoint + ") NACK");
devEvts = new GBDeviceEvent[]{null};
break;
case APPLICATIONMESSAGE_REQUEST:
LOG.info("got APPLICATIONMESSAGE/LAUNCHER (EP " + endpoint + ") REQUEST");
devEvts = new GBDeviceEvent[]{null};
break;
default:
break;
}
break;
case ENDPOINT_PHONEVERSION:
pebbleCmd = buf.get();
switch (pebbleCmd) {
case PHONEVERSION_REQUEST:
LOG.info("Pebble asked for Phone/App Version - repLYING!");
GBDeviceEventSendBytes sendBytes = new GBDeviceEventSendBytes();
sendBytes.encodedBytes = encodePhoneVersion(PHONEVERSION_REMOTE_OS_ANDROID);
devEvts = new GBDeviceEvent[]{sendBytes};
break;
default:
break;
}
break;
case ENDPOINT_DATALOG:
devEvts = new GBDeviceEvent[]{decodeDatalog(buf, length)};
break;
case ENDPOINT_SCREENSHOT:
devEvts = new GBDeviceEvent[]{decodeScreenshot(buf, length)};
break;
case ENDPOINT_EXTENSIBLENOTIFS:
case ENDPOINT_NOTIFICATIONACTION:
devEvts = decodeAction(buf);
break;
case ENDPOINT_PING:
devEvts = new GBDeviceEvent[]{decodePing(buf)};
break;
case ENDPOINT_APPFETCH:
devEvts = new GBDeviceEvent[]{decodeAppFetch(buf)};
break;
case ENDPOINT_SYSTEMMESSAGE:
devEvts = new GBDeviceEvent[]{decodeSystemMessage(buf)};
break;
case ENDPOINT_APPRUNSTATE:
devEvts = new GBDeviceEvent[]{decodeAppRunState(buf)};
break;
case ENDPOINT_BLOBDB:
devEvts = new GBDeviceEvent[]{decodeBlobDb(buf)};
break;
default:
break;
}
return devEvts;
}
public void setForceProtocol(boolean force) {
LOG.info("setting force protocol to " + force);
mForceProtocol = force;
}
}
| Pebble: Display a failure if we cannot map a notification id back to a Phone number when replying to an SMS
| app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/devices/pebble/PebbleProtocol.java | Pebble: Display a failure if we cannot map a notification id back to a Phone number when replying to an SMS |
|
Java | agpl-3.0 | 48de5d18dda322e39b25b929c1500a0ffaf0c1d8 | 0 | podd/podd-redesign,podd/podd-redesign,podd/podd-redesign,podd/podd-redesign | package com.github.podd.impl.file;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.openrdf.model.Model;
import org.openrdf.model.Resource;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.model.vocabulary.RDFS;
import org.semanticweb.owlapi.model.IRI;
import com.github.podd.api.file.SSHFileReference;
import com.github.podd.api.file.SSHFileReferenceProcessor;
import com.github.podd.utils.DebugUtils;
import com.github.podd.utils.PoddRdfConstants;
/**
* Processor for File References of type <i>http://purl.org/podd/ns/poddBase#SSHFileReference</i>.
*
* @author kutila
*/
public class SSHFileReferenceProcessorImpl implements SSHFileReferenceProcessor
{
@Override
public boolean canHandle(final Model rdfStatements)
{
if(rdfStatements == null || rdfStatements.isEmpty())
{
return false;
}
for(final URI fileType : this.getTypes())
{
final Model matchingModels = rdfStatements.filter((Resource)null, null, fileType);
if(!matchingModels.isEmpty())
{
return true;
}
}
return false;
}
@Override
public Collection<SSHFileReference> createReferences(final Model rdfStatements)
{
if(rdfStatements == null || rdfStatements.isEmpty())
{
return null;
}
final Set<SSHFileReference> results = new HashSet<SSHFileReference>();
for(final URI fileType : this.getTypes())
{
final Set<Resource> fileRefUris = rdfStatements.filter(null, RDF.TYPE, fileType).subjects();
for(final Resource fileRef : fileRefUris)
{
final Model model = rdfStatements.filter(fileRef, null, null);
DebugUtils.printContents(model);
final SSHFileReference fileReference = new SSHFileReferenceImpl();
// note: artifact ID is not available to us in here and must be added externally
if(fileRef instanceof URI)
{
fileReference.setObjectIri(IRI.create((URI)fileRef));
}
final Set<Value> label = model.filter(fileRef, RDFS.LABEL, null).objects();
if(!label.isEmpty())
{
fileReference.setLabel(label.iterator().next().stringValue());
}
final Set<Value> filename =
model.filter(fileRef, PoddRdfConstants.PODD_BASE_HAS_FILENAME, null).objects();
if(!filename.isEmpty())
{
fileReference.setFilename(filename.iterator().next().stringValue());
}
final Set<Value> path = model.filter(fileRef, PoddRdfConstants.PODD_BASE_HAS_FILE_PATH, null).objects();
if(!path.isEmpty())
{
fileReference.setPath(path.iterator().next().stringValue());
}
final Set<Value> alias = model.filter(fileRef, PoddRdfConstants.PODD_BASE_HAS_ALIAS, null).objects();
if(!alias.isEmpty())
{
fileReference.setRepositoryAlias(alias.iterator().next().stringValue());
}
Model linksToFileReference = rdfStatements.filter(null, null, fileRef);
// TODO: Need to use a SPARQL query to verify that the property is a sub-property of
// PODD Contains
if(!linksToFileReference.isEmpty())
{
for(Resource nextResource : linksToFileReference.subjects())
{
if(nextResource instanceof URI)
{
fileReference.setParentIri(IRI.create((URI)nextResource));
break;
}
}
}
results.add(fileReference);
}
}
return results;
}
@Override
public Set<URI> getTypes()
{
return Collections.singleton(PoddRdfConstants.PODD_BASE_FILE_REFERENCE_TYPE_SSH);
}
}
| webapp/lib/src/main/java/com/github/podd/impl/file/SSHFileReferenceProcessorImpl.java | package com.github.podd.impl.file;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.openrdf.model.Model;
import org.openrdf.model.Resource;
import org.openrdf.model.URI;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.model.vocabulary.RDFS;
import org.semanticweb.owlapi.model.IRI;
import com.github.podd.api.file.SSHFileReference;
import com.github.podd.api.file.SSHFileReferenceProcessor;
import com.github.podd.utils.PoddRdfConstants;
/**
* Processor for File References of type <i>http://purl.org/podd/ns/poddBase#SSHFileReference</i>.
*
* @author kutila
*/
public class SSHFileReferenceProcessorImpl implements SSHFileReferenceProcessor
{
@Override
public boolean canHandle(final Model rdfStatements)
{
if(rdfStatements == null || rdfStatements.isEmpty())
{
return false;
}
for(final URI fileType : this.getTypes())
{
final Model matchingModels = rdfStatements.filter((Resource)null, null, fileType);
if(!matchingModels.isEmpty())
{
return true;
}
}
return false;
}
@Override
public Collection<SSHFileReference> createReferences(final Model rdfStatements)
{
if(rdfStatements == null || rdfStatements.isEmpty())
{
return null;
}
final Set<SSHFileReference> results = new HashSet<SSHFileReference>();
for(final URI fileType : this.getTypes())
{
final Set<Resource> fileRefUris = rdfStatements.filter(null, RDF.TYPE, fileType).subjects();
for(final Resource fileRef : fileRefUris)
{
final Model model = rdfStatements.filter(fileRef, null, null);
final SSHFileReference fileReference = new SSHFileReferenceImpl();
// note: artifact ID is not available to us in here and must be added externally
if(fileRef instanceof URI)
{
fileReference.setObjectIri(IRI.create((URI)fileRef));
}
final String label = model.filter(fileRef, RDFS.LABEL, null).objectString();
if(label != null)
{
fileReference.setLabel(label);
}
final String filename =
model.filter(fileRef, PoddRdfConstants.PODD_BASE_HAS_FILENAME, null).objectString();
if(filename != null)
{
fileReference.setFilename(filename);
}
final String path =
model.filter(fileRef, PoddRdfConstants.PODD_BASE_HAS_FILE_PATH, null).objectString();
if(path != null)
{
fileReference.setPath(path);
}
final String alias = model.filter(fileRef, PoddRdfConstants.PODD_BASE_HAS_ALIAS, null).objectString();
if(alias != null)
{
fileReference.setRepositoryAlias(alias);
}
Model linksToFileReference = rdfStatements.filter(null, null, fileRef);
// TODO: Need to use a SPARQL query to verify that the property is a sub-property of
// PODD Contains
if(!linksToFileReference.isEmpty())
{
for(Resource nextResource : linksToFileReference.subjects())
{
if(nextResource instanceof URI)
{
fileReference.setParentIri(IRI.create((URI)nextResource));
break;
}
}
}
results.add(fileReference);
}
}
return results;
}
@Override
public Set<URI> getTypes()
{
return Collections.singleton(PoddRdfConstants.PODD_BASE_FILE_REFERENCE_TYPE_SSH);
}
}
| Fix EditArtifactResourceImplTest.testEditArtifactBasicRdf
The reasoner seems to be generating inferred triples that have
XSD:string attached for any triples that are RDF-1.0 Plain Literals
In RDF-1.1 this situation will not occur as all plain literal will be
typed as XSD:string. | webapp/lib/src/main/java/com/github/podd/impl/file/SSHFileReferenceProcessorImpl.java | Fix EditArtifactResourceImplTest.testEditArtifactBasicRdf |
|
Java | agpl-3.0 | 159027d07b8e8d691c3d10787c39c18ab992f852 | 0 | rdkgit/opennms,rdkgit/opennms,aihua/opennms,tdefilip/opennms,tdefilip/opennms,tdefilip/opennms,roskens/opennms-pre-github,aihua/opennms,rdkgit/opennms,tdefilip/opennms,aihua/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,rdkgit/opennms,roskens/opennms-pre-github,aihua/opennms,tdefilip/opennms,rdkgit/opennms,tdefilip/opennms,tdefilip/opennms,roskens/opennms-pre-github,aihua/opennms,tdefilip/opennms,aihua/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,rdkgit/opennms,aihua/opennms,rdkgit/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,tdefilip/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,rdkgit/opennms,rdkgit/opennms,aihua/opennms,rdkgit/opennms,aihua/opennms | //
// This file is part of the OpenNMS(R) Application.
//
// OpenNMS(R) is Copyright (C) 2005 The OpenNMS Group, Inc. All rights reserved.
// OpenNMS(R) is a derivative work, containing both original code, included code and modified
// code that was published under the GNU General Public License. Copyrights for modified
// and included code are below.
//
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
//
// Modifications:
//
// 2007 May 21: Make sure that the value cannot be null in the
// constructor. - [email protected]
//
// Original code base Copyright (C) 1999-2001 Oculan Corp. All rights reserved.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// For more information contact:
// OpenNMS Licensing <[email protected]>
// http://www.opennms.org/
// http://www.opennms.com/
//
package org.opennms.netmgt.snmp.snmp4j;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.opennms.netmgt.snmp.SnmpObjId;
import org.opennms.netmgt.snmp.SnmpValue;
import org.snmp4j.smi.Counter32;
import org.snmp4j.smi.Counter64;
import org.snmp4j.smi.Integer32;
import org.snmp4j.smi.IpAddress;
import org.snmp4j.smi.Null;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.Opaque;
import org.snmp4j.smi.SMIConstants;
import org.snmp4j.smi.TimeTicks;
import org.snmp4j.smi.UnsignedInteger32;
import org.snmp4j.smi.Variable;
import org.springframework.util.Assert;
class Snmp4JValue implements SnmpValue {
Variable m_value;
Snmp4JValue(Variable value) {
Assert.notNull(value, "value attribute cannot be null");
m_value = value;
}
Snmp4JValue(int syntax, byte[] bytes) {
switch (syntax) {
case SMIConstants.SYNTAX_INTEGER: {
BigInteger val = new BigInteger(bytes);
m_value = new Integer32(val.intValue());
break;
}
case SMIConstants.SYNTAX_COUNTER32: {
BigInteger val = new BigInteger(bytes);
m_value = new Counter32(val.longValue());
break;
}
case SMIConstants.SYNTAX_COUNTER64: {
BigInteger val = new BigInteger(bytes);
m_value = new Counter64(val.longValue());
break;
}
case SMIConstants.SYNTAX_TIMETICKS: {
BigInteger val = new BigInteger(bytes);
m_value = new TimeTicks(val.longValue());
break;
}
case SMIConstants.SYNTAX_UNSIGNED_INTEGER32: {
BigInteger val = new BigInteger(bytes);
m_value = new UnsignedInteger32(val.longValue());
break;
}
case SMIConstants.SYNTAX_IPADDRESS: {
try {
InetAddress addr = InetAddress.getByAddress(bytes);
m_value = new IpAddress(addr);
} catch (UnknownHostException e) {
throw new IllegalArgumentException("unable to create InetAddress from bytes: "+e.getMessage());
}
break;
}
case SMIConstants.SYNTAX_OBJECT_IDENTIFIER: {
m_value = new OID(new String(bytes));
break;
}
case SMIConstants.SYNTAX_OCTET_STRING: {
m_value = new OctetString(bytes);
break;
}
case SMIConstants.SYNTAX_OPAQUE: {
m_value = new Opaque(bytes);
break;
}
case SMIConstants.SYNTAX_NULL: {
m_value = new Null();
break;
}
default:
throw new IllegalArgumentException("invalid syntax "+syntax);
}
Assert.notNull(m_value, "value object created from syntax " + syntax + " is null");
}
public byte[] getBytes() {
switch (m_value.getSyntax()) {
case SMIConstants.SYNTAX_INTEGER:
case SMIConstants.SYNTAX_COUNTER32:
case SMIConstants.SYNTAX_COUNTER64:
case SMIConstants.SYNTAX_TIMETICKS:
case SMIConstants.SYNTAX_UNSIGNED_INTEGER32:
return toBigInteger().toByteArray();
case SMIConstants.SYNTAX_IPADDRESS:
return toInetAddress().getAddress();
case SMIConstants.SYNTAX_OBJECT_IDENTIFIER:
return toSnmpObjId().toString().getBytes();
case SMIConstants.SYNTAX_OCTET_STRING:
return ((OctetString)m_value).getValue();
case SMIConstants.SYNTAX_OPAQUE:
return((Opaque)m_value).getValue();
case SMIConstants.SYNTAX_NULL:
return new byte[0];
default:
throw new IllegalArgumentException("cannot convert "+m_value+" to a byte array");
}
}
public int getType() {
return m_value.getSyntax();
}
public boolean isEndOfMib() {
return m_value.getSyntax() == SMIConstants.EXCEPTION_END_OF_MIB_VIEW;
}
public boolean isNumeric() {
switch (m_value.getSyntax()) {
case SMIConstants.SYNTAX_INTEGER:
case SMIConstants.SYNTAX_COUNTER32:
case SMIConstants.SYNTAX_COUNTER64:
case SMIConstants.SYNTAX_TIMETICKS:
case SMIConstants.SYNTAX_UNSIGNED_INTEGER32:
return true;
default:
return false;
}
}
public int toInt() {
switch (m_value.getSyntax()) {
case SMIConstants.SYNTAX_COUNTER64:
return (int)((Counter64)m_value).getValue();
case SMIConstants.SYNTAX_INTEGER:
return ((Integer32)m_value).getValue();
case SMIConstants.SYNTAX_COUNTER32:
case SMIConstants.SYNTAX_TIMETICKS:
case SMIConstants.SYNTAX_UNSIGNED_INTEGER32:
return (int)((UnsignedInteger32)m_value).getValue();
default:
return Integer.parseInt(m_value.toString());
}
}
public long toLong() {
switch (m_value.getSyntax()) {
case SMIConstants.SYNTAX_COUNTER64:
return ((Counter64)m_value).getValue();
case SMIConstants.SYNTAX_INTEGER:
return ((Integer32)m_value).getValue();
case SMIConstants.SYNTAX_COUNTER32:
case SMIConstants.SYNTAX_TIMETICKS:
case SMIConstants.SYNTAX_UNSIGNED_INTEGER32:
return ((UnsignedInteger32)m_value).getValue();
case SMIConstants.SYNTAX_OCTET_STRING:
return (convertStringToLong());
default:
return Integer.parseInt(m_value.toString());
}
}
private long convertStringToLong() {
return Float.valueOf(m_value.toString()).longValue();
}
public String toDisplayString() {
switch (m_value.getSyntax()) {
case SMIConstants.SYNTAX_OBJECT_IDENTIFIER :
return SnmpObjId.get(((OID)m_value).getValue()).toString();
case SMIConstants.SYNTAX_TIMETICKS :
return Long.toString(toLong());
case SMIConstants.SYNTAX_OCTET_STRING :
return toStringDottingCntrlChars(((OctetString)m_value).getValue());
default :
return m_value.toString();
}
}
private String toStringDottingCntrlChars(byte[] value) {
byte[] results = new byte[value.length];
for (int i = 0; i < value.length; i++) {
results[i] = Character.isISOControl((char)value[i]) ? (byte)'.' : value[i];
}
return new String(results);
}
public InetAddress toInetAddress() {
switch (m_value.getSyntax()) {
case SMIConstants.SYNTAX_IPADDRESS:
return ((IpAddress)m_value).getInetAddress();
default:
throw new IllegalArgumentException("cannot convert "+m_value+" to an InetAddress");
}
}
public String toHexString() {
switch (m_value.getSyntax()) {
case SMIConstants.SYNTAX_OCTET_STRING:
return ((OctetString)m_value).toHexString().replaceAll(":", "");
default:
throw new IllegalArgumentException("cannot convert "+m_value+" to a HexString");
}
}
public String toString() {
return toDisplayString();
}
public BigInteger toBigInteger() {
switch (m_value.getSyntax()) {
case SMIConstants.SYNTAX_COUNTER64:
Counter64 cnt = (Counter64)m_value;
if (cnt.getValue() > 0)
return BigInteger.valueOf(cnt.getValue());
else {
return new BigInteger(cnt.toString());
}
case SMIConstants.SYNTAX_INTEGER:
return BigInteger.valueOf(((Integer32)m_value).getValue());
case SMIConstants.SYNTAX_COUNTER32:
case SMIConstants.SYNTAX_TIMETICKS:
case SMIConstants.SYNTAX_UNSIGNED_INTEGER32:
return BigInteger.valueOf(((UnsignedInteger32)m_value).getValue());
default:
return new BigInteger(m_value.toString());
}
}
public SnmpObjId toSnmpObjId() {
switch (m_value.getSyntax()) {
case SMIConstants.SYNTAX_OBJECT_IDENTIFIER:
return SnmpObjId.get(((OID)m_value).getValue());
default:
throw new IllegalArgumentException("cannot convert "+m_value+" to an SnmpObjId");
}
}
public boolean isDisplayable() {
if (isNumeric())
return true;
if (getType() == SnmpValue.SNMP_OBJECT_IDENTIFIER || getType() == SnmpValue.SNMP_IPADDRESS)
return true;
if (getType() == SnmpValue.SNMP_OCTET_STRING) {
return allBytesDisplayable(getBytes());
}
return false;
}
private boolean allBytesDisplayable(byte[] bytes) {
for(int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
if ((b < 32 && b != 9 && b != 10 && b != 13 && b != 0) || b == 127)
return false;
}
return true;
}
public boolean isNull() {
return getType() == SnmpValue.SNMP_NULL;
}
public Variable getVariable() {
return m_value;
}
} | opennms-snmp/opennms-snmp-snmp4j/src/main/java/org/opennms/netmgt/snmp/snmp4j/Snmp4JValue.java | //
// This file is part of the OpenNMS(R) Application.
//
// OpenNMS(R) is Copyright (C) 2005 The OpenNMS Group, Inc. All rights reserved.
// OpenNMS(R) is a derivative work, containing both original code, included code and modified
// code that was published under the GNU General Public License. Copyrights for modified
// and included code are below.
//
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
//
// Original code base Copyright (C) 1999-2001 Oculan Corp. All rights reserved.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// For more information contact:
// OpenNMS Licensing <[email protected]>
// http://www.opennms.org/
// http://www.opennms.com/
//
package org.opennms.netmgt.snmp.snmp4j;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.opennms.netmgt.snmp.SnmpObjId;
import org.opennms.netmgt.snmp.SnmpValue;
import org.snmp4j.smi.Counter32;
import org.snmp4j.smi.Counter64;
import org.snmp4j.smi.Integer32;
import org.snmp4j.smi.IpAddress;
import org.snmp4j.smi.Null;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.Opaque;
import org.snmp4j.smi.SMIConstants;
import org.snmp4j.smi.TimeTicks;
import org.snmp4j.smi.UnsignedInteger32;
import org.snmp4j.smi.Variable;
class Snmp4JValue implements SnmpValue {
Variable m_value;
Snmp4JValue(Variable value) {
m_value = value;
}
Snmp4JValue(int syntax, byte[] bytes) {
switch (syntax) {
case SMIConstants.SYNTAX_INTEGER: {
BigInteger val = new BigInteger(bytes);
m_value = new Integer32(val.intValue());
break;
}
case SMIConstants.SYNTAX_COUNTER32: {
BigInteger val = new BigInteger(bytes);
m_value = new Counter32(val.longValue());
break;
}
case SMIConstants.SYNTAX_COUNTER64: {
BigInteger val = new BigInteger(bytes);
m_value = new Counter64(val.longValue());
break;
}
case SMIConstants.SYNTAX_TIMETICKS: {
BigInteger val = new BigInteger(bytes);
m_value = new TimeTicks(val.longValue());
break;
}
case SMIConstants.SYNTAX_UNSIGNED_INTEGER32: {
BigInteger val = new BigInteger(bytes);
m_value = new UnsignedInteger32(val.longValue());
break;
}
case SMIConstants.SYNTAX_IPADDRESS: {
try {
InetAddress addr = InetAddress.getByAddress(bytes);
m_value = new IpAddress(addr);
} catch (UnknownHostException e) {
throw new IllegalArgumentException("unable to create InetAddress from bytes: "+e.getMessage());
}
break;
}
case SMIConstants.SYNTAX_OBJECT_IDENTIFIER: {
m_value = new OID(new String(bytes));
break;
}
case SMIConstants.SYNTAX_OCTET_STRING: {
m_value = new OctetString(bytes);
break;
}
case SMIConstants.SYNTAX_OPAQUE: {
m_value = new Opaque(bytes);
break;
}
case SMIConstants.SYNTAX_NULL: {
m_value = new Null();
break;
}
default:
throw new IllegalArgumentException("invalid syntax "+syntax);
}
}
public byte[] getBytes() {
switch (m_value.getSyntax()) {
case SMIConstants.SYNTAX_INTEGER:
case SMIConstants.SYNTAX_COUNTER32:
case SMIConstants.SYNTAX_COUNTER64:
case SMIConstants.SYNTAX_TIMETICKS:
case SMIConstants.SYNTAX_UNSIGNED_INTEGER32:
return toBigInteger().toByteArray();
case SMIConstants.SYNTAX_IPADDRESS:
return toInetAddress().getAddress();
case SMIConstants.SYNTAX_OBJECT_IDENTIFIER:
return toSnmpObjId().toString().getBytes();
case SMIConstants.SYNTAX_OCTET_STRING:
return ((OctetString)m_value).getValue();
case SMIConstants.SYNTAX_OPAQUE:
return((Opaque)m_value).getValue();
case SMIConstants.SYNTAX_NULL:
return new byte[0];
default:
throw new IllegalArgumentException("cannot convert "+m_value+" to a byte array");
}
}
public int getType() {
return m_value.getSyntax();
}
public boolean isEndOfMib() {
return m_value.getSyntax() == SMIConstants.EXCEPTION_END_OF_MIB_VIEW;
}
public boolean isNumeric() {
switch (m_value.getSyntax()) {
case SMIConstants.SYNTAX_INTEGER:
case SMIConstants.SYNTAX_COUNTER32:
case SMIConstants.SYNTAX_COUNTER64:
case SMIConstants.SYNTAX_TIMETICKS:
case SMIConstants.SYNTAX_UNSIGNED_INTEGER32:
return true;
default:
return false;
}
}
public int toInt() {
switch (m_value.getSyntax()) {
case SMIConstants.SYNTAX_COUNTER64:
return (int)((Counter64)m_value).getValue();
case SMIConstants.SYNTAX_INTEGER:
return ((Integer32)m_value).getValue();
case SMIConstants.SYNTAX_COUNTER32:
case SMIConstants.SYNTAX_TIMETICKS:
case SMIConstants.SYNTAX_UNSIGNED_INTEGER32:
return (int)((UnsignedInteger32)m_value).getValue();
default:
return Integer.parseInt(m_value.toString());
}
}
public long toLong() {
switch (m_value.getSyntax()) {
case SMIConstants.SYNTAX_COUNTER64:
return ((Counter64)m_value).getValue();
case SMIConstants.SYNTAX_INTEGER:
return ((Integer32)m_value).getValue();
case SMIConstants.SYNTAX_COUNTER32:
case SMIConstants.SYNTAX_TIMETICKS:
case SMIConstants.SYNTAX_UNSIGNED_INTEGER32:
return ((UnsignedInteger32)m_value).getValue();
case SMIConstants.SYNTAX_OCTET_STRING:
return (convertStringToLong());
default:
return Integer.parseInt(m_value.toString());
}
}
private long convertStringToLong() {
return Float.valueOf(m_value.toString()).longValue();
}
public String toDisplayString() {
switch (m_value.getSyntax()) {
case SMIConstants.SYNTAX_OBJECT_IDENTIFIER :
return SnmpObjId.get(((OID)m_value).getValue()).toString();
case SMIConstants.SYNTAX_TIMETICKS :
return Long.toString(toLong());
case SMIConstants.SYNTAX_OCTET_STRING :
return toStringDottingCntrlChars(((OctetString)m_value).getValue());
default :
return m_value.toString();
}
}
private String toStringDottingCntrlChars(byte[] value) {
byte[] results = new byte[value.length];
for (int i = 0; i < value.length; i++) {
results[i] = Character.isISOControl((char)value[i]) ? (byte)'.' : value[i];
}
return new String(results);
}
public InetAddress toInetAddress() {
switch (m_value.getSyntax()) {
case SMIConstants.SYNTAX_IPADDRESS:
return ((IpAddress)m_value).getInetAddress();
default:
throw new IllegalArgumentException("cannot convert "+m_value+" to an InetAddress");
}
}
public String toHexString() {
switch (m_value.getSyntax()) {
case SMIConstants.SYNTAX_OCTET_STRING:
return ((OctetString)m_value).toHexString().replaceAll(":", "");
default:
throw new IllegalArgumentException("cannot convert "+m_value+" to a HexString");
}
}
public String toString() {
return toDisplayString();
}
public BigInteger toBigInteger() {
switch (m_value.getSyntax()) {
case SMIConstants.SYNTAX_COUNTER64:
Counter64 cnt = (Counter64)m_value;
if (cnt.getValue() > 0)
return BigInteger.valueOf(cnt.getValue());
else {
return new BigInteger(cnt.toString());
}
case SMIConstants.SYNTAX_INTEGER:
return BigInteger.valueOf(((Integer32)m_value).getValue());
case SMIConstants.SYNTAX_COUNTER32:
case SMIConstants.SYNTAX_TIMETICKS:
case SMIConstants.SYNTAX_UNSIGNED_INTEGER32:
return BigInteger.valueOf(((UnsignedInteger32)m_value).getValue());
default:
return new BigInteger(m_value.toString());
}
}
public SnmpObjId toSnmpObjId() {
switch (m_value.getSyntax()) {
case SMIConstants.SYNTAX_OBJECT_IDENTIFIER:
return SnmpObjId.get(((OID)m_value).getValue());
default:
throw new IllegalArgumentException("cannot convert "+m_value+" to an SnmpObjId");
}
}
public boolean isDisplayable() {
if (isNumeric())
return true;
if (getType() == SnmpValue.SNMP_OBJECT_IDENTIFIER || getType() == SnmpValue.SNMP_IPADDRESS)
return true;
if (getType() == SnmpValue.SNMP_OCTET_STRING) {
return allBytesDisplayable(getBytes());
}
return false;
}
private boolean allBytesDisplayable(byte[] bytes) {
for(int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
if ((b < 32 && b != 9 && b != 10 && b != 13 && b != 0) || b == 127)
return false;
}
return true;
}
public boolean isNull() {
return getType() == SnmpValue.SNMP_NULL;
}
public Variable getVariable() {
return m_value;
}
} | Make sure that the value cannot be null in the constructor.
| opennms-snmp/opennms-snmp-snmp4j/src/main/java/org/opennms/netmgt/snmp/snmp4j/Snmp4JValue.java | Make sure that the value cannot be null in the constructor. |
|
Java | lgpl-2.1 | 8bc2117b437869d84e3e1ad4e6db3bd499333605 | 0 | xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.xpn.xwiki.doc;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.Vector;
import junit.framework.Assert;
import org.jmock.Mock;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.EntityReference;
import org.xwiki.model.reference.ObjectReference;
import org.xwiki.rendering.syntax.Syntax;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiConfig;
import com.xpn.xwiki.XWikiConstant;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.api.DocumentSection;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.StringProperty;
import com.xpn.xwiki.objects.classes.BaseClass;
import com.xpn.xwiki.objects.classes.TextAreaClass;
import com.xpn.xwiki.render.XWikiRenderingEngine;
import com.xpn.xwiki.store.XWikiStoreInterface;
import com.xpn.xwiki.store.XWikiVersioningStoreInterface;
import com.xpn.xwiki.test.AbstractBridgedXWikiComponentTestCase;
import com.xpn.xwiki.user.api.XWikiRightService;
import com.xpn.xwiki.web.XWikiMessageTool;
/**
* Unit tests for {@link XWikiDocument}.
*
* @version $Id$
*/
public class XWikiDocumentTest extends AbstractBridgedXWikiComponentTestCase
{
private static final String DOCWIKI = "Wiki";
private static final String DOCSPACE = "Space";
private static final String DOCNAME = "Page";
private static final String DOCFULLNAME = DOCSPACE + "." + DOCNAME;
private static final String CLASSNAME = DOCFULLNAME;
private XWikiDocument document;
private XWikiDocument translatedDocument;
private Mock mockXWiki;
private Mock mockXWikiRenderingEngine;
private Mock mockXWikiVersioningStore;
private Mock mockXWikiStoreInterface;
private Mock mockXWikiMessageTool;
private Mock mockXWikiRightService;
private BaseClass baseClass;
private BaseObject baseObject;
@Override
protected void setUp() throws Exception
{
super.setUp();
this.document = new XWikiDocument(new DocumentReference(DOCWIKI, DOCSPACE, DOCNAME));
this.document.setSyntax(Syntax.XWIKI_1_0);
this.document.setLanguage("en");
this.document.setDefaultLanguage("en");
this.document.setNew(false);
this.translatedDocument = new XWikiDocument();
this.translatedDocument.setSyntax(Syntax.XWIKI_2_0);
this.translatedDocument.setLanguage("fr");
this.translatedDocument.setNew(false);
getContext().put("isInRenderingEngine", true);
this.mockXWiki = mock(XWiki.class);
this.mockXWiki.stubs().method("Param").will(returnValue(null));
this.mockXWikiRenderingEngine = mock(XWikiRenderingEngine.class);
this.mockXWikiVersioningStore = mock(XWikiVersioningStoreInterface.class);
this.mockXWikiVersioningStore.stubs().method("getXWikiDocumentArchive").will(returnValue(null));
this.mockXWikiStoreInterface = mock(XWikiStoreInterface.class);
this.document.setStore((XWikiStoreInterface) this.mockXWikiStoreInterface.proxy());
this.mockXWikiMessageTool =
mock(XWikiMessageTool.class, new Class[] {ResourceBundle.class, XWikiContext.class}, new Object[] {
null, getContext()});
this.mockXWikiMessageTool.stubs().method("get").will(returnValue("message"));
this.mockXWikiRightService = mock(XWikiRightService.class);
this.mockXWikiRightService.stubs().method("hasProgrammingRights").will(returnValue(true));
this.mockXWiki.stubs().method("getRenderingEngine").will(returnValue(this.mockXWikiRenderingEngine.proxy()));
this.mockXWiki.stubs().method("getVersioningStore").will(returnValue(this.mockXWikiVersioningStore.proxy()));
this.mockXWiki.stubs().method("getStore").will(returnValue(this.mockXWikiStoreInterface.proxy()));
this.mockXWiki.stubs().method("getDocument").will(returnValue(this.document));
this.mockXWiki.stubs().method("getLanguagePreference").will(returnValue("en"));
this.mockXWiki.stubs().method("getSectionEditingDepth").will(returnValue(2L));
this.mockXWiki.stubs().method("getRightService").will(returnValue(this.mockXWikiRightService.proxy()));
getContext().setWiki((XWiki) this.mockXWiki.proxy());
getContext().put("msg", this.mockXWikiMessageTool.proxy());
this.baseClass = this.document.getxWikiClass();
this.baseClass.addTextField("string", "String", 30);
this.baseClass.addTextAreaField("area", "Area", 10, 10);
this.baseClass.addTextAreaField("puretextarea", "Pure text area", 10, 10);
// set the text areas an non interpreted content
((TextAreaClass) this.baseClass.getField("puretextarea")).setContentType("puretext");
this.baseClass.addPasswordField("passwd", "Password", 30);
this.baseClass.addBooleanField("boolean", "Boolean", "yesno");
this.baseClass.addNumberField("int", "Int", 10, "integer");
this.baseClass.addStaticListField("stringlist", "StringList", "value1, value2");
this.mockXWiki.stubs().method("getClass").will(returnValue(this.baseClass));
this.mockXWiki.stubs().method("getXClass").will(returnValue(this.baseClass));
this.baseObject = this.document.newObject(CLASSNAME, getContext());
this.baseObject.setStringValue("string", "string");
this.baseObject.setLargeStringValue("area", "area");
this.baseObject.setStringValue("passwd", "passwd");
this.baseObject.setIntValue("boolean", 1);
this.baseObject.setIntValue("int", 42);
this.baseObject.setStringListValue("stringlist", Arrays.asList("VALUE1", "VALUE2"));
this.mockXWikiStoreInterface.stubs().method("search").will(returnValue(new ArrayList<XWikiDocument>()));
}
public void testDeprecatedConstructors()
{
DocumentReference defaultReference = new DocumentReference("xwiki", "Main", "WebHome");
XWikiDocument doc = new XWikiDocument(null);
assertEquals(defaultReference, doc.getDocumentReference());
doc = new XWikiDocument();
assertEquals(defaultReference, doc.getDocumentReference());
doc = new XWikiDocument("notused", "space.page");
assertEquals("space", doc.getSpaceName());
assertEquals("page", doc.getPageName());
assertEquals("xwiki", doc.getWikiName());
doc = new XWikiDocument("space", "page");
assertEquals("space", doc.getSpaceName());
assertEquals("page", doc.getPageName());
assertEquals("xwiki", doc.getWikiName());
doc = new XWikiDocument("wiki", "space", "page");
assertEquals("space", doc.getSpaceName());
assertEquals("page", doc.getPageName());
assertEquals("wiki", doc.getWikiName());
doc = new XWikiDocument("wiki", "notused", "notused:space.page");
assertEquals("space", doc.getSpaceName());
assertEquals("page", doc.getPageName());
assertEquals("wiki", doc.getWikiName());
}
public void testGetDisplayTitleWhenNoTitleAndNoContent()
{
this.document.setContent("Some content");
assertEquals("Page", this.document.getDisplayTitle(getContext()));
}
public void testGetDisplayWhenTitleExists()
{
this.document.setContent("Some content");
this.document.setTitle("Title");
this.mockXWikiRenderingEngine.expects(once()).method("interpretText").with(eq("Title"), ANYTHING, ANYTHING).will(
returnValue("Title"));
assertEquals("Title", this.document.getDisplayTitle(getContext()));
}
public void testGetDisplayWhenNoTitleButSectionExists()
{
this.document.setContent("Some content\n1 Title");
this.mockXWikiRenderingEngine.expects(once()).method("interpretText").with(eq("Title"), ANYTHING, ANYTHING).will(
returnValue("Title"));
assertEquals("Title", this.document.getDisplayTitle(getContext()));
}
public void testGetRenderedTitleWhenMatchingTitleHeaderDepth()
{
this.document.setContent("=== level3");
this.document.setSyntax(Syntax.XWIKI_2_0);
this.mockXWiki.stubs().method("ParamAsLong").will(returnValue(3L));
assertEquals("level3", this.document.getRenderedTitle(Syntax.XHTML_1_0, getContext()));
}
public void testGetRenderedTitleWhenNotMatchingTitleHeaderDepth()
{
this.document.setContent("=== level3");
this.document.setSyntax(Syntax.XWIKI_2_0);
this.mockXWiki.stubs().method("ParamAsLong").will(returnValue(2L));
assertEquals("Page", this.document.getRenderedTitle(Syntax.XHTML_1_0, getContext()));
}
/**
* Verify that if an error happens when evaluation the title, we fallback to the computed title.
*/
public void testGetDisplayTitleWhenVelocityError()
{
this.document.setContent("Some content");
this.document.setTitle("some content that generate a velocity error");
this.mockXWikiRenderingEngine.expects(once()).method("interpretText").will(
returnValue("... blah blah ... <div id=\"xwikierror105\" ... blah blah ..."));
assertEquals("Page", this.document.getDisplayTitle(getContext()));
}
public void testMinorMajorVersions()
{
// there is no version in doc yet, so 1.1
assertEquals("1.1", this.document.getVersion());
this.document.setMinorEdit(false);
this.document.incrementVersion();
// no version => incrementVersion sets 1.1
assertEquals("1.1", this.document.getVersion());
this.document.setMinorEdit(false);
this.document.incrementVersion();
// increment major version
assertEquals("2.1", this.document.getVersion());
this.document.setMinorEdit(true);
this.document.incrementVersion();
// increment minor version
assertEquals("2.2", this.document.getVersion());
}
public void testGetPreviousVersion() throws XWikiException
{
this.mockXWiki.stubs().method("getEncoding").will(returnValue("UTF-8"));
this.mockXWiki.stubs().method("getConfig").will(returnValue(new XWikiConfig()));
XWikiContext context = this.getContext();
Date now = new Date();
XWikiDocumentArchive archiveDoc = new XWikiDocumentArchive(this.document.getId());
this.document.setDocumentArchive(archiveDoc);
assertEquals("1.1", this.document.getVersion());
assertNull(this.document.getPreviousVersion());
this.document.incrementVersion();
archiveDoc.updateArchive(this.document, "Admin", now, "", this.document.getRCSVersion(), context);
assertEquals("1.1", this.document.getVersion());
assertNull(this.document.getPreviousVersion());
this.document.setMinorEdit(true);
this.document.incrementVersion();
archiveDoc.updateArchive(this.document, "Admin", now, "", this.document.getRCSVersion(), context);
assertEquals("1.2", this.document.getVersion());
assertEquals("1.1", this.document.getPreviousVersion());
this.document.setMinorEdit(false);
this.document.incrementVersion();
archiveDoc.updateArchive(this.document, "Admin", now, "", this.document.getRCSVersion(), context);
assertEquals("2.1", this.document.getVersion());
assertEquals("1.2", this.document.getPreviousVersion());
this.document.setMinorEdit(true);
this.document.incrementVersion();
archiveDoc.updateArchive(this.document, "Admin", now, "", this.document.getRCSVersion(), context);
assertEquals("2.2", this.document.getVersion());
assertEquals("2.1", this.document.getPreviousVersion());
archiveDoc.resetArchive();
assertEquals("2.2", this.document.getVersion());
assertNull(this.document.getPreviousVersion());
}
public void testAuthorAfterDocumentCopy() throws XWikiException
{
DocumentReference author = new DocumentReference("Wiki", "XWiki", "Albatross");
this.document.setAuthorReference(author);
XWikiDocument copy = this.document.copyDocument(this.document.getName() + " Copy", getContext());
assertEquals(author, copy.getAuthorReference());
}
public void testCreatorAfterDocumentCopy() throws XWikiException
{
DocumentReference creator = new DocumentReference("Wiki", "XWiki", "Condor");
this.document.setCreatorReference(creator);
XWikiDocument copy = this.document.copyDocument(this.document.getName() + " Copy", getContext());
assertEquals(creator, copy.getCreatorReference());
}
public void testCreationDateAfterDocumentCopy() throws Exception
{
Date sourceCreationDate = this.document.getCreationDate();
Thread.sleep(1000);
XWikiDocument copy = this.document.copyDocument(this.document.getName() + " Copy", getContext());
assertEquals(sourceCreationDate, copy.getCreationDate());
}
public void testObjectGuidsAfterDocumentCopy() throws Exception
{
assertTrue(this.document.getXObjects().size() > 0);
List<String> originalGuids = new ArrayList<String>();
for (Map.Entry<DocumentReference, List<BaseObject>> entry : this.document.getXObjects().entrySet()) {
for (BaseObject baseObject : entry.getValue()) {
originalGuids.add(baseObject.getGuid());
}
}
XWikiDocument copy = this.document.copyDocument(this.document.getName() + " Copy", getContext());
// Verify that the cloned objects have different GUIDs
for (Map.Entry<DocumentReference, List<BaseObject>> entry : copy.getXObjects().entrySet()) {
for (BaseObject baseObject : entry.getValue()) {
assertFalse("Non unique object GUID found!", originalGuids.contains(baseObject.getGuid()));
}
}
}
public void testRelativeObjectReferencesAfterDocumentCopy() throws Exception
{
XWikiDocument copy = this.document.copyDocument(new DocumentReference("copywiki", "copyspace", "copypage"),
getContext());
// Verify that the XObject's XClass reference points to the target wiki and not the old wiki.
// This tests the XObject cache.
DocumentReference targetXClassReference = new DocumentReference("copywiki", DOCSPACE, DOCNAME);
assertNotNull(copy.getXObject(targetXClassReference));
// Also verify that actual XObject's reference (not from the cache).
assertEquals(1, copy.getXObjects().size());
BaseObject bobject = copy.getXObjects().get(copy.getXObjects().keySet().iterator().next()).get(0);
assertEquals(new DocumentReference("copywiki", DOCSPACE, DOCNAME), bobject.getXClassReference());
}
public void testCloneNullObjects() throws XWikiException
{
XWikiDocument document = new XWikiDocument(new DocumentReference("wiki", DOCSPACE, DOCNAME));
EntityReference relativeClassReference =
new EntityReference(DOCNAME, EntityType.DOCUMENT, new EntityReference(DOCSPACE, EntityType.SPACE));
DocumentReference classReference = new DocumentReference("wiki", DOCSPACE, DOCNAME);
DocumentReference duplicatedClassReference = new DocumentReference("otherwiki", DOCSPACE, DOCNAME);
// no object
XWikiDocument clonedDocument = document.clone();
assertTrue(clonedDocument.getXObjects().isEmpty());
XWikiDocument duplicatedDocument = document.duplicate(new DocumentReference("otherwiki", DOCSPACE, DOCNAME));
assertTrue(duplicatedDocument.getXObjects().isEmpty());
// 1 null object
document.addXObject(classReference, null);
clonedDocument = document.clone();
assertEquals(1, clonedDocument.getXObjects(classReference).size());
assertEquals(document.getXObjects(classReference), clonedDocument.getXObjects(classReference));
duplicatedDocument = document.duplicate(new DocumentReference("otherwiki", DOCSPACE, DOCNAME));
assertTrue(duplicatedDocument.getXObjects().isEmpty());
// 1 null object and 1 object
BaseObject object = new BaseObject();
object.setXClassReference(relativeClassReference);
document.addXObject(object);
clonedDocument = document.clone();
assertEquals(2, clonedDocument.getXObjects(classReference).size());
assertEquals(document.getXObjects(classReference), clonedDocument.getXObjects(classReference));
duplicatedDocument = document.duplicate(new DocumentReference("otherwiki", DOCSPACE, DOCNAME));
assertEquals(2, duplicatedDocument.getXObjects(duplicatedClassReference).size());
}
public void testCloneWithAbsoluteClassReference()
{
XWikiDocument document = new XWikiDocument(new DocumentReference("wiki", DOCSPACE, DOCNAME));
EntityReference relativeClassReference =
new EntityReference(DOCNAME, EntityType.DOCUMENT, new EntityReference(DOCSPACE, EntityType.SPACE));
DocumentReference classReference = new DocumentReference("wiki", DOCSPACE, DOCNAME);
DocumentReference duplicatedClassReference = new DocumentReference("otherwiki", DOCSPACE, DOCNAME);
BaseObject object = new BaseObject();
object.setXClassReference(relativeClassReference);
document.addXObject(object);
BaseObject object2 = new BaseObject();
object2.setXClassReference(classReference);
document.addXObject(object2);
BaseObject object3 = new BaseObject();
object3.setXClassReference(relativeClassReference);
document.addXObject(object3);
XWikiDocument clonedDocument = document.clone();
assertEquals(3, clonedDocument.getXObjects(classReference).size());
assertEquals(document.getXObjects(classReference), clonedDocument.getXObjects(classReference));
XWikiDocument duplicatedDocument = document.duplicate(new DocumentReference("otherwiki", DOCSPACE, DOCNAME));
assertNotNull(duplicatedDocument.getXObject(duplicatedClassReference, 0));
assertNotNull(duplicatedDocument.getXObject(classReference, 1));
assertNotNull(duplicatedDocument.getXObject(duplicatedClassReference, 2));
}
public void testToStringReturnsFullName()
{
assertEquals("Space.Page", this.document.toString());
assertEquals("Main.WebHome", new XWikiDocument().toString());
}
public void testCloneSaveVersions()
{
XWikiDocument doc1 = new XWikiDocument(new DocumentReference("qwe", "qwe", "qwe"));
XWikiDocument doc2 = doc1.clone();
doc1.incrementVersion();
doc2.incrementVersion();
assertEquals(doc1.getVersion(), doc2.getVersion());
}
public void testAddObject() throws XWikiException
{
XWikiDocument doc = new XWikiDocument(new DocumentReference("test", "test", "document"));
this.mockXWiki.stubs().method("getClass").will(returnValue(new BaseClass()));
BaseObject object = BaseClass.newCustomClassInstance("XWiki.XWikiUsers", getContext());
doc.addObject("XWiki.XWikiUsers", object);
assertEquals("XWikiDocument.addObject does not set the object's name", doc.getFullName(), object.getName());
}
public void testObjectNumbersAfterXMLRoundrip() throws XWikiException
{
String classname = XWikiConstant.TAG_CLASS;
BaseClass tagClass = new BaseClass();
tagClass.setName(classname);
tagClass.addStaticListField(XWikiConstant.TAG_CLASS_PROP_TAGS, "Tags", 30, true, "", "checkbox");
XWikiDocument doc = new XWikiDocument(new DocumentReference("test", "test", "document"));
this.mockXWiki.stubs().method("getXClass").will(returnValue(tagClass));
this.mockXWiki.stubs().method("getEncoding").will(returnValue("iso-8859-1"));
BaseObject object = BaseClass.newCustomClassInstance(classname, getContext());
object.setClassName(classname);
doc.addObject(classname, object);
object = BaseClass.newCustomClassInstance(classname, getContext());
object.setClassName(classname);
doc.addObject(classname, object);
object = BaseClass.newCustomClassInstance(classname, getContext());
object.setClassName(classname);
doc.addObject(classname, object);
doc.setObject(classname, 1, null);
String docXML = doc.toXML(getContext());
XWikiDocument docFromXML = new XWikiDocument();
docFromXML.fromXML(docXML);
Vector<BaseObject> objects = doc.getObjects(classname);
Vector<BaseObject> objectsFromXML = docFromXML.getObjects(classname);
assertNotNull(objects);
assertNotNull(objectsFromXML);
assertTrue(objects.size() == objectsFromXML.size());
for (int i = 0; i < objects.size(); i++) {
if (objects.get(i) == null) {
assertNull(objectsFromXML.get(i));
} else {
assertTrue(objects.get(i).getNumber() == objectsFromXML.get(i).getNumber());
}
}
}
public void testGetUniqueLinkedPages10()
{
XWikiDocument contextDocument =
new XWikiDocument(new DocumentReference("contextdocwiki", "contextdocspace", "contextdocpage"));
getContext().setDoc(contextDocument);
this.mockXWiki.stubs().method("exists").will(returnValue(true));
this.document.setContent("[TargetPage][TargetLabel>TargetPage][TargetSpace.TargetPage]"
+ "[TargetLabel>TargetSpace.TargetPage?param=value#anchor][http://externallink][mailto:mailto][label>]");
Set<String> linkedPages = this.document.getUniqueLinkedPages(getContext());
assertEquals(new HashSet<String>(Arrays.asList("TargetPage", "TargetSpace.TargetPage")), new HashSet<String>(
linkedPages));
}
public void testGetUniqueLinkedPages()
{
XWikiDocument contextDocument =
new XWikiDocument(new DocumentReference("contextdocwiki", "contextdocspace", "contextdocpage"));
getContext().setDoc(contextDocument);
this.document.setContent("[[TargetPage]][[TargetLabel>>TargetPage]][[TargetSpace.TargetPage]]"
+ "[[TargetLabel>>TargetSpace.TargetPage?param=value#anchor]][[http://externallink]][[mailto:mailto]]"
+ "[[]][[#anchor]][[?param=value]][[targetwiki:TargetSpace.TargetPage]]");
this.document.setSyntax(Syntax.XWIKI_2_0);
Set<String> linkedPages = this.document.getUniqueLinkedPages(getContext());
assertEquals(new LinkedHashSet<String>(Arrays.asList("Space.TargetPage", "TargetSpace.TargetPage",
"targetwiki:TargetSpace.TargetPage")), linkedPages);
}
public void testGetSections10() throws XWikiException
{
this.document.setContent("content not in section\n" + "1 header 1\nheader 1 content\n"
+ "1.1 header 2\nheader 2 content");
List<DocumentSection> headers = this.document.getSections();
assertEquals(2, headers.size());
DocumentSection header1 = headers.get(0);
DocumentSection header2 = headers.get(1);
assertEquals("header 1", header1.getSectionTitle());
assertEquals(23, header1.getSectionIndex());
assertEquals(1, header1.getSectionNumber());
assertEquals("1", header1.getSectionLevel());
assertEquals("header 2", header2.getSectionTitle());
assertEquals(51, header2.getSectionIndex());
assertEquals(2, header2.getSectionNumber());
assertEquals("1.1", header2.getSectionLevel());
}
public void testGetSections() throws XWikiException
{
this.document.setContent("content not in section\n" + "= header 1=\nheader 1 content\n"
+ "== header 2==\nheader 2 content");
this.document.setSyntax(Syntax.XWIKI_2_0);
List<DocumentSection> headers = this.document.getSections();
assertEquals(2, headers.size());
DocumentSection header1 = headers.get(0);
DocumentSection header2 = headers.get(1);
assertEquals("header 1", header1.getSectionTitle());
assertEquals(-1, header1.getSectionIndex());
assertEquals(1, header1.getSectionNumber());
assertEquals("1", header1.getSectionLevel());
assertEquals("header 2", header2.getSectionTitle());
assertEquals(-1, header2.getSectionIndex());
assertEquals(2, header2.getSectionNumber());
assertEquals("1.1", header2.getSectionLevel());
}
public void testGetDocumentSection10() throws XWikiException
{
this.document.setContent("content not in section\n" + "1 header 1\nheader 1 content\n"
+ "1.1 header 2\nheader 2 content");
DocumentSection header1 = this.document.getDocumentSection(1);
DocumentSection header2 = this.document.getDocumentSection(2);
assertEquals("header 1", header1.getSectionTitle());
assertEquals(23, header1.getSectionIndex());
assertEquals(1, header1.getSectionNumber());
assertEquals("1", header1.getSectionLevel());
assertEquals("header 2", header2.getSectionTitle());
assertEquals(51, header2.getSectionIndex());
assertEquals(2, header2.getSectionNumber());
assertEquals("1.1", header2.getSectionLevel());
}
public void testGetDocumentSection() throws XWikiException
{
this.document.setContent("content not in section\n" + "= header 1=\nheader 1 content\n"
+ "== header 2==\nheader 2 content");
this.document.setSyntax(Syntax.XWIKI_2_0);
DocumentSection header1 = this.document.getDocumentSection(1);
DocumentSection header2 = this.document.getDocumentSection(2);
assertEquals("header 1", header1.getSectionTitle());
assertEquals(-1, header1.getSectionIndex());
assertEquals(1, header1.getSectionNumber());
assertEquals("1", header1.getSectionLevel());
assertEquals("header 2", header2.getSectionTitle());
assertEquals(-1, header2.getSectionIndex());
assertEquals(2, header2.getSectionNumber());
assertEquals("1.1", header2.getSectionLevel());
}
public void testGetContentOfSection10() throws XWikiException
{
this.document.setContent("content not in section\n" + "1 header 1\nheader 1 content\n"
+ "1.1 header 2\nheader 2 content");
String content1 = this.document.getContentOfSection(1);
String content2 = this.document.getContentOfSection(2);
assertEquals("1 header 1\nheader 1 content\n1.1 header 2\nheader 2 content", content1);
assertEquals("1.1 header 2\nheader 2 content", content2);
}
public void testGetContentOfSection() throws XWikiException
{
this.document.setContent("content not in section\n" + "= header 1=\nheader 1 content\n"
+ "== header 2==\nheader 2 content\n" + "=== header 3===\nheader 3 content\n"
+ "== header 4==\nheader 4 content");
this.document.setSyntax(Syntax.XWIKI_2_0);
String content1 = this.document.getContentOfSection(1);
String content2 = this.document.getContentOfSection(2);
String content3 = this.document.getContentOfSection(3);
assertEquals("= header 1 =\n\nheader 1 content\n\n== header 2 ==\n\nheader 2 content\n\n"
+ "=== header 3 ===\n\nheader 3 content\n\n== header 4 ==\n\nheader 4 content", content1);
assertEquals("== header 2 ==\n\nheader 2 content\n\n=== header 3 ===\n\nheader 3 content", content2);
assertEquals("== header 4 ==\n\nheader 4 content", content3);
// Validate that third level header is not skipped anymore
this.mockXWiki.stubs().method("getSectionEditingDepth").will(returnValue(3L));
content3 = this.document.getContentOfSection(3);
String content4 = this.document.getContentOfSection(4);
assertEquals("=== header 3 ===\n\nheader 3 content", content3);
assertEquals("== header 4 ==\n\nheader 4 content", content4);
}
public void testSectionSplit10() throws XWikiException
{
List<DocumentSection> sections;
// Simple test
this.document.setContent("1 Section 1\n" + "Content of first section\n" + "1.1 Subsection 2\n"
+ "Content of second section\n" + "1 Section 3\n" + "Content of section 3");
sections = this.document.getSections();
assertEquals(3, sections.size());
assertEquals("Section 1", sections.get(0).getSectionTitle());
assertEquals("1 Section 1\n" + "Content of first section\n" + "1.1 Subsection 2\n"
+ "Content of second section\n", this.document.getContentOfSection(1));
assertEquals("1.1", sections.get(1).getSectionLevel());
assertEquals("1.1 Subsection 2\nContent of second section\n", this.document.getContentOfSection(2));
assertEquals(3, sections.get(2).getSectionNumber());
assertEquals(80, sections.get(2).getSectionIndex());
assertEquals("1 Section 3\nContent of section 3", this.document.getContentOfSection(3));
// Test comments don't break the section editing
this.document.setContent("1 Section 1\n" + "Content of first section\n" + "## 1.1 Subsection 2\n"
+ "Content of second section\n" + "1 Section 3\n" + "Content of section 3");
sections = this.document.getSections();
assertEquals(2, sections.size());
assertEquals("Section 1", sections.get(0).getSectionTitle());
assertEquals("1", sections.get(1).getSectionLevel());
assertEquals(2, sections.get(1).getSectionNumber());
assertEquals(83, sections.get(1).getSectionIndex());
// Test spaces are ignored
this.document.setContent("1 Section 1\n" + "Content of first section\n" + " 1.1 Subsection 2 \n"
+ "Content of second section\n" + "1 Section 3\n" + "Content of section 3");
sections = this.document.getSections();
assertEquals(3, sections.size());
assertEquals("Subsection 2 ", sections.get(1).getSectionTitle());
assertEquals("1.1", sections.get(1).getSectionLevel());
// Test lower headings are ignored
this.document.setContent("1 Section 1\n" + "Content of first section\n" + "1.1.1 Lower subsection\n"
+ "This content is not important\n" + " 1.1 Subsection 2 \n" + "Content of second section\n"
+ "1 Section 3\n" + "Content of section 3");
sections = this.document.getSections();
assertEquals(3, sections.size());
assertEquals("Section 1", sections.get(0).getSectionTitle());
assertEquals("Subsection 2 ", sections.get(1).getSectionTitle());
assertEquals("1.1", sections.get(1).getSectionLevel());
// Test blank lines are preserved
this.document.setContent("\n\n1 Section 1\n\n\n" + "Content of first section\n\n\n"
+ " 1.1 Subsection 2 \n\n" + "Content of second section\n" + "1 Section 3\n" + "Content of section 3");
sections = this.document.getSections();
assertEquals(3, sections.size());
assertEquals(2, sections.get(0).getSectionIndex());
assertEquals("Subsection 2 ", sections.get(1).getSectionTitle());
assertEquals(43, sections.get(1).getSectionIndex());
}
public void testUpdateDocumentSection10() throws XWikiException
{
List<DocumentSection> sections;
// Fill the document
this.document.setContent("1 Section 1\n" + "Content of first section\n" + "1.1 Subsection 2\n"
+ "Content of second section\n" + "1 Section 3\n" + "Content of section 3");
String content = this.document.updateDocumentSection(3, "1 Section 3\n" + "Modified content of section 3");
assertEquals("1 Section 1\n" + "Content of first section\n" + "1.1 Subsection 2\n"
+ "Content of second section\n" + "1 Section 3\n" + "Modified content of section 3", content);
this.document.setContent(content);
sections = this.document.getSections();
assertEquals(3, sections.size());
assertEquals("Section 1", sections.get(0).getSectionTitle());
assertEquals("1 Section 1\n" + "Content of first section\n" + "1.1 Subsection 2\n"
+ "Content of second section\n", this.document.getContentOfSection(1));
assertEquals("1.1", sections.get(1).getSectionLevel());
assertEquals("1.1 Subsection 2\nContent of second section\n", this.document.getContentOfSection(2));
assertEquals(3, sections.get(2).getSectionNumber());
assertEquals(80, sections.get(2).getSectionIndex());
assertEquals("1 Section 3\nModified content of section 3", this.document.getContentOfSection(3));
}
public void testUpdateDocumentSection() throws XWikiException
{
this.document.setContent("content not in section\n" + "= header 1=\nheader 1 content\n"
+ "== header 2==\nheader 2 content");
this.document.setSyntax(Syntax.XWIKI_2_0);
// Modify section content
String content1 = this.document.updateDocumentSection(2, "== header 2==\nmodified header 2 content");
assertEquals(
"content not in section\n\n= header 1 =\n\nheader 1 content\n\n== header 2 ==\n\nmodified header 2 content",
content1);
String content2 =
this.document.updateDocumentSection(1,
"= header 1 =\n\nmodified also header 1 content\n\n== header 2 ==\n\nheader 2 content");
assertEquals(
"content not in section\n\n= header 1 =\n\nmodified also header 1 content\n\n== header 2 ==\n\nheader 2 content",
content2);
// Remove a section
String content3 = this.document.updateDocumentSection(2, "");
assertEquals("content not in section\n\n= header 1 =\n\nheader 1 content", content3);
}
public void testDisplay10()
{
this.mockXWiki.stubs().method("getCurrentContentSyntaxId").will(returnValue("xwiki/1.0"));
assertEquals("string", this.document.display("string", "view", getContext()));
assertEquals(
"{pre}<input size='30' id='Space.Page_0_string' value='string' name='Space.Page_0_string' type='text'/>{/pre}",
this.document.display("string", "edit", getContext()));
this.mockXWikiRenderingEngine.expects(once()).method("renderText").with(eq("area"), ANYTHING, ANYTHING).will(
returnValue("area"));
assertEquals("area", this.document.display("area", "view", getContext()));
}
public void testDisplay()
{
this.mockXWiki.stubs().method("getCurrentContentSyntaxId").will(returnValue("xwiki/2.0"));
this.document.setSyntax(Syntax.XWIKI_2_0);
assertEquals("string", this.document.display("string", "view", getContext()));
assertEquals(
"{{html clean=\"false\" wiki=\"false\"}}<input size='30' id='Space.Page_0_string' value='string' name='Space.Page_0_string' type='text'/>{{/html}}",
this.document.display("string", "edit", getContext()));
assertEquals("{{html clean=\"false\" wiki=\"false\"}}<p>area</p>{{/html}}", this.document.display("area",
"view", getContext()));
}
public void testDisplay1020()
{
this.mockXWiki.stubs().method("getCurrentContentSyntaxId").will(returnValue("xwiki/1.0"));
XWikiDocument doc10 = new XWikiDocument();
doc10.setSyntax(Syntax.XWIKI_1_0);
getContext().setDoc(doc10);
this.document.setSyntax(Syntax.XWIKI_2_0);
assertEquals("string", this.document.display("string", "view", getContext()));
assertEquals(
"{pre}<input size='30' id='Space.Page_0_string' value='string' name='Space.Page_0_string' type='text'/>{/pre}",
this.document.display("string", "edit", getContext()));
assertEquals("<p>area</p>", this.document.display("area", "view", getContext()));
}
public void testDisplay2010()
{
this.mockXWiki.stubs().method("getCurrentContentSyntaxId").will(returnValue("xwiki/2.0"));
XWikiDocument doc10 = new XWikiDocument();
doc10.setSyntax(Syntax.XWIKI_2_0);
getContext().setDoc(doc10);
assertEquals("string", this.document.display("string", "view", getContext()));
assertEquals(
"{{html clean=\"false\" wiki=\"false\"}}<input size='30' id='Space.Page_0_string' value='string' name='Space.Page_0_string' type='text'/>{{/html}}",
this.document.display("string", "edit", getContext()));
this.mockXWikiRenderingEngine.expects(once()).method("renderText").with(eq("area"), ANYTHING, ANYTHING).will(
returnValue("area"));
assertEquals("area", this.document.display("area", "view", getContext()));
}
public void testDisplayTemplate10()
{
this.mockXWiki.stubs().method("getCurrentContentSyntaxId").will(returnValue("xwiki/1.0"));
this.mockXWiki.stubs().method("getSkin").will(returnValue("colibri"));
this.mockXWiki.stubs().method("getSkinFile").will(returnValue(""));
getContext().put("isInRenderingEngine", false);
assertEquals("string", this.document.display("string", "view", getContext()));
assertEquals(
"<input size='30' id='Space.Page_0_string' value='string' name='Space.Page_0_string' type='text'/>",
this.document.display("string", "edit", getContext()));
this.mockXWikiRenderingEngine.expects(once()).method("renderText").with(eq("area"), ANYTHING, ANYTHING).will(
returnValue("area"));
assertEquals("area", this.document.display("area", "view", getContext()));
}
public void testDisplayTemplate20()
{
this.mockXWiki.stubs().method("getCurrentContentSyntaxId").will(returnValue("xwiki/2.0"));
this.mockXWiki.stubs().method("getSkin").will(returnValue("colibri"));
this.mockXWiki.stubs().method("getSkinFile").will(returnValue(""));
getContext().put("isInRenderingEngine", false);
this.document.setSyntax(Syntax.XWIKI_2_0);
assertEquals("string", this.document.display("string", "view", getContext()));
assertEquals(
"<input size='30' id='Space.Page_0_string' value='string' name='Space.Page_0_string' type='text'/>",
this.document.display("string", "edit", getContext()));
assertEquals("<p>area</p>", this.document.display("area", "view", getContext()));
}
public void testConvertSyntax() throws XWikiException
{
this.document.setContent("content not in section\n" + "1 header 1\nheader 1 content\n"
+ "1.1 header 2\nheader 2 content");
this.baseObject.setLargeStringValue("area", "object content not in section\n"
+ "1 object header 1\nobject header 1 content\n" + "1.1 object header 2\nobject header 2 content");
this.baseObject.setLargeStringValue("puretextarea", "object content not in section\n"
+ "1 object header 1\nobject header 1 content\n" + "1.1 object header 2\nobject header 2 content");
this.document.convertSyntax("xwiki/2.0", getContext());
assertEquals("content not in section\n\n" + "= header 1 =\n\nheader 1 content\n\n"
+ "== header 2 ==\n\nheader 2 content", this.document.getContent());
assertEquals("object content not in section\n\n" + "= object header 1 =\n\nobject header 1 content\n\n"
+ "== object header 2 ==\n\nobject header 2 content", this.baseObject.getStringValue("area"));
assertEquals("object content not in section\n" + "1 object header 1\nobject header 1 content\n"
+ "1.1 object header 2\nobject header 2 content", this.baseObject.getStringValue("puretextarea"));
assertEquals("xwiki/2.0", this.document.getSyntaxId());
}
public void testGetRenderedContent10() throws XWikiException
{
this.document.setContent("*bold*");
this.document.setSyntax(Syntax.XWIKI_1_0);
this.mockXWikiRenderingEngine.expects(once()).method("renderDocument").will(returnValue("<b>bold</b>"));
assertEquals("<b>bold</b>", this.document.getRenderedContent(getContext()));
this.translatedDocument = new XWikiDocument();
this.translatedDocument.setContent("~italic~");
this.translatedDocument.setSyntax(Syntax.XWIKI_2_0);
this.translatedDocument.setNew(false);
this.mockXWiki.stubs().method("getLanguagePreference").will(returnValue("fr"));
this.mockXWikiStoreInterface.stubs().method("loadXWikiDoc").will(returnValue(this.translatedDocument));
this.mockXWikiRenderingEngine.expects(once()).method("renderDocument").will(returnValue("<i>italic</i>"));
assertEquals("<i>italic</i>", this.document.getRenderedContent(getContext()));
}
public void testGetRenderedContent() throws XWikiException
{
this.document.setContent("**bold**");
this.document.setSyntax(Syntax.XWIKI_2_0);
assertEquals("<p><strong>bold</strong></p>", this.document.getRenderedContent(getContext()));
this.translatedDocument = new XWikiDocument();
this.translatedDocument.setContent("//italic//");
this.translatedDocument.setSyntax(Syntax.XWIKI_1_0);
this.translatedDocument.setNew(false);
this.mockXWiki.stubs().method("getLanguagePreference").will(returnValue("fr"));
this.mockXWikiStoreInterface.stubs().method("loadXWikiDoc").will(returnValue(this.translatedDocument));
assertEquals("<p><em>italic</em></p>", this.document.getRenderedContent(getContext()));
}
public void testGetRenderedContentWithSourceSyntax() throws XWikiException
{
this.document.setSyntax(Syntax.XWIKI_1_0);
assertEquals("<p><strong>bold</strong></p>", this.document.getRenderedContent("**bold**", "xwiki/2.0",
getContext()));
}
public void testRename() throws XWikiException
{
// Possible ways to write parents, include documents, or make links:
// "name" -----means-----> DOCWIKI+":"+DOCSPACE+"."+input
// "space.name" -means----> DOCWIKI+":"+input
// "database:space.name" (no change)
DocumentReference sourceReference = new DocumentReference(this.document.getDocumentReference());
this.document.setContent("[[pageinsamespace]]");
this.document.setSyntax(Syntax.XWIKI_2_0);
DocumentReference targetReference = new DocumentReference("newwikiname", "newspace", "newpage");
XWikiDocument targetDocument = this.document.duplicate(targetReference);
DocumentReference reference1 = new DocumentReference(DOCWIKI, DOCSPACE, "Page1");
XWikiDocument doc1 = new XWikiDocument(reference1);
doc1.setContent("[[" + DOCWIKI + ":" + DOCSPACE + "." + DOCNAME + "]] [[someName>>" + DOCSPACE + "." + DOCNAME
+ "]] [[" + DOCNAME + "]]");
doc1.setSyntax(Syntax.XWIKI_2_0);
DocumentReference reference2 = new DocumentReference("newwikiname", DOCSPACE, "Page2");
XWikiDocument doc2 = new XWikiDocument(reference2);
doc2.setContent("[[" + DOCWIKI + ":" + DOCSPACE + "." + DOCNAME + "]]");
doc2.setSyntax(Syntax.XWIKI_2_0);
DocumentReference reference3 = new DocumentReference("newwikiname", "newspace", "Page3");
XWikiDocument doc3 = new XWikiDocument(reference3);
doc3.setContent("[[" + DOCWIKI + ":" + DOCSPACE + "." + DOCNAME + "]]");
doc3.setSyntax(Syntax.XWIKI_2_0);
// Test to make sure it also drags children along.
DocumentReference reference4 = new DocumentReference(DOCWIKI, DOCSPACE, "Page4");
XWikiDocument doc4 = new XWikiDocument(reference4);
doc4.setParent(DOCSPACE + "." + DOCNAME);
DocumentReference reference5 = new DocumentReference("newwikiname", "newspace", "Page5");
XWikiDocument doc5 = new XWikiDocument(reference5);
doc5.setParent(DOCWIKI + ":" + DOCSPACE + "." + DOCNAME);
this.mockXWiki.stubs().method("copyDocument").will(returnValue(true));
this.mockXWiki.stubs().method("getDocument").with(eq(targetReference), ANYTHING).will(returnValue(targetDocument));
this.mockXWiki.stubs().method("getDocument").with(eq(reference1), ANYTHING).will(returnValue(doc1));
this.mockXWiki.stubs().method("getDocument").with(eq(reference2), ANYTHING).will(returnValue(doc2));
this.mockXWiki.stubs().method("getDocument").with(eq(reference3), ANYTHING).will(returnValue(doc3));
this.mockXWiki.stubs().method("getDocument").with(eq(reference4), ANYTHING).will(returnValue(doc4));
this.mockXWiki.stubs().method("getDocument").with(eq(reference5), ANYTHING).will(returnValue(doc5));
this.mockXWiki.stubs().method("saveDocument").isVoid();
this.mockXWiki.stubs().method("deleteDocument").isVoid();
this.document.rename(new DocumentReference("newwikiname", "newspace", "newpage"),
Arrays.asList(reference1, reference2, reference3), Arrays.asList(reference4, reference5), getContext());
// Test links
assertEquals("[[Wiki:Space.pageinsamespace]]", this.document.getContent());
assertEquals("[[newwikiname:newspace.newpage]] " + "[[someName>>newwikiname:newspace.newpage]] "
+ "[[newwikiname:newspace.newpage]]", doc1.getContent());
assertEquals("[[newspace.newpage]]", doc2.getContent());
assertEquals("[[newpage]]", doc3.getContent());
// Test parents
assertEquals("newwikiname:newspace.newpage", doc4.getParent());
assertEquals(new DocumentReference("newwikiname", "newspace", "newpage"), doc5.getParentReference());
}
/**
* Validate rename does not crash when the document has 1.0 syntax (it does not support everything but it does not crash).
*/
public void testRename10() throws XWikiException
{
DocumentReference sourceReference = new DocumentReference(this.document.getDocumentReference());
this.document.setContent("[pageinsamespace]");
this.document.setSyntax(Syntax.XWIKI_1_0);
DocumentReference targetReference = new DocumentReference("newwikiname", "newspace", "newpage");
XWikiDocument targetDocument = this.document.duplicate(targetReference);
this.mockXWiki.stubs().method("copyDocument").will(returnValue(true));
this.mockXWiki.stubs().method("getDocument").with(eq(targetReference), ANYTHING).will(returnValue(targetDocument));
this.mockXWiki.stubs().method("saveDocument").isVoid();
this.mockXWiki.stubs().method("deleteDocument").isVoid();
this.document.rename(new DocumentReference("newwikiname", "newspace", "newpage"), Collections.<DocumentReference>emptyList(),
Collections.<DocumentReference>emptyList(), getContext());
// Test links
assertEquals("[pageinsamespace]", this.document.getContent());
}
/**
* Normally the xobject vector has the Nth object on the Nth position, but in case an object gets misplaced, trying
* to remove it should indeed remove that object, and no other.
*/
public void testRemovingObjectWithWrongObjectVector()
{
// Setup: Create a document and two xobjects
BaseObject o1 = new BaseObject();
BaseObject o2 = new BaseObject();
o1.setClassName(CLASSNAME);
o2.setClassName(CLASSNAME);
// Test: put the second xobject on the third position
// addObject creates the object vector and configures the objects
// o1 is added at position 0
// o2 is added at position 1
XWikiDocument doc = new XWikiDocument();
doc.addObject(CLASSNAME, o1);
doc.addObject(CLASSNAME, o2);
// Modify the o2 object's position to ensure it can still be found and removed by the removeObject method.
assertEquals(1, o2.getNumber());
o2.setNumber(0);
// Set a field on o1 so that when comparing it with o2 they are different. This is needed so that the remove
// will pick the right object to remove (since we've voluntarily set a wrong number of o2 it would pick o1
// if they were equals).
o1.addField("somefield", new StringProperty());
// Call the tested method, removing o2 from position 2 which is set to null
boolean result = doc.removeObject(o2);
// Check the correct behavior:
assertTrue(result);
Vector<BaseObject> objects = doc.getObjects(CLASSNAME);
assertTrue(objects.contains(o1));
assertFalse(objects.contains(o2));
assertNull(objects.get(1));
// Second test: swap the two objects, so that the first object is in the position the second should have
// Start over, re-adding the two objects
doc = new XWikiDocument();
doc.addObject(CLASSNAME, o1);
doc.addObject(CLASSNAME, o2);
}
public void testCopyDocument() throws XWikiException
{
XWikiDocument doc = new XWikiDocument();
BaseObject o = new BaseObject();
o.setClassName(CLASSNAME);
doc.addObject(CLASSNAME, o);
XWikiDocument newDoc = doc.copyDocument("newdoc", getContext());
BaseObject newO = newDoc.getObject(CLASSNAME);
assertNotSame(o, newDoc.getObject(CLASSNAME));
assertFalse(newO.getGuid().equals(o.getGuid()));
}
public void testResolveClassReference() throws Exception
{
XWikiDocument doc = new XWikiDocument(new DocumentReference("docwiki", "docspace", "docpage"));
DocumentReference expected1 = new DocumentReference("docwiki", "XWiki", "docpage");
assertEquals(expected1, doc.resolveClassReference(""));
DocumentReference expected2 = new DocumentReference("docwiki", "XWiki", "page");
assertEquals(expected2, doc.resolveClassReference("page"));
DocumentReference expected3 = new DocumentReference("docwiki", "space", "page");
assertEquals(expected3, doc.resolveClassReference("space.page"));
DocumentReference expected4 = new DocumentReference("wiki", "space", "page");
assertEquals(expected4, doc.resolveClassReference("wiki:space.page"));
}
/**
* Test that the parent remain the same relative value whatever the context.
*/
public void testGetParent()
{
XWikiDocument doc = new XWikiDocument(new DocumentReference("docwiki", "docspace", "docpage"));
assertEquals("", doc.getParent());
doc.setParent(null);
assertEquals("", doc.getParent());
doc.setParent("page");
assertEquals("page", doc.getParent());
getContext().setDatabase("otherwiki");
assertEquals("page", doc.getParent());
doc.setDocumentReference(new DocumentReference("otherwiki", "otherspace", "otherpage"));
assertEquals("page", doc.getParent());
}
public void testGetParentReference()
{
XWikiDocument doc = new XWikiDocument(new DocumentReference("docwiki", "docspace", "docpage"));
assertNull(doc.getParentReference());
doc.setParent("parentpage");
//////////////////////////////////////////////////////////////////
// The following tests are checking that document reference cache is properly cleaned something could make the
// parent change
assertEquals(new DocumentReference("docwiki", "docspace", "parentpage"), doc.getParentReference());
doc.setName("docpage2");
assertEquals(new DocumentReference("docwiki", "docspace", "parentpage"), doc.getParentReference());
doc.setSpace("docspace2");
assertEquals(new DocumentReference("docwiki", "docspace2", "parentpage"), doc.getParentReference());
doc.setDatabase("docwiki2");
assertEquals(new DocumentReference("docwiki2", "docspace2", "parentpage"), doc.getParentReference());
doc.setDocumentReference(new DocumentReference("docwiki", "docspace", "docpage"));
assertEquals(new DocumentReference("docwiki", "docspace", "parentpage"), doc.getParentReference());
doc.setFullName("docwiki2:docspace2.docpage2", getContext());
assertEquals(new DocumentReference("docwiki2", "docspace2", "parentpage"), doc.getParentReference());
doc.setParent("parentpage2");
assertEquals(new DocumentReference("docwiki2", "docspace2", "parentpage2"), doc.getParentReference());
}
public void testSetAbsoluteParentReference()
{
XWikiDocument doc = new XWikiDocument(new DocumentReference("docwiki", "docspace", "docpage"));
doc.setParentReference(new DocumentReference("docwiki", "docspace", "docpage2"));
assertEquals("docspace.docpage2", doc.getParent());
}
public void testSetRelativeParentReference()
{
XWikiDocument doc = new XWikiDocument(new DocumentReference("docwiki", "docspace", "docpage"));
doc.setParentReference(new EntityReference("docpage2", EntityType.DOCUMENT));
assertEquals(new DocumentReference("docwiki", "docspace", "docpage2"), doc.getParentReference());
assertEquals("docpage2", doc.getParent());
}
/**
* Verify that cloning objects modify their references to point to the document in which they are cloned into.
*/
public void testCloneObjectsHaveCorrectReference()
{
XWikiDocument doc = new XWikiDocument(new DocumentReference("somewiki", "somespace", "somepage"));
doc.cloneXObjects(this.document);
assertTrue(doc.getXObjects().size() > 0);
// Verify that the object references point to the doc in which it's cloned.
for (Map.Entry<DocumentReference, List<BaseObject>> entry : doc.getXObjects().entrySet()) {
for (BaseObject baseObject : entry.getValue()) {
assertEquals(doc.getDocumentReference(), baseObject.getDocumentReference());
}
}
}
/**
* Verify that merging objects modify their references to point to the document in which they are cloned into and
* that GUID fors merged objects are different from the original GUIDs.
*/
public void testMergeObjectsHaveCorrectReferenceAndDifferentGuids()
{
List<String> originalGuids = new ArrayList<String>();
for (Map.Entry<DocumentReference, List<BaseObject>> entry : this.document.getXObjects().entrySet()) {
for (BaseObject baseObject : entry.getValue()) {
originalGuids.add(baseObject.getGuid());
}
}
XWikiDocument doc = new XWikiDocument(new DocumentReference("somewiki", "somespace", "somepage"));
doc.mergeXObjects(this.document);
assertTrue(doc.getXObjects().size() > 0);
// Verify that the object references point to the doc in which it's cloned.
// Verify that GUIDs are not the same as the original ones
for (Map.Entry<DocumentReference, List<BaseObject>> entry : doc.getXObjects().entrySet()) {
for (BaseObject baseObject : entry.getValue()) {
assertEquals(doc.getDocumentReference(), baseObject.getDocumentReference());
assertFalse("Non unique object GUID found!", originalGuids.contains(baseObject.getGuid()));
}
}
}
/** Check that a new empty document has empty content (used to have a new line before 2.5). */
public void testInitialContent()
{
XWikiDocument doc = new XWikiDocument(new DocumentReference("somewiki", "somespace", "somepage"));
assertEquals("", doc.getContent());
}
public void testGetXObjectWithObjectReference()
{
Assert.assertSame(this.baseObject, this.document.getXObject(this.baseObject.getReference()));
Assert.assertSame(this.baseObject, this.document.getXObject(new ObjectReference(CLASSNAME, this.document.getDocumentReference())));
}
}
| xwiki-platform-core/xwiki-platform-oldcore/src/test/java/com/xpn/xwiki/doc/XWikiDocumentTest.java | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.xpn.xwiki.doc;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.Vector;
import org.jmock.Mock;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.EntityReference;
import org.xwiki.rendering.syntax.Syntax;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiConfig;
import com.xpn.xwiki.XWikiConstant;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.api.DocumentSection;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.StringProperty;
import com.xpn.xwiki.objects.classes.BaseClass;
import com.xpn.xwiki.objects.classes.TextAreaClass;
import com.xpn.xwiki.render.XWikiRenderingEngine;
import com.xpn.xwiki.store.XWikiStoreInterface;
import com.xpn.xwiki.store.XWikiVersioningStoreInterface;
import com.xpn.xwiki.test.AbstractBridgedXWikiComponentTestCase;
import com.xpn.xwiki.user.api.XWikiRightService;
import com.xpn.xwiki.web.XWikiMessageTool;
/**
* Unit tests for {@link XWikiDocument}.
*
* @version $Id$
*/
public class XWikiDocumentTest extends AbstractBridgedXWikiComponentTestCase
{
private static final String DOCWIKI = "Wiki";
private static final String DOCSPACE = "Space";
private static final String DOCNAME = "Page";
private static final String DOCFULLNAME = DOCSPACE + "." + DOCNAME;
private static final String CLASSNAME = DOCFULLNAME;
private XWikiDocument document;
private XWikiDocument translatedDocument;
private Mock mockXWiki;
private Mock mockXWikiRenderingEngine;
private Mock mockXWikiVersioningStore;
private Mock mockXWikiStoreInterface;
private Mock mockXWikiMessageTool;
private Mock mockXWikiRightService;
private BaseClass baseClass;
private BaseObject baseObject;
@Override
protected void setUp() throws Exception
{
super.setUp();
this.document = new XWikiDocument(new DocumentReference(DOCWIKI, DOCSPACE, DOCNAME));
this.document.setSyntax(Syntax.XWIKI_1_0);
this.document.setLanguage("en");
this.document.setDefaultLanguage("en");
this.document.setNew(false);
this.translatedDocument = new XWikiDocument();
this.translatedDocument.setSyntax(Syntax.XWIKI_2_0);
this.translatedDocument.setLanguage("fr");
this.translatedDocument.setNew(false);
getContext().put("isInRenderingEngine", true);
this.mockXWiki = mock(XWiki.class);
this.mockXWiki.stubs().method("Param").will(returnValue(null));
this.mockXWikiRenderingEngine = mock(XWikiRenderingEngine.class);
this.mockXWikiVersioningStore = mock(XWikiVersioningStoreInterface.class);
this.mockXWikiVersioningStore.stubs().method("getXWikiDocumentArchive").will(returnValue(null));
this.mockXWikiStoreInterface = mock(XWikiStoreInterface.class);
this.document.setStore((XWikiStoreInterface) this.mockXWikiStoreInterface.proxy());
this.mockXWikiMessageTool =
mock(XWikiMessageTool.class, new Class[] {ResourceBundle.class, XWikiContext.class}, new Object[] {
null, getContext()});
this.mockXWikiMessageTool.stubs().method("get").will(returnValue("message"));
this.mockXWikiRightService = mock(XWikiRightService.class);
this.mockXWikiRightService.stubs().method("hasProgrammingRights").will(returnValue(true));
this.mockXWiki.stubs().method("getRenderingEngine").will(returnValue(this.mockXWikiRenderingEngine.proxy()));
this.mockXWiki.stubs().method("getVersioningStore").will(returnValue(this.mockXWikiVersioningStore.proxy()));
this.mockXWiki.stubs().method("getStore").will(returnValue(this.mockXWikiStoreInterface.proxy()));
this.mockXWiki.stubs().method("getDocument").will(returnValue(this.document));
this.mockXWiki.stubs().method("getLanguagePreference").will(returnValue("en"));
this.mockXWiki.stubs().method("getSectionEditingDepth").will(returnValue(2L));
this.mockXWiki.stubs().method("getRightService").will(returnValue(this.mockXWikiRightService.proxy()));
getContext().setWiki((XWiki) this.mockXWiki.proxy());
getContext().put("msg", this.mockXWikiMessageTool.proxy());
this.baseClass = this.document.getxWikiClass();
this.baseClass.addTextField("string", "String", 30);
this.baseClass.addTextAreaField("area", "Area", 10, 10);
this.baseClass.addTextAreaField("puretextarea", "Pure text area", 10, 10);
// set the text areas an non interpreted content
((TextAreaClass) this.baseClass.getField("puretextarea")).setContentType("puretext");
this.baseClass.addPasswordField("passwd", "Password", 30);
this.baseClass.addBooleanField("boolean", "Boolean", "yesno");
this.baseClass.addNumberField("int", "Int", 10, "integer");
this.baseClass.addStaticListField("stringlist", "StringList", "value1, value2");
this.mockXWiki.stubs().method("getClass").will(returnValue(this.baseClass));
this.mockXWiki.stubs().method("getXClass").will(returnValue(this.baseClass));
this.baseObject = this.document.newObject(CLASSNAME, getContext());
this.baseObject.setStringValue("string", "string");
this.baseObject.setLargeStringValue("area", "area");
this.baseObject.setStringValue("passwd", "passwd");
this.baseObject.setIntValue("boolean", 1);
this.baseObject.setIntValue("int", 42);
this.baseObject.setStringListValue("stringlist", Arrays.asList("VALUE1", "VALUE2"));
this.mockXWikiStoreInterface.stubs().method("search").will(returnValue(new ArrayList<XWikiDocument>()));
}
public void testDeprecatedConstructors()
{
DocumentReference defaultReference = new DocumentReference("xwiki", "Main", "WebHome");
XWikiDocument doc = new XWikiDocument(null);
assertEquals(defaultReference, doc.getDocumentReference());
doc = new XWikiDocument();
assertEquals(defaultReference, doc.getDocumentReference());
doc = new XWikiDocument("notused", "space.page");
assertEquals("space", doc.getSpaceName());
assertEquals("page", doc.getPageName());
assertEquals("xwiki", doc.getWikiName());
doc = new XWikiDocument("space", "page");
assertEquals("space", doc.getSpaceName());
assertEquals("page", doc.getPageName());
assertEquals("xwiki", doc.getWikiName());
doc = new XWikiDocument("wiki", "space", "page");
assertEquals("space", doc.getSpaceName());
assertEquals("page", doc.getPageName());
assertEquals("wiki", doc.getWikiName());
doc = new XWikiDocument("wiki", "notused", "notused:space.page");
assertEquals("space", doc.getSpaceName());
assertEquals("page", doc.getPageName());
assertEquals("wiki", doc.getWikiName());
}
public void testGetDisplayTitleWhenNoTitleAndNoContent()
{
this.document.setContent("Some content");
assertEquals("Page", this.document.getDisplayTitle(getContext()));
}
public void testGetDisplayWhenTitleExists()
{
this.document.setContent("Some content");
this.document.setTitle("Title");
this.mockXWikiRenderingEngine.expects(once()).method("interpretText").with(eq("Title"), ANYTHING, ANYTHING).will(
returnValue("Title"));
assertEquals("Title", this.document.getDisplayTitle(getContext()));
}
public void testGetDisplayWhenNoTitleButSectionExists()
{
this.document.setContent("Some content\n1 Title");
this.mockXWikiRenderingEngine.expects(once()).method("interpretText").with(eq("Title"), ANYTHING, ANYTHING).will(
returnValue("Title"));
assertEquals("Title", this.document.getDisplayTitle(getContext()));
}
public void testGetRenderedTitleWhenMatchingTitleHeaderDepth()
{
this.document.setContent("=== level3");
this.document.setSyntax(Syntax.XWIKI_2_0);
this.mockXWiki.stubs().method("ParamAsLong").will(returnValue(3L));
assertEquals("level3", this.document.getRenderedTitle(Syntax.XHTML_1_0, getContext()));
}
public void testGetRenderedTitleWhenNotMatchingTitleHeaderDepth()
{
this.document.setContent("=== level3");
this.document.setSyntax(Syntax.XWIKI_2_0);
this.mockXWiki.stubs().method("ParamAsLong").will(returnValue(2L));
assertEquals("Page", this.document.getRenderedTitle(Syntax.XHTML_1_0, getContext()));
}
/**
* Verify that if an error happens when evaluation the title, we fallback to the computed title.
*/
public void testGetDisplayTitleWhenVelocityError()
{
this.document.setContent("Some content");
this.document.setTitle("some content that generate a velocity error");
this.mockXWikiRenderingEngine.expects(once()).method("interpretText").will(
returnValue("... blah blah ... <div id=\"xwikierror105\" ... blah blah ..."));
assertEquals("Page", this.document.getDisplayTitle(getContext()));
}
public void testMinorMajorVersions()
{
// there is no version in doc yet, so 1.1
assertEquals("1.1", this.document.getVersion());
this.document.setMinorEdit(false);
this.document.incrementVersion();
// no version => incrementVersion sets 1.1
assertEquals("1.1", this.document.getVersion());
this.document.setMinorEdit(false);
this.document.incrementVersion();
// increment major version
assertEquals("2.1", this.document.getVersion());
this.document.setMinorEdit(true);
this.document.incrementVersion();
// increment minor version
assertEquals("2.2", this.document.getVersion());
}
public void testGetPreviousVersion() throws XWikiException
{
this.mockXWiki.stubs().method("getEncoding").will(returnValue("UTF-8"));
this.mockXWiki.stubs().method("getConfig").will(returnValue(new XWikiConfig()));
XWikiContext context = this.getContext();
Date now = new Date();
XWikiDocumentArchive archiveDoc = new XWikiDocumentArchive(this.document.getId());
this.document.setDocumentArchive(archiveDoc);
assertEquals("1.1", this.document.getVersion());
assertNull(this.document.getPreviousVersion());
this.document.incrementVersion();
archiveDoc.updateArchive(this.document, "Admin", now, "", this.document.getRCSVersion(), context);
assertEquals("1.1", this.document.getVersion());
assertNull(this.document.getPreviousVersion());
this.document.setMinorEdit(true);
this.document.incrementVersion();
archiveDoc.updateArchive(this.document, "Admin", now, "", this.document.getRCSVersion(), context);
assertEquals("1.2", this.document.getVersion());
assertEquals("1.1", this.document.getPreviousVersion());
this.document.setMinorEdit(false);
this.document.incrementVersion();
archiveDoc.updateArchive(this.document, "Admin", now, "", this.document.getRCSVersion(), context);
assertEquals("2.1", this.document.getVersion());
assertEquals("1.2", this.document.getPreviousVersion());
this.document.setMinorEdit(true);
this.document.incrementVersion();
archiveDoc.updateArchive(this.document, "Admin", now, "", this.document.getRCSVersion(), context);
assertEquals("2.2", this.document.getVersion());
assertEquals("2.1", this.document.getPreviousVersion());
archiveDoc.resetArchive();
assertEquals("2.2", this.document.getVersion());
assertNull(this.document.getPreviousVersion());
}
public void testAuthorAfterDocumentCopy() throws XWikiException
{
DocumentReference author = new DocumentReference("Wiki", "XWiki", "Albatross");
this.document.setAuthorReference(author);
XWikiDocument copy = this.document.copyDocument(this.document.getName() + " Copy", getContext());
assertEquals(author, copy.getAuthorReference());
}
public void testCreatorAfterDocumentCopy() throws XWikiException
{
DocumentReference creator = new DocumentReference("Wiki", "XWiki", "Condor");
this.document.setCreatorReference(creator);
XWikiDocument copy = this.document.copyDocument(this.document.getName() + " Copy", getContext());
assertEquals(creator, copy.getCreatorReference());
}
public void testCreationDateAfterDocumentCopy() throws Exception
{
Date sourceCreationDate = this.document.getCreationDate();
Thread.sleep(1000);
XWikiDocument copy = this.document.copyDocument(this.document.getName() + " Copy", getContext());
assertEquals(sourceCreationDate, copy.getCreationDate());
}
public void testObjectGuidsAfterDocumentCopy() throws Exception
{
assertTrue(this.document.getXObjects().size() > 0);
List<String> originalGuids = new ArrayList<String>();
for (Map.Entry<DocumentReference, List<BaseObject>> entry : this.document.getXObjects().entrySet()) {
for (BaseObject baseObject : entry.getValue()) {
originalGuids.add(baseObject.getGuid());
}
}
XWikiDocument copy = this.document.copyDocument(this.document.getName() + " Copy", getContext());
// Verify that the cloned objects have different GUIDs
for (Map.Entry<DocumentReference, List<BaseObject>> entry : copy.getXObjects().entrySet()) {
for (BaseObject baseObject : entry.getValue()) {
assertFalse("Non unique object GUID found!", originalGuids.contains(baseObject.getGuid()));
}
}
}
public void testRelativeObjectReferencesAfterDocumentCopy() throws Exception
{
XWikiDocument copy = this.document.copyDocument(new DocumentReference("copywiki", "copyspace", "copypage"),
getContext());
// Verify that the XObject's XClass reference points to the target wiki and not the old wiki.
// This tests the XObject cache.
DocumentReference targetXClassReference = new DocumentReference("copywiki", DOCSPACE, DOCNAME);
assertNotNull(copy.getXObject(targetXClassReference));
// Also verify that actual XObject's reference (not from the cache).
assertEquals(1, copy.getXObjects().size());
BaseObject bobject = copy.getXObjects().get(copy.getXObjects().keySet().iterator().next()).get(0);
assertEquals(new DocumentReference("copywiki", DOCSPACE, DOCNAME), bobject.getXClassReference());
}
public void testCloneNullObjects() throws XWikiException
{
XWikiDocument document = new XWikiDocument(new DocumentReference("wiki", DOCSPACE, DOCNAME));
EntityReference relativeClassReference =
new EntityReference(DOCNAME, EntityType.DOCUMENT, new EntityReference(DOCSPACE, EntityType.SPACE));
DocumentReference classReference = new DocumentReference("wiki", DOCSPACE, DOCNAME);
DocumentReference duplicatedClassReference = new DocumentReference("otherwiki", DOCSPACE, DOCNAME);
// no object
XWikiDocument clonedDocument = document.clone();
assertTrue(clonedDocument.getXObjects().isEmpty());
XWikiDocument duplicatedDocument = document.duplicate(new DocumentReference("otherwiki", DOCSPACE, DOCNAME));
assertTrue(duplicatedDocument.getXObjects().isEmpty());
// 1 null object
document.addXObject(classReference, null);
clonedDocument = document.clone();
assertEquals(1, clonedDocument.getXObjects(classReference).size());
assertEquals(document.getXObjects(classReference), clonedDocument.getXObjects(classReference));
duplicatedDocument = document.duplicate(new DocumentReference("otherwiki", DOCSPACE, DOCNAME));
assertTrue(duplicatedDocument.getXObjects().isEmpty());
// 1 null object and 1 object
BaseObject object = new BaseObject();
object.setXClassReference(relativeClassReference);
document.addXObject(object);
clonedDocument = document.clone();
assertEquals(2, clonedDocument.getXObjects(classReference).size());
assertEquals(document.getXObjects(classReference), clonedDocument.getXObjects(classReference));
duplicatedDocument = document.duplicate(new DocumentReference("otherwiki", DOCSPACE, DOCNAME));
assertEquals(2, duplicatedDocument.getXObjects(duplicatedClassReference).size());
}
public void testCloneWithAbsoluteClassReference()
{
XWikiDocument document = new XWikiDocument(new DocumentReference("wiki", DOCSPACE, DOCNAME));
EntityReference relativeClassReference =
new EntityReference(DOCNAME, EntityType.DOCUMENT, new EntityReference(DOCSPACE, EntityType.SPACE));
DocumentReference classReference = new DocumentReference("wiki", DOCSPACE, DOCNAME);
DocumentReference duplicatedClassReference = new DocumentReference("otherwiki", DOCSPACE, DOCNAME);
BaseObject object = new BaseObject();
object.setXClassReference(relativeClassReference);
document.addXObject(object);
BaseObject object2 = new BaseObject();
object2.setXClassReference(classReference);
document.addXObject(object2);
BaseObject object3 = new BaseObject();
object3.setXClassReference(relativeClassReference);
document.addXObject(object3);
XWikiDocument clonedDocument = document.clone();
assertEquals(3, clonedDocument.getXObjects(classReference).size());
assertEquals(document.getXObjects(classReference), clonedDocument.getXObjects(classReference));
XWikiDocument duplicatedDocument = document.duplicate(new DocumentReference("otherwiki", DOCSPACE, DOCNAME));
assertNotNull(duplicatedDocument.getXObject(duplicatedClassReference, 0));
assertNotNull(duplicatedDocument.getXObject(classReference, 1));
assertNotNull(duplicatedDocument.getXObject(duplicatedClassReference, 2));
}
public void testToStringReturnsFullName()
{
assertEquals("Space.Page", this.document.toString());
assertEquals("Main.WebHome", new XWikiDocument().toString());
}
public void testCloneSaveVersions()
{
XWikiDocument doc1 = new XWikiDocument(new DocumentReference("qwe", "qwe", "qwe"));
XWikiDocument doc2 = doc1.clone();
doc1.incrementVersion();
doc2.incrementVersion();
assertEquals(doc1.getVersion(), doc2.getVersion());
}
public void testAddObject() throws XWikiException
{
XWikiDocument doc = new XWikiDocument(new DocumentReference("test", "test", "document"));
this.mockXWiki.stubs().method("getClass").will(returnValue(new BaseClass()));
BaseObject object = BaseClass.newCustomClassInstance("XWiki.XWikiUsers", getContext());
doc.addObject("XWiki.XWikiUsers", object);
assertEquals("XWikiDocument.addObject does not set the object's name", doc.getFullName(), object.getName());
}
public void testObjectNumbersAfterXMLRoundrip() throws XWikiException
{
String classname = XWikiConstant.TAG_CLASS;
BaseClass tagClass = new BaseClass();
tagClass.setName(classname);
tagClass.addStaticListField(XWikiConstant.TAG_CLASS_PROP_TAGS, "Tags", 30, true, "", "checkbox");
XWikiDocument doc = new XWikiDocument(new DocumentReference("test", "test", "document"));
this.mockXWiki.stubs().method("getXClass").will(returnValue(tagClass));
this.mockXWiki.stubs().method("getEncoding").will(returnValue("iso-8859-1"));
BaseObject object = BaseClass.newCustomClassInstance(classname, getContext());
object.setClassName(classname);
doc.addObject(classname, object);
object = BaseClass.newCustomClassInstance(classname, getContext());
object.setClassName(classname);
doc.addObject(classname, object);
object = BaseClass.newCustomClassInstance(classname, getContext());
object.setClassName(classname);
doc.addObject(classname, object);
doc.setObject(classname, 1, null);
String docXML = doc.toXML(getContext());
XWikiDocument docFromXML = new XWikiDocument();
docFromXML.fromXML(docXML);
Vector<BaseObject> objects = doc.getObjects(classname);
Vector<BaseObject> objectsFromXML = docFromXML.getObjects(classname);
assertNotNull(objects);
assertNotNull(objectsFromXML);
assertTrue(objects.size() == objectsFromXML.size());
for (int i = 0; i < objects.size(); i++) {
if (objects.get(i) == null) {
assertNull(objectsFromXML.get(i));
} else {
assertTrue(objects.get(i).getNumber() == objectsFromXML.get(i).getNumber());
}
}
}
public void testGetUniqueLinkedPages10()
{
XWikiDocument contextDocument =
new XWikiDocument(new DocumentReference("contextdocwiki", "contextdocspace", "contextdocpage"));
getContext().setDoc(contextDocument);
this.mockXWiki.stubs().method("exists").will(returnValue(true));
this.document.setContent("[TargetPage][TargetLabel>TargetPage][TargetSpace.TargetPage]"
+ "[TargetLabel>TargetSpace.TargetPage?param=value#anchor][http://externallink][mailto:mailto][label>]");
Set<String> linkedPages = this.document.getUniqueLinkedPages(getContext());
assertEquals(new HashSet<String>(Arrays.asList("TargetPage", "TargetSpace.TargetPage")), new HashSet<String>(
linkedPages));
}
public void testGetUniqueLinkedPages()
{
XWikiDocument contextDocument =
new XWikiDocument(new DocumentReference("contextdocwiki", "contextdocspace", "contextdocpage"));
getContext().setDoc(contextDocument);
this.document.setContent("[[TargetPage]][[TargetLabel>>TargetPage]][[TargetSpace.TargetPage]]"
+ "[[TargetLabel>>TargetSpace.TargetPage?param=value#anchor]][[http://externallink]][[mailto:mailto]]"
+ "[[]][[#anchor]][[?param=value]][[targetwiki:TargetSpace.TargetPage]]");
this.document.setSyntax(Syntax.XWIKI_2_0);
Set<String> linkedPages = this.document.getUniqueLinkedPages(getContext());
assertEquals(new LinkedHashSet<String>(Arrays.asList("Space.TargetPage", "TargetSpace.TargetPage",
"targetwiki:TargetSpace.TargetPage")), linkedPages);
}
public void testGetSections10() throws XWikiException
{
this.document.setContent("content not in section\n" + "1 header 1\nheader 1 content\n"
+ "1.1 header 2\nheader 2 content");
List<DocumentSection> headers = this.document.getSections();
assertEquals(2, headers.size());
DocumentSection header1 = headers.get(0);
DocumentSection header2 = headers.get(1);
assertEquals("header 1", header1.getSectionTitle());
assertEquals(23, header1.getSectionIndex());
assertEquals(1, header1.getSectionNumber());
assertEquals("1", header1.getSectionLevel());
assertEquals("header 2", header2.getSectionTitle());
assertEquals(51, header2.getSectionIndex());
assertEquals(2, header2.getSectionNumber());
assertEquals("1.1", header2.getSectionLevel());
}
public void testGetSections() throws XWikiException
{
this.document.setContent("content not in section\n" + "= header 1=\nheader 1 content\n"
+ "== header 2==\nheader 2 content");
this.document.setSyntax(Syntax.XWIKI_2_0);
List<DocumentSection> headers = this.document.getSections();
assertEquals(2, headers.size());
DocumentSection header1 = headers.get(0);
DocumentSection header2 = headers.get(1);
assertEquals("header 1", header1.getSectionTitle());
assertEquals(-1, header1.getSectionIndex());
assertEquals(1, header1.getSectionNumber());
assertEquals("1", header1.getSectionLevel());
assertEquals("header 2", header2.getSectionTitle());
assertEquals(-1, header2.getSectionIndex());
assertEquals(2, header2.getSectionNumber());
assertEquals("1.1", header2.getSectionLevel());
}
public void testGetDocumentSection10() throws XWikiException
{
this.document.setContent("content not in section\n" + "1 header 1\nheader 1 content\n"
+ "1.1 header 2\nheader 2 content");
DocumentSection header1 = this.document.getDocumentSection(1);
DocumentSection header2 = this.document.getDocumentSection(2);
assertEquals("header 1", header1.getSectionTitle());
assertEquals(23, header1.getSectionIndex());
assertEquals(1, header1.getSectionNumber());
assertEquals("1", header1.getSectionLevel());
assertEquals("header 2", header2.getSectionTitle());
assertEquals(51, header2.getSectionIndex());
assertEquals(2, header2.getSectionNumber());
assertEquals("1.1", header2.getSectionLevel());
}
public void testGetDocumentSection() throws XWikiException
{
this.document.setContent("content not in section\n" + "= header 1=\nheader 1 content\n"
+ "== header 2==\nheader 2 content");
this.document.setSyntax(Syntax.XWIKI_2_0);
DocumentSection header1 = this.document.getDocumentSection(1);
DocumentSection header2 = this.document.getDocumentSection(2);
assertEquals("header 1", header1.getSectionTitle());
assertEquals(-1, header1.getSectionIndex());
assertEquals(1, header1.getSectionNumber());
assertEquals("1", header1.getSectionLevel());
assertEquals("header 2", header2.getSectionTitle());
assertEquals(-1, header2.getSectionIndex());
assertEquals(2, header2.getSectionNumber());
assertEquals("1.1", header2.getSectionLevel());
}
public void testGetContentOfSection10() throws XWikiException
{
this.document.setContent("content not in section\n" + "1 header 1\nheader 1 content\n"
+ "1.1 header 2\nheader 2 content");
String content1 = this.document.getContentOfSection(1);
String content2 = this.document.getContentOfSection(2);
assertEquals("1 header 1\nheader 1 content\n1.1 header 2\nheader 2 content", content1);
assertEquals("1.1 header 2\nheader 2 content", content2);
}
public void testGetContentOfSection() throws XWikiException
{
this.document.setContent("content not in section\n" + "= header 1=\nheader 1 content\n"
+ "== header 2==\nheader 2 content\n" + "=== header 3===\nheader 3 content\n"
+ "== header 4==\nheader 4 content");
this.document.setSyntax(Syntax.XWIKI_2_0);
String content1 = this.document.getContentOfSection(1);
String content2 = this.document.getContentOfSection(2);
String content3 = this.document.getContentOfSection(3);
assertEquals("= header 1 =\n\nheader 1 content\n\n== header 2 ==\n\nheader 2 content\n\n"
+ "=== header 3 ===\n\nheader 3 content\n\n== header 4 ==\n\nheader 4 content", content1);
assertEquals("== header 2 ==\n\nheader 2 content\n\n=== header 3 ===\n\nheader 3 content", content2);
assertEquals("== header 4 ==\n\nheader 4 content", content3);
// Validate that third level header is not skipped anymore
this.mockXWiki.stubs().method("getSectionEditingDepth").will(returnValue(3L));
content3 = this.document.getContentOfSection(3);
String content4 = this.document.getContentOfSection(4);
assertEquals("=== header 3 ===\n\nheader 3 content", content3);
assertEquals("== header 4 ==\n\nheader 4 content", content4);
}
public void testSectionSplit10() throws XWikiException
{
List<DocumentSection> sections;
// Simple test
this.document.setContent("1 Section 1\n" + "Content of first section\n" + "1.1 Subsection 2\n"
+ "Content of second section\n" + "1 Section 3\n" + "Content of section 3");
sections = this.document.getSections();
assertEquals(3, sections.size());
assertEquals("Section 1", sections.get(0).getSectionTitle());
assertEquals("1 Section 1\n" + "Content of first section\n" + "1.1 Subsection 2\n"
+ "Content of second section\n", this.document.getContentOfSection(1));
assertEquals("1.1", sections.get(1).getSectionLevel());
assertEquals("1.1 Subsection 2\nContent of second section\n", this.document.getContentOfSection(2));
assertEquals(3, sections.get(2).getSectionNumber());
assertEquals(80, sections.get(2).getSectionIndex());
assertEquals("1 Section 3\nContent of section 3", this.document.getContentOfSection(3));
// Test comments don't break the section editing
this.document.setContent("1 Section 1\n" + "Content of first section\n" + "## 1.1 Subsection 2\n"
+ "Content of second section\n" + "1 Section 3\n" + "Content of section 3");
sections = this.document.getSections();
assertEquals(2, sections.size());
assertEquals("Section 1", sections.get(0).getSectionTitle());
assertEquals("1", sections.get(1).getSectionLevel());
assertEquals(2, sections.get(1).getSectionNumber());
assertEquals(83, sections.get(1).getSectionIndex());
// Test spaces are ignored
this.document.setContent("1 Section 1\n" + "Content of first section\n" + " 1.1 Subsection 2 \n"
+ "Content of second section\n" + "1 Section 3\n" + "Content of section 3");
sections = this.document.getSections();
assertEquals(3, sections.size());
assertEquals("Subsection 2 ", sections.get(1).getSectionTitle());
assertEquals("1.1", sections.get(1).getSectionLevel());
// Test lower headings are ignored
this.document.setContent("1 Section 1\n" + "Content of first section\n" + "1.1.1 Lower subsection\n"
+ "This content is not important\n" + " 1.1 Subsection 2 \n" + "Content of second section\n"
+ "1 Section 3\n" + "Content of section 3");
sections = this.document.getSections();
assertEquals(3, sections.size());
assertEquals("Section 1", sections.get(0).getSectionTitle());
assertEquals("Subsection 2 ", sections.get(1).getSectionTitle());
assertEquals("1.1", sections.get(1).getSectionLevel());
// Test blank lines are preserved
this.document.setContent("\n\n1 Section 1\n\n\n" + "Content of first section\n\n\n"
+ " 1.1 Subsection 2 \n\n" + "Content of second section\n" + "1 Section 3\n" + "Content of section 3");
sections = this.document.getSections();
assertEquals(3, sections.size());
assertEquals(2, sections.get(0).getSectionIndex());
assertEquals("Subsection 2 ", sections.get(1).getSectionTitle());
assertEquals(43, sections.get(1).getSectionIndex());
}
public void testUpdateDocumentSection10() throws XWikiException
{
List<DocumentSection> sections;
// Fill the document
this.document.setContent("1 Section 1\n" + "Content of first section\n" + "1.1 Subsection 2\n"
+ "Content of second section\n" + "1 Section 3\n" + "Content of section 3");
String content = this.document.updateDocumentSection(3, "1 Section 3\n" + "Modified content of section 3");
assertEquals("1 Section 1\n" + "Content of first section\n" + "1.1 Subsection 2\n"
+ "Content of second section\n" + "1 Section 3\n" + "Modified content of section 3", content);
this.document.setContent(content);
sections = this.document.getSections();
assertEquals(3, sections.size());
assertEquals("Section 1", sections.get(0).getSectionTitle());
assertEquals("1 Section 1\n" + "Content of first section\n" + "1.1 Subsection 2\n"
+ "Content of second section\n", this.document.getContentOfSection(1));
assertEquals("1.1", sections.get(1).getSectionLevel());
assertEquals("1.1 Subsection 2\nContent of second section\n", this.document.getContentOfSection(2));
assertEquals(3, sections.get(2).getSectionNumber());
assertEquals(80, sections.get(2).getSectionIndex());
assertEquals("1 Section 3\nModified content of section 3", this.document.getContentOfSection(3));
}
public void testUpdateDocumentSection() throws XWikiException
{
this.document.setContent("content not in section\n" + "= header 1=\nheader 1 content\n"
+ "== header 2==\nheader 2 content");
this.document.setSyntax(Syntax.XWIKI_2_0);
// Modify section content
String content1 = this.document.updateDocumentSection(2, "== header 2==\nmodified header 2 content");
assertEquals(
"content not in section\n\n= header 1 =\n\nheader 1 content\n\n== header 2 ==\n\nmodified header 2 content",
content1);
String content2 =
this.document.updateDocumentSection(1,
"= header 1 =\n\nmodified also header 1 content\n\n== header 2 ==\n\nheader 2 content");
assertEquals(
"content not in section\n\n= header 1 =\n\nmodified also header 1 content\n\n== header 2 ==\n\nheader 2 content",
content2);
// Remove a section
String content3 = this.document.updateDocumentSection(2, "");
assertEquals("content not in section\n\n= header 1 =\n\nheader 1 content", content3);
}
public void testDisplay10()
{
this.mockXWiki.stubs().method("getCurrentContentSyntaxId").will(returnValue("xwiki/1.0"));
assertEquals("string", this.document.display("string", "view", getContext()));
assertEquals(
"{pre}<input size='30' id='Space.Page_0_string' value='string' name='Space.Page_0_string' type='text'/>{/pre}",
this.document.display("string", "edit", getContext()));
this.mockXWikiRenderingEngine.expects(once()).method("renderText").with(eq("area"), ANYTHING, ANYTHING).will(
returnValue("area"));
assertEquals("area", this.document.display("area", "view", getContext()));
}
public void testDisplay()
{
this.mockXWiki.stubs().method("getCurrentContentSyntaxId").will(returnValue("xwiki/2.0"));
this.document.setSyntax(Syntax.XWIKI_2_0);
assertEquals("string", this.document.display("string", "view", getContext()));
assertEquals(
"{{html clean=\"false\" wiki=\"false\"}}<input size='30' id='Space.Page_0_string' value='string' name='Space.Page_0_string' type='text'/>{{/html}}",
this.document.display("string", "edit", getContext()));
assertEquals("{{html clean=\"false\" wiki=\"false\"}}<p>area</p>{{/html}}", this.document.display("area",
"view", getContext()));
}
public void testDisplay1020()
{
this.mockXWiki.stubs().method("getCurrentContentSyntaxId").will(returnValue("xwiki/1.0"));
XWikiDocument doc10 = new XWikiDocument();
doc10.setSyntax(Syntax.XWIKI_1_0);
getContext().setDoc(doc10);
this.document.setSyntax(Syntax.XWIKI_2_0);
assertEquals("string", this.document.display("string", "view", getContext()));
assertEquals(
"{pre}<input size='30' id='Space.Page_0_string' value='string' name='Space.Page_0_string' type='text'/>{/pre}",
this.document.display("string", "edit", getContext()));
assertEquals("<p>area</p>", this.document.display("area", "view", getContext()));
}
public void testDisplay2010()
{
this.mockXWiki.stubs().method("getCurrentContentSyntaxId").will(returnValue("xwiki/2.0"));
XWikiDocument doc10 = new XWikiDocument();
doc10.setSyntax(Syntax.XWIKI_2_0);
getContext().setDoc(doc10);
assertEquals("string", this.document.display("string", "view", getContext()));
assertEquals(
"{{html clean=\"false\" wiki=\"false\"}}<input size='30' id='Space.Page_0_string' value='string' name='Space.Page_0_string' type='text'/>{{/html}}",
this.document.display("string", "edit", getContext()));
this.mockXWikiRenderingEngine.expects(once()).method("renderText").with(eq("area"), ANYTHING, ANYTHING).will(
returnValue("area"));
assertEquals("area", this.document.display("area", "view", getContext()));
}
public void testDisplayTemplate10()
{
this.mockXWiki.stubs().method("getCurrentContentSyntaxId").will(returnValue("xwiki/1.0"));
this.mockXWiki.stubs().method("getSkin").will(returnValue("colibri"));
this.mockXWiki.stubs().method("getSkinFile").will(returnValue(""));
getContext().put("isInRenderingEngine", false);
assertEquals("string", this.document.display("string", "view", getContext()));
assertEquals(
"<input size='30' id='Space.Page_0_string' value='string' name='Space.Page_0_string' type='text'/>",
this.document.display("string", "edit", getContext()));
this.mockXWikiRenderingEngine.expects(once()).method("renderText").with(eq("area"), ANYTHING, ANYTHING).will(
returnValue("area"));
assertEquals("area", this.document.display("area", "view", getContext()));
}
public void testDisplayTemplate20()
{
this.mockXWiki.stubs().method("getCurrentContentSyntaxId").will(returnValue("xwiki/2.0"));
this.mockXWiki.stubs().method("getSkin").will(returnValue("colibri"));
this.mockXWiki.stubs().method("getSkinFile").will(returnValue(""));
getContext().put("isInRenderingEngine", false);
this.document.setSyntax(Syntax.XWIKI_2_0);
assertEquals("string", this.document.display("string", "view", getContext()));
assertEquals(
"<input size='30' id='Space.Page_0_string' value='string' name='Space.Page_0_string' type='text'/>",
this.document.display("string", "edit", getContext()));
assertEquals("<p>area</p>", this.document.display("area", "view", getContext()));
}
public void testConvertSyntax() throws XWikiException
{
this.document.setContent("content not in section\n" + "1 header 1\nheader 1 content\n"
+ "1.1 header 2\nheader 2 content");
this.baseObject.setLargeStringValue("area", "object content not in section\n"
+ "1 object header 1\nobject header 1 content\n" + "1.1 object header 2\nobject header 2 content");
this.baseObject.setLargeStringValue("puretextarea", "object content not in section\n"
+ "1 object header 1\nobject header 1 content\n" + "1.1 object header 2\nobject header 2 content");
this.document.convertSyntax("xwiki/2.0", getContext());
assertEquals("content not in section\n\n" + "= header 1 =\n\nheader 1 content\n\n"
+ "== header 2 ==\n\nheader 2 content", this.document.getContent());
assertEquals("object content not in section\n\n" + "= object header 1 =\n\nobject header 1 content\n\n"
+ "== object header 2 ==\n\nobject header 2 content", this.baseObject.getStringValue("area"));
assertEquals("object content not in section\n" + "1 object header 1\nobject header 1 content\n"
+ "1.1 object header 2\nobject header 2 content", this.baseObject.getStringValue("puretextarea"));
assertEquals("xwiki/2.0", this.document.getSyntaxId());
}
public void testGetRenderedContent10() throws XWikiException
{
this.document.setContent("*bold*");
this.document.setSyntax(Syntax.XWIKI_1_0);
this.mockXWikiRenderingEngine.expects(once()).method("renderDocument").will(returnValue("<b>bold</b>"));
assertEquals("<b>bold</b>", this.document.getRenderedContent(getContext()));
this.translatedDocument = new XWikiDocument();
this.translatedDocument.setContent("~italic~");
this.translatedDocument.setSyntax(Syntax.XWIKI_2_0);
this.translatedDocument.setNew(false);
this.mockXWiki.stubs().method("getLanguagePreference").will(returnValue("fr"));
this.mockXWikiStoreInterface.stubs().method("loadXWikiDoc").will(returnValue(this.translatedDocument));
this.mockXWikiRenderingEngine.expects(once()).method("renderDocument").will(returnValue("<i>italic</i>"));
assertEquals("<i>italic</i>", this.document.getRenderedContent(getContext()));
}
public void testGetRenderedContent() throws XWikiException
{
this.document.setContent("**bold**");
this.document.setSyntax(Syntax.XWIKI_2_0);
assertEquals("<p><strong>bold</strong></p>", this.document.getRenderedContent(getContext()));
this.translatedDocument = new XWikiDocument();
this.translatedDocument.setContent("//italic//");
this.translatedDocument.setSyntax(Syntax.XWIKI_1_0);
this.translatedDocument.setNew(false);
this.mockXWiki.stubs().method("getLanguagePreference").will(returnValue("fr"));
this.mockXWikiStoreInterface.stubs().method("loadXWikiDoc").will(returnValue(this.translatedDocument));
assertEquals("<p><em>italic</em></p>", this.document.getRenderedContent(getContext()));
}
public void testGetRenderedContentWithSourceSyntax() throws XWikiException
{
this.document.setSyntax(Syntax.XWIKI_1_0);
assertEquals("<p><strong>bold</strong></p>", this.document.getRenderedContent("**bold**", "xwiki/2.0",
getContext()));
}
public void testRename() throws XWikiException
{
// Possible ways to write parents, include documents, or make links:
// "name" -----means-----> DOCWIKI+":"+DOCSPACE+"."+input
// "space.name" -means----> DOCWIKI+":"+input
// "database:space.name" (no change)
DocumentReference sourceReference = new DocumentReference(this.document.getDocumentReference());
this.document.setContent("[[pageinsamespace]]");
this.document.setSyntax(Syntax.XWIKI_2_0);
DocumentReference targetReference = new DocumentReference("newwikiname", "newspace", "newpage");
XWikiDocument targetDocument = this.document.duplicate(targetReference);
DocumentReference reference1 = new DocumentReference(DOCWIKI, DOCSPACE, "Page1");
XWikiDocument doc1 = new XWikiDocument(reference1);
doc1.setContent("[[" + DOCWIKI + ":" + DOCSPACE + "." + DOCNAME + "]] [[someName>>" + DOCSPACE + "." + DOCNAME
+ "]] [[" + DOCNAME + "]]");
doc1.setSyntax(Syntax.XWIKI_2_0);
DocumentReference reference2 = new DocumentReference("newwikiname", DOCSPACE, "Page2");
XWikiDocument doc2 = new XWikiDocument(reference2);
doc2.setContent("[[" + DOCWIKI + ":" + DOCSPACE + "." + DOCNAME + "]]");
doc2.setSyntax(Syntax.XWIKI_2_0);
DocumentReference reference3 = new DocumentReference("newwikiname", "newspace", "Page3");
XWikiDocument doc3 = new XWikiDocument(reference3);
doc3.setContent("[[" + DOCWIKI + ":" + DOCSPACE + "." + DOCNAME + "]]");
doc3.setSyntax(Syntax.XWIKI_2_0);
// Test to make sure it also drags children along.
DocumentReference reference4 = new DocumentReference(DOCWIKI, DOCSPACE, "Page4");
XWikiDocument doc4 = new XWikiDocument(reference4);
doc4.setParent(DOCSPACE + "." + DOCNAME);
DocumentReference reference5 = new DocumentReference("newwikiname", "newspace", "Page5");
XWikiDocument doc5 = new XWikiDocument(reference5);
doc5.setParent(DOCWIKI + ":" + DOCSPACE + "." + DOCNAME);
this.mockXWiki.stubs().method("copyDocument").will(returnValue(true));
this.mockXWiki.stubs().method("getDocument").with(eq(targetReference), ANYTHING).will(returnValue(targetDocument));
this.mockXWiki.stubs().method("getDocument").with(eq(reference1), ANYTHING).will(returnValue(doc1));
this.mockXWiki.stubs().method("getDocument").with(eq(reference2), ANYTHING).will(returnValue(doc2));
this.mockXWiki.stubs().method("getDocument").with(eq(reference3), ANYTHING).will(returnValue(doc3));
this.mockXWiki.stubs().method("getDocument").with(eq(reference4), ANYTHING).will(returnValue(doc4));
this.mockXWiki.stubs().method("getDocument").with(eq(reference5), ANYTHING).will(returnValue(doc5));
this.mockXWiki.stubs().method("saveDocument").isVoid();
this.mockXWiki.stubs().method("deleteDocument").isVoid();
this.document.rename(new DocumentReference("newwikiname", "newspace", "newpage"),
Arrays.asList(reference1, reference2, reference3), Arrays.asList(reference4, reference5), getContext());
// Test links
assertEquals("[[Wiki:Space.pageinsamespace]]", this.document.getContent());
assertEquals("[[newwikiname:newspace.newpage]] " + "[[someName>>newwikiname:newspace.newpage]] "
+ "[[newwikiname:newspace.newpage]]", doc1.getContent());
assertEquals("[[newspace.newpage]]", doc2.getContent());
assertEquals("[[newpage]]", doc3.getContent());
// Test parents
assertEquals("newwikiname:newspace.newpage", doc4.getParent());
assertEquals(new DocumentReference("newwikiname", "newspace", "newpage"), doc5.getParentReference());
}
/**
* Validate rename does not crash when the document has 1.0 syntax (it does not support everything but it does not crash).
*/
public void testRename10() throws XWikiException
{
DocumentReference sourceReference = new DocumentReference(this.document.getDocumentReference());
this.document.setContent("[pageinsamespace]");
this.document.setSyntax(Syntax.XWIKI_1_0);
DocumentReference targetReference = new DocumentReference("newwikiname", "newspace", "newpage");
XWikiDocument targetDocument = this.document.duplicate(targetReference);
this.mockXWiki.stubs().method("copyDocument").will(returnValue(true));
this.mockXWiki.stubs().method("getDocument").with(eq(targetReference), ANYTHING).will(returnValue(targetDocument));
this.mockXWiki.stubs().method("saveDocument").isVoid();
this.mockXWiki.stubs().method("deleteDocument").isVoid();
this.document.rename(new DocumentReference("newwikiname", "newspace", "newpage"), Collections.<DocumentReference>emptyList(),
Collections.<DocumentReference>emptyList(), getContext());
// Test links
assertEquals("[pageinsamespace]", this.document.getContent());
}
/**
* Normally the xobject vector has the Nth object on the Nth position, but in case an object gets misplaced, trying
* to remove it should indeed remove that object, and no other.
*/
public void testRemovingObjectWithWrongObjectVector()
{
// Setup: Create a document and two xobjects
BaseObject o1 = new BaseObject();
BaseObject o2 = new BaseObject();
o1.setClassName(CLASSNAME);
o2.setClassName(CLASSNAME);
// Test: put the second xobject on the third position
// addObject creates the object vector and configures the objects
// o1 is added at position 0
// o2 is added at position 1
XWikiDocument doc = new XWikiDocument();
doc.addObject(CLASSNAME, o1);
doc.addObject(CLASSNAME, o2);
// Modify the o2 object's position to ensure it can still be found and removed by the removeObject method.
assertEquals(1, o2.getNumber());
o2.setNumber(0);
// Set a field on o1 so that when comparing it with o2 they are different. This is needed so that the remove
// will pick the right object to remove (since we've voluntarily set a wrong number of o2 it would pick o1
// if they were equals).
o1.addField("somefield", new StringProperty());
// Call the tested method, removing o2 from position 2 which is set to null
boolean result = doc.removeObject(o2);
// Check the correct behavior:
assertTrue(result);
Vector<BaseObject> objects = doc.getObjects(CLASSNAME);
assertTrue(objects.contains(o1));
assertFalse(objects.contains(o2));
assertNull(objects.get(1));
// Second test: swap the two objects, so that the first object is in the position the second should have
// Start over, re-adding the two objects
doc = new XWikiDocument();
doc.addObject(CLASSNAME, o1);
doc.addObject(CLASSNAME, o2);
}
public void testCopyDocument() throws XWikiException
{
XWikiDocument doc = new XWikiDocument();
BaseObject o = new BaseObject();
o.setClassName(CLASSNAME);
doc.addObject(CLASSNAME, o);
XWikiDocument newDoc = doc.copyDocument("newdoc", getContext());
BaseObject newO = newDoc.getObject(CLASSNAME);
assertNotSame(o, newDoc.getObject(CLASSNAME));
assertFalse(newO.getGuid().equals(o.getGuid()));
}
public void testResolveClassReference() throws Exception
{
XWikiDocument doc = new XWikiDocument(new DocumentReference("docwiki", "docspace", "docpage"));
DocumentReference expected1 = new DocumentReference("docwiki", "XWiki", "docpage");
assertEquals(expected1, doc.resolveClassReference(""));
DocumentReference expected2 = new DocumentReference("docwiki", "XWiki", "page");
assertEquals(expected2, doc.resolveClassReference("page"));
DocumentReference expected3 = new DocumentReference("docwiki", "space", "page");
assertEquals(expected3, doc.resolveClassReference("space.page"));
DocumentReference expected4 = new DocumentReference("wiki", "space", "page");
assertEquals(expected4, doc.resolveClassReference("wiki:space.page"));
}
/**
* Test that the parent remain the same relative value whatever the context.
*/
public void testGetParent()
{
XWikiDocument doc = new XWikiDocument(new DocumentReference("docwiki", "docspace", "docpage"));
assertEquals("", doc.getParent());
doc.setParent(null);
assertEquals("", doc.getParent());
doc.setParent("page");
assertEquals("page", doc.getParent());
getContext().setDatabase("otherwiki");
assertEquals("page", doc.getParent());
doc.setDocumentReference(new DocumentReference("otherwiki", "otherspace", "otherpage"));
assertEquals("page", doc.getParent());
}
public void testGetParentReference()
{
XWikiDocument doc = new XWikiDocument(new DocumentReference("docwiki", "docspace", "docpage"));
assertNull(doc.getParentReference());
doc.setParent("parentpage");
//////////////////////////////////////////////////////////////////
// The following tests are checking that document reference cache is properly cleaned something could make the
// parent change
assertEquals(new DocumentReference("docwiki", "docspace", "parentpage"), doc.getParentReference());
doc.setName("docpage2");
assertEquals(new DocumentReference("docwiki", "docspace", "parentpage"), doc.getParentReference());
doc.setSpace("docspace2");
assertEquals(new DocumentReference("docwiki", "docspace2", "parentpage"), doc.getParentReference());
doc.setDatabase("docwiki2");
assertEquals(new DocumentReference("docwiki2", "docspace2", "parentpage"), doc.getParentReference());
doc.setDocumentReference(new DocumentReference("docwiki", "docspace", "docpage"));
assertEquals(new DocumentReference("docwiki", "docspace", "parentpage"), doc.getParentReference());
doc.setFullName("docwiki2:docspace2.docpage2", getContext());
assertEquals(new DocumentReference("docwiki2", "docspace2", "parentpage"), doc.getParentReference());
doc.setParent("parentpage2");
assertEquals(new DocumentReference("docwiki2", "docspace2", "parentpage2"), doc.getParentReference());
}
public void testSetAbsoluteParentReference()
{
XWikiDocument doc = new XWikiDocument(new DocumentReference("docwiki", "docspace", "docpage"));
doc.setParentReference(new DocumentReference("docwiki", "docspace", "docpage2"));
assertEquals("docspace.docpage2", doc.getParent());
}
public void testSetRelativeParentReference()
{
XWikiDocument doc = new XWikiDocument(new DocumentReference("docwiki", "docspace", "docpage"));
doc.setParentReference(new EntityReference("docpage2", EntityType.DOCUMENT));
assertEquals(new DocumentReference("docwiki", "docspace", "docpage2"), doc.getParentReference());
assertEquals("docpage2", doc.getParent());
}
/**
* Verify that cloning objects modify their references to point to the document in which they are cloned into.
*/
public void testCloneObjectsHaveCorrectReference()
{
XWikiDocument doc = new XWikiDocument(new DocumentReference("somewiki", "somespace", "somepage"));
doc.cloneXObjects(this.document);
assertTrue(doc.getXObjects().size() > 0);
// Verify that the object references point to the doc in which it's cloned.
for (Map.Entry<DocumentReference, List<BaseObject>> entry : doc.getXObjects().entrySet()) {
for (BaseObject baseObject : entry.getValue()) {
assertEquals(doc.getDocumentReference(), baseObject.getDocumentReference());
}
}
}
/**
* Verify that merging objects modify their references to point to the document in which they are cloned into and
* that GUID fors merged objects are different from the original GUIDs.
*/
public void testMergeObjectsHaveCorrectReferenceAndDifferentGuids()
{
List<String> originalGuids = new ArrayList<String>();
for (Map.Entry<DocumentReference, List<BaseObject>> entry : this.document.getXObjects().entrySet()) {
for (BaseObject baseObject : entry.getValue()) {
originalGuids.add(baseObject.getGuid());
}
}
XWikiDocument doc = new XWikiDocument(new DocumentReference("somewiki", "somespace", "somepage"));
doc.mergeXObjects(this.document);
assertTrue(doc.getXObjects().size() > 0);
// Verify that the object references point to the doc in which it's cloned.
// Verify that GUIDs are not the same as the original ones
for (Map.Entry<DocumentReference, List<BaseObject>> entry : doc.getXObjects().entrySet()) {
for (BaseObject baseObject : entry.getValue()) {
assertEquals(doc.getDocumentReference(), baseObject.getDocumentReference());
assertFalse("Non unique object GUID found!", originalGuids.contains(baseObject.getGuid()));
}
}
}
/** Check that a new empty document has empty content (used to have a new line before 2.5). */
public void testInitialContent()
{
XWikiDocument doc = new XWikiDocument(new DocumentReference("somewiki", "somespace", "somepage"));
assertEquals("", doc.getContent());
}
}
| XWIKI-6896: XWikiDocument#getXObject(ObjectReference) throws a NPE when
the object reference has no object number | xwiki-platform-core/xwiki-platform-oldcore/src/test/java/com/xpn/xwiki/doc/XWikiDocumentTest.java | XWIKI-6896: XWikiDocument#getXObject(ObjectReference) throws a NPE when the object reference has no object number |
|
Java | apache-2.0 | 73b28eacc7cfcd0ee2aac8d185ccbcee60e274e6 | 0 | ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,da1z/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,ibinti/intellij-community,semonte/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,semonte/intellij-community,ibinti/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,semonte/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,semonte/intellij-community,allotria/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,da1z/intellij-community,apixandru/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,apixandru/intellij-community,xfournet/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,allotria/intellij-community,apixandru/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,ibinti/intellij-community,FHannes/intellij-community,ibinti/intellij-community,xfournet/intellij-community,allotria/intellij-community,allotria/intellij-community,semonte/intellij-community,xfournet/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,allotria/intellij-community,da1z/intellij-community,asedunov/intellij-community,FHannes/intellij-community,semonte/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,semonte/intellij-community,ibinti/intellij-community,xfournet/intellij-community,apixandru/intellij-community,da1z/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,semonte/intellij-community,asedunov/intellij-community,semonte/intellij-community,apixandru/intellij-community,FHannes/intellij-community,xfournet/intellij-community,asedunov/intellij-community,da1z/intellij-community,allotria/intellij-community,semonte/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,da1z/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,asedunov/intellij-community,asedunov/intellij-community,apixandru/intellij-community,FHannes/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,allotria/intellij-community,xfournet/intellij-community,asedunov/intellij-community,allotria/intellij-community,apixandru/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,semonte/intellij-community,xfournet/intellij-community,apixandru/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,semonte/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,allotria/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,da1z/intellij-community,da1z/intellij-community,da1z/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,ibinti/intellij-community,allotria/intellij-community,ibinti/intellij-community | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.codeInsight;
import com.google.common.collect.Iterables;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiReferenceBase;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.ArrayUtil;
import com.jetbrains.python.inspections.PyStringFormatParser;
import com.jetbrains.python.inspections.PyStringFormatParser.NewStyleSubstitutionChunk;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.impl.PyPsiUtils;
import com.jetbrains.python.psi.resolve.PyResolveContext;
import com.jetbrains.python.psi.types.TypeEvalContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class PySubstitutionChunkReference extends PsiReferenceBase<PyStringLiteralExpression> implements PsiReferenceEx {
private final int myPosition;
@NotNull private final PyStringFormatParser.SubstitutionChunk myChunk;
private final boolean myIsPercent;
private final TypeEvalContext myTypeEvalContext;
public PySubstitutionChunkReference(@NotNull final PyStringLiteralExpression element,
@NotNull final PyStringFormatParser.SubstitutionChunk chunk, final int position) {
super(element, getKeywordRange(element, chunk));
myChunk = chunk;
myPosition = position;
myIsPercent = chunk instanceof PyStringFormatParser.PercentSubstitutionChunk;
final PsiFile file = element.getContainingFile();
myTypeEvalContext = TypeEvalContext.codeAnalysis(file.getProject(), file);
}
@Nullable
@Override
public HighlightSeverity getUnresolvedHighlightSeverity(@NotNull final TypeEvalContext context) {
return HighlightSeverity.WARNING;
}
@Nullable
@Override
public String getUnresolvedDescription() {
return null;
}
@NotNull
private static TextRange getKeywordRange(@NotNull final PyStringLiteralExpression element,
@NotNull final PyStringFormatParser.SubstitutionChunk chunk) {
final TextRange textRange = chunk.getTextRange();
if (chunk.getMappingKey() != null) {
final int start = textRange.getStartOffset() + chunk.getTextRange().substring(element.getText()).indexOf(chunk.getMappingKey());
return TextRange.from(start, chunk.getMappingKey().length());
}
return textRange;
}
@Nullable
@Override
public PsiElement resolve() {
return myIsPercent ? resolvePercentString() : resolveFormatString();
}
@Nullable
private PsiElement resolveFormatString() {
final PyArgumentList argumentList = getArgumentList(getElement());
if (argumentList == null || argumentList.getArguments().length == 0) {
return null;
}
return myChunk.getMappingKey() != null ? resolveKeywordFormat(argumentList).get() : resolvePositionalFormat(argumentList);
}
@Nullable
private PsiElement resolvePositionalFormat(@NotNull PyArgumentList argumentList) {
final int position = myChunk.getPosition() == null ? myPosition : myChunk.getPosition();
int n = 0;
boolean notSureAboutStarArgs = false;
PyStarArgument firstStarArg = null;
for (PyExpression arg : argumentList.getArguments()) {
final PyStarArgument starArg = PyUtil.as(arg, PyStarArgument.class);
if (starArg != null) {
if (!starArg.isKeyword()) {
if (firstStarArg == null) {
firstStarArg = starArg;
}
// TODO: Support multiple *args for Python 3.5+
final Ref<PyExpression> resolvedRef = resolvePositionalStarExpression(starArg, n);
if (resolvedRef != null) {
final PsiElement resolved = resolvedRef.get();
if (resolved != null) {
return resolved;
}
}
else {
notSureAboutStarArgs = true;
}
}
}
else if (!(arg instanceof PyKeywordArgument)) {
if (position == n) {
return arg;
}
n++;
}
}
return notSureAboutStarArgs ? firstStarArg : null;
}
@NotNull
private Ref<PyExpression> resolveKeywordFormat(@NotNull PyArgumentList argumentList) {
final Ref<PyExpression> valueExprRef = getKeyValueFromArguments(argumentList);
final String indexElement = myChunk instanceof NewStyleSubstitutionChunk ? ((NewStyleSubstitutionChunk)myChunk).getMappingKeyElementIndex() : null;
if (valueExprRef != null && !valueExprRef.isNull() && indexElement != null) {
final PyExpression valueExpr = PyPsiUtils.flattenParens(valueExprRef.get());
assert valueExpr != null;
try {
final Integer index = Integer.valueOf(indexElement);
final Ref<PyExpression> resolvedRef = resolveNumericIndex(valueExpr, index);
if (resolvedRef != null) return resolvedRef;
}
catch (NumberFormatException e) {
final Ref<PyExpression> resolvedRef = resolveStringIndex(valueExpr, indexElement);
if (resolvedRef != null) return resolvedRef;
}
}
// valueExprRef is null only if there's no corresponding keyword argument and no star arguments
return valueExprRef == null ? Ref.create() : valueExprRef;
}
@Nullable
private Ref<PyExpression> getKeyValueFromArguments(@NotNull PyArgumentList argumentList) {
final PyKeywordArgument valueFromKeywordArg = argumentList.getKeywordArgument(myChunk.getMappingKey());
final List<PyStarArgument> keywordStarArgs = getStarArguments(argumentList, true);
Ref<PyExpression> valueExprRef = null;
if (valueFromKeywordArg != null) {
valueExprRef = Ref.create(valueFromKeywordArg.getValueExpression());
}
else if (!keywordStarArgs.isEmpty()){
for (PyStarArgument arg : keywordStarArgs) {
final Ref<PyExpression> resolvedRef = resolveKeywordStarExpression(arg);
if (resolvedRef != null && (valueExprRef == null || valueExprRef.get() == null)) {
valueExprRef = resolvedRef;
}
}
if (valueExprRef == null) {
valueExprRef = Ref.create(Iterables.getFirst(keywordStarArgs, null));
}
}
return valueExprRef;
}
@Nullable
private Ref<PyExpression> resolveStringIndex(@NotNull PyExpression valueExpr, @NotNull String indexElement) {
final PyResolveContext resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(myTypeEvalContext);
if (valueExpr instanceof PyCallExpression) {
return resolveDictCall((PyCallExpression)valueExpr, indexElement, false);
}
else if (valueExpr instanceof PyDictLiteralExpression) {
Ref<PyExpression> resolvedRef = getElementFromDictLiteral((PyDictLiteralExpression)valueExpr, indexElement);
if (resolvedRef != null) return resolvedRef;
}
else if (valueExpr instanceof PyReferenceExpression) {
PsiElement element = ((PyReferenceExpression)valueExpr).followAssignmentsChain(resolveContext).getElement();
if (element != valueExpr && element instanceof PyExpression) {
return resolveStringIndex((PyExpression)element, indexElement);
}
}
return null;
}
@Nullable
private Ref<PyExpression> resolveNumericIndex(@NotNull PyExpression valueExpr, @NotNull Integer index) {
final PyResolveContext resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(myTypeEvalContext);
if (PyUtil.instanceOf(valueExpr, PyListLiteralExpression.class, PyTupleExpression.class, PyStringLiteralExpression.class)) {
Ref<PyExpression> elementRef = getElementByIndex(valueExpr, index);
if (elementRef != null) return elementRef;
}
else if (valueExpr instanceof PyDictLiteralExpression) {
return getElementFromDictLiteral((PyDictLiteralExpression)valueExpr, index);
}
else if (valueExpr instanceof PyReferenceExpression) {
PsiElement element = ((PyReferenceExpression)valueExpr).followAssignmentsChain(resolveContext).getElement();
if (element != null && element != valueExpr && element instanceof PyExpression) {
//noinspection ConstantConditions
return resolveNumericIndex(PyPsiUtils.flattenParens((PyExpression)element), index);
}
}
return null;
}
@Nullable
private Ref<PyExpression> getElementFromDictLiteral(@NotNull PyDictLiteralExpression valueExpr,
@NotNull Integer index) {
boolean allKeysForSure = true;
final PyKeyValueExpression[] elements = valueExpr.getElements();
for (PyKeyValueExpression element : elements) {
final PyNumericLiteralExpression key = PyUtil.as(element.getKey(), PyNumericLiteralExpression.class);
if (key != null && new Long(index).equals(key.getLongValue())) {
return Ref.create(element.getValue());
}
else if (!(element.getKey() instanceof PyLiteralExpression)) {
allKeysForSure = false;
}
}
PyDoubleStarExpression[] starExpressions = PsiTreeUtil.getChildrenOfType(valueExpr, PyDoubleStarExpression.class);
if (starExpressions != null) {
for (PyDoubleStarExpression expression : starExpressions) {
PyExpression underStarExpr = PyPsiUtils.flattenParens(expression.getExpression());
if (underStarExpr != null) {
if (underStarExpr instanceof PyDictLiteralExpression) {
Ref<PyExpression> expr = getElementFromDictLiteral((PyDictLiteralExpression)underStarExpr, index);
allKeysForSure = expr != null;
if (expr != null && !expr.isNull()) return expr;
}
else if (underStarExpr instanceof PyCallExpression) {
Ref<PyExpression> expr = resolveDictCall((PyCallExpression)underStarExpr, index.toString(), true);
allKeysForSure = expr != null;
if (expr != null && !expr.isNull()) return expr;
}
else {
allKeysForSure = false;
}
}
}
}
return allKeysForSure ? Ref.create() : null;
}
@Nullable
public static Ref<PyExpression> getElementByIndex(@NotNull PyExpression listTupleExpr, int index) {
boolean noElementsForSure = true;
int seenElementsNumber = 0;
PyExpression[] elements = getElementsFromListOrTuple(listTupleExpr);
for (PyExpression element : elements) {
if (element instanceof PyStarExpression) {
if (!LanguageLevel.forElement(element).isAtLeast(LanguageLevel.PYTHON35)) continue;
final PyExpression underStarExpr = PyPsiUtils.flattenParens(((PyStarExpression)element).getExpression());
if (PyUtil.instanceOf(underStarExpr, PyListLiteralExpression.class, PyTupleExpression.class)) {
PyExpression[] subsequenсeElements = getElementsFromListOrTuple(underStarExpr);
int subsequenceElementIndex = index - seenElementsNumber;
if (subsequenceElementIndex < subsequenсeElements.length) {
return Ref.create(subsequenсeElements[subsequenceElementIndex]);
}
if (noElementsForSure) noElementsForSure = Arrays.stream(subsequenсeElements).noneMatch(it -> it instanceof PyStarExpression);
seenElementsNumber += subsequenсeElements.length;
}
else {
noElementsForSure = false;
break;
}
}
else {
if (index == seenElementsNumber) {
return Ref.create(element);
}
seenElementsNumber++;
}
}
return noElementsForSure ? Ref.create() : null;
}
public static PyExpression[] getElementsFromListOrTuple(@NotNull final PyExpression expression) {
if (expression instanceof PyListLiteralExpression) {
return ((PyListLiteralExpression)expression).getElements();
}
else if (expression instanceof PyTupleExpression) {
return ((PyTupleExpression)expression).getElements();
}
else if (expression instanceof PyStringLiteralExpression) {
String value = ((PyStringLiteralExpression)expression).getStringValue();
if (value != null) {
// Strings might be packed as well as dicts, so we need to resolve somehow to string element.
// But string element isn't PyExpression so I decided to resolve to PyStringLiteralExpression for
// every string element
PyExpression[] result = new PyExpression[value.length()];
for (int i = 0; i < value.length(); i++) {
result[i] = expression;
}
return result;
}
}
return PyExpression.EMPTY_ARRAY;
}
@NotNull
private static List<PyStarArgument> getStarArguments(@NotNull PyArgumentList argumentList,
@SuppressWarnings("SameParameterValue") boolean isKeyword) {
return Arrays.stream(argumentList.getArguments())
.map(expression -> PyUtil.as(expression, PyStarArgument.class))
.filter(argument -> argument != null && argument.isKeyword() == isKeyword).collect(Collectors.toList());
}
@Nullable
private PsiElement resolvePercentString() {
final PyBinaryExpression binaryExpression = PsiTreeUtil.getParentOfType(getElement(), PyBinaryExpression.class);
if (binaryExpression != null) {
final PyExpression rightExpression = binaryExpression.getRightExpression();
if (rightExpression == null) {
return null;
}
boolean isKeyWordSubstitution = myChunk.getMappingKey() != null;
return isKeyWordSubstitution ? resolveKeywordPercent(rightExpression, myChunk.getMappingKey()) : resolvePositionalPercent(rightExpression);
}
return null;
}
@Nullable
private PyExpression resolveKeywordPercent(@NotNull PyExpression expression, @NotNull String key) {
final PyExpression containedExpr = PyPsiUtils.flattenParens(expression);
if (PyUtil.instanceOf(containedExpr, PyDictLiteralExpression.class)) {
final Ref<PyExpression> resolvedRef = getElementFromDictLiteral((PyDictLiteralExpression)containedExpr, key);
return resolvedRef != null ? resolvedRef.get() : containedExpr;
}
else if (PyUtil.instanceOf(containedExpr, PyLiteralExpression.class, PySetLiteralExpression.class,
PyListLiteralExpression.class, PyTupleExpression.class)) {
return null;
}
else if (containedExpr instanceof PyCallExpression) {
if (myChunk.getMappingKey() != null) {
Ref<PyExpression> elementRef = resolveDictCall((PyCallExpression)containedExpr, myChunk.getMappingKey(), true);
if (elementRef != null) return elementRef.get();
}
}
return containedExpr;
}
@Nullable
private PsiElement resolvePositionalPercent(@NotNull PyExpression expression) {
final PyExpression containedExpression = PyPsiUtils.flattenParens(expression);
if (containedExpression instanceof PyTupleExpression) {
final PyExpression[] elements = ((PyTupleExpression)containedExpression).getElements();
return myPosition < elements.length ? elements[myPosition] : null;
}
else if (containedExpression instanceof PyBinaryExpression && ((PyBinaryExpression)containedExpression).isOperator("+")) {
return resolveNotNestedBinaryExpression((PyBinaryExpression)containedExpression);
}
else if (containedExpression instanceof PyCallExpression) {
final PyExpression callee = ((PyCallExpression)containedExpression).getCallee();
if (callee != null && "dict".equals(callee.getName()) && myPosition != 0) {
return null;
}
}
else if (myPosition != 0 && PsiTreeUtil.instanceOf(containedExpression, PyLiteralExpression.class, PySetLiteralExpression.class,
PyListLiteralExpression.class, PyDictLiteralExpression.class)) {
return null;
}
return containedExpression;
}
@Nullable
private PsiElement resolveNotNestedBinaryExpression(@NotNull PyBinaryExpression containedExpression) {
PyExpression left = containedExpression.getLeftExpression();
PyExpression right = containedExpression.getRightExpression();
if (left instanceof PyParenthesizedExpression) {
PyExpression leftTuple = PyPsiUtils.flattenParens(left);
if (leftTuple instanceof PyTupleExpression) {
PyExpression[] leftTupleElements = ((PyTupleExpression)leftTuple).getElements();
int leftTupleLength = leftTupleElements.length;
if (leftTupleLength > myPosition) {
return leftTupleElements[myPosition];
}
if (right instanceof PyTupleExpression) {
PyExpression[] rightTupleElements = ((PyTupleExpression)right).getElements();
int rightLength = rightTupleElements.length;
if (leftTupleLength + rightLength > myPosition) return rightTupleElements[myPosition - leftTupleLength];
}
}
}
return containedExpression;
}
@Nullable
private static PyArgumentList getArgumentList(final PsiElement original) {
final PsiElement pyReferenceExpression = PsiTreeUtil.getParentOfType(original, PyReferenceExpression.class);
return PsiTreeUtil.getNextSiblingOfType(pyReferenceExpression, PyArgumentList.class);
}
@Nullable
private Ref<PyExpression> resolveKeywordStarExpression(@NotNull PyStarArgument starArgument) {
// TODO: support call, reference expressions here
final PyDictLiteralExpression dictExpr = PsiTreeUtil.getChildOfType(starArgument, PyDictLiteralExpression.class);
final PyCallExpression callExpression = PsiTreeUtil.getChildOfType(starArgument, PyCallExpression.class);
final String key = myChunk.getMappingKey();
assert key != null;
if (dictExpr != null) {
return getElementFromDictLiteral(dictExpr, key);
}
else if (callExpression != null) {
return resolveDictCall(callExpression, key, false);
}
return null;
}
@Nullable
private Ref<PyExpression> resolvePositionalStarExpression(@NotNull PyStarArgument starArgument, int argumentPosition) {
final PyExpression expr = PyPsiUtils.flattenParens(PsiTreeUtil.getChildOfAnyType(starArgument, PyListLiteralExpression.class, PyParenthesizedExpression.class,
PyStringLiteralExpression.class));
if (expr == null) {
return Ref.create(starArgument);
}
final int position = (myChunk.getPosition() != null ? myChunk.getPosition() : myPosition) - argumentPosition;
return getElementByIndex(expr, position);
}
@Nullable
private Ref<PyExpression> getElementFromDictLiteral(@NotNull PyDictLiteralExpression expression, @NotNull String mappingKey) {
final PyKeyValueExpression[] keyValueExpressions = expression.getElements();
boolean allKeysForSure = true;
for (PyKeyValueExpression keyValueExpression : keyValueExpressions) {
PyExpression keyExpression = keyValueExpression.getKey();
if (keyExpression instanceof PyStringLiteralExpression) {
final PyStringLiteralExpression key = (PyStringLiteralExpression)keyExpression;
if (key.getStringValue().equals(mappingKey)) {
return Ref.create(keyValueExpression.getValue());
}
}
else if (!(keyExpression instanceof PyLiteralExpression)) {
allKeysForSure = false;
}
}
final LanguageLevel languageLevel = LanguageLevel.forElement(expression);
PyDoubleStarExpression[] starExpressions = PsiTreeUtil.getChildrenOfType(expression, PyDoubleStarExpression.class);
if (languageLevel.isAtLeast(LanguageLevel.PYTHON35) && starExpressions != null) {
for (PyDoubleStarExpression expr : starExpressions) {
PyExpression underStarExpr = PyPsiUtils.flattenParens(expr.getExpression());
if (underStarExpr != null) {
if (underStarExpr instanceof PyDictLiteralExpression) {
Ref<PyExpression> element = getElementFromDictLiteral((PyDictLiteralExpression)underStarExpr, mappingKey);
allKeysForSure = element != null;
if (element != null && !element.isNull()) return element;
}
else if (underStarExpr instanceof PyCallExpression) {
Ref<PyExpression> element = resolveDictCall((PyCallExpression)underStarExpr, mappingKey, true);
allKeysForSure = element != null;
if (element != null && !element.isNull()) return element;
}
else {
allKeysForSure = false;
}
}
}
}
return allKeysForSure ? Ref.create() : null;
}
@Nullable
private Ref<PyExpression> resolveDictCall(@NotNull PyCallExpression expression, @NotNull String key, boolean goDeep) {
final PyExpression callee = expression.getCallee();
boolean allKeysForSure = true;
final LanguageLevel languageLevel = LanguageLevel.forElement(expression);
if (callee != null) {
final String name = callee.getName();
if ("dict".equals(name)) {
final PyArgumentList argumentList = expression.getArgumentList();
for (PyExpression arg : expression.getArguments()) {
if (languageLevel.isAtLeast(LanguageLevel.PYTHON35) && goDeep && arg instanceof PyStarExpression) {
PyExpression expr = ((PyStarExpression)arg).getExpression();
if (expr instanceof PyDictLiteralExpression) {
Ref<PyExpression> element = getElementFromDictLiteral((PyDictLiteralExpression)expr, key);
if (element != null) return element;
}
else if (expr instanceof PyCallExpression) {
Ref<PyExpression> element = resolveDictCall((PyCallExpression)expr, key, false);
if (element != null) return element;
}
else {
allKeysForSure = false;
}
}
if (!(arg instanceof PyKeywordArgument)) {
allKeysForSure = false;
}
}
if (argumentList != null) {
PyKeywordArgument argument = argumentList.getKeywordArgument(key);
if (argument != null) {
return Ref.create(argument);
}
else {
return allKeysForSure ? Ref.create() : null;
}
}
}
}
return Ref.create(expression);
}
@NotNull
@Override
public Object[] getVariants() {
return ArrayUtil.EMPTY_OBJECT_ARRAY;
}
}
| python/src/com/jetbrains/python/codeInsight/PySubstitutionChunkReference.java | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.codeInsight;
import com.google.common.collect.Iterables;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiReferenceBase;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.ArrayUtil;
import com.jetbrains.python.inspections.PyStringFormatParser;
import com.jetbrains.python.inspections.PyStringFormatParser.NewStyleSubstitutionChunk;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.impl.PyPsiUtils;
import com.jetbrains.python.psi.resolve.PyResolveContext;
import com.jetbrains.python.psi.types.TypeEvalContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class PySubstitutionChunkReference extends PsiReferenceBase<PyStringLiteralExpression> implements PsiReferenceEx {
private final int myPosition;
@NotNull private final PyStringFormatParser.SubstitutionChunk myChunk;
private final boolean myIsPercent;
private final TypeEvalContext myTypeEvalContext;
public PySubstitutionChunkReference(@NotNull final PyStringLiteralExpression element,
@NotNull final PyStringFormatParser.SubstitutionChunk chunk, final int position) {
super(element, getKeywordRange(element, chunk));
myChunk = chunk;
myPosition = position;
myIsPercent = chunk instanceof PyStringFormatParser.PercentSubstitutionChunk;
final PsiFile file = element.getContainingFile();
myTypeEvalContext = TypeEvalContext.codeAnalysis(file.getProject(), file);
}
@Nullable
@Override
public HighlightSeverity getUnresolvedHighlightSeverity(@NotNull final TypeEvalContext context) {
return HighlightSeverity.WARNING;
}
@Nullable
@Override
public String getUnresolvedDescription() {
return null;
}
@NotNull
private static TextRange getKeywordRange(@NotNull final PyStringLiteralExpression element,
@NotNull final PyStringFormatParser.SubstitutionChunk chunk) {
final TextRange textRange = chunk.getTextRange();
if (chunk.getMappingKey() != null) {
final int start = textRange.getStartOffset() + chunk.getTextRange().substring(element.getText()).indexOf(chunk.getMappingKey());
return TextRange.from(start, chunk.getMappingKey().length());
}
return textRange;
}
@Nullable
@Override
public PsiElement resolve() {
return myIsPercent ? resolvePercentString() : resolveFormatString();
}
@Nullable
private PsiElement resolveFormatString() {
final PyArgumentList argumentList = getArgumentList(getElement());
if (argumentList == null || argumentList.getArguments().length == 0) {
return null;
}
return myChunk.getMappingKey() != null ? resolveKeywordFormat(argumentList).get() : resolvePositionalFormat(argumentList);
}
@Nullable
private PsiElement resolvePositionalFormat(@NotNull PyArgumentList argumentList) {
final int position = myChunk.getPosition() == null ? myPosition : myChunk.getPosition();
int n = 0;
boolean notSureAboutStarArgs = false;
PyStarArgument firstStarArg = null;
for (PyExpression arg : argumentList.getArguments()) {
final PyStarArgument starArg = PyUtil.as(arg, PyStarArgument.class);
if (starArg != null) {
if (!starArg.isKeyword()) {
if (firstStarArg == null) {
firstStarArg = starArg;
}
// TODO: Support multiple *args for Python 3.5+
final Ref<PyExpression> resolvedRef = resolvePositionalStarExpression(starArg, n);
if (resolvedRef != null) {
final PsiElement resolved = resolvedRef.get();
if (resolved != null) {
return resolved;
}
}
else {
notSureAboutStarArgs = true;
}
}
}
else if (!(arg instanceof PyKeywordArgument)) {
if (position == n) {
return arg;
}
n++;
}
}
return notSureAboutStarArgs ? firstStarArg : null;
}
@NotNull
private Ref<PyExpression> resolveKeywordFormat(@NotNull PyArgumentList argumentList) {
final Ref<PyExpression> valueExprRef = getKeyValueFromArguments(argumentList);
final String indexElement = myChunk instanceof NewStyleSubstitutionChunk ? ((NewStyleSubstitutionChunk)myChunk).getMappingKeyElementIndex() : null;
if (valueExprRef != null && !valueExprRef.isNull() && indexElement != null) {
final PyExpression valueExpr = PyPsiUtils.flattenParens(valueExprRef.get());
assert valueExpr != null;
try {
final Integer index = Integer.valueOf(indexElement);
final Ref<PyExpression> resolvedRef = resolveNumericIndex(valueExpr, index);
if (resolvedRef != null) return resolvedRef;
}
catch (NumberFormatException e) {
final Ref<PyExpression> resolvedRef = resolveStringIndex(valueExpr, indexElement);
if (resolvedRef != null) return resolvedRef;
}
}
// valueExprRef is null only if there's no corresponding keyword argument and no star arguments
return valueExprRef == null ? Ref.create() : valueExprRef;
}
@Nullable
private Ref<PyExpression> getKeyValueFromArguments(@NotNull PyArgumentList argumentList) {
final PyKeywordArgument valueFromKeywordArg = argumentList.getKeywordArgument(myChunk.getMappingKey());
final List<PyStarArgument> keywordStarArgs = getStarArguments(argumentList, true);
Ref<PyExpression> valueExprRef = null;
if (valueFromKeywordArg != null) {
valueExprRef = Ref.create(valueFromKeywordArg.getValueExpression());
}
else if (!keywordStarArgs.isEmpty()){
for (PyStarArgument arg : keywordStarArgs) {
final Ref<PyExpression> resolvedRef = resolveKeywordStarExpression(arg);
if (resolvedRef != null && (valueExprRef == null || valueExprRef.get() == null)) {
valueExprRef = resolvedRef;
}
}
if (valueExprRef == null) {
valueExprRef = Ref.create(Iterables.getFirst(keywordStarArgs, null));
}
}
return valueExprRef;
}
@Nullable
private Ref<PyExpression> resolveStringIndex(@NotNull PyExpression valueExpr, @NotNull String indexElement) {
final PyResolveContext resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(myTypeEvalContext);
if (valueExpr instanceof PyCallExpression) {
return resolveDictCall((PyCallExpression)valueExpr, indexElement, false);
}
else if (valueExpr instanceof PyDictLiteralExpression) {
Ref<PyExpression> resolvedRef = getElementFromDictLiteral(valueExpr, indexElement);
if (resolvedRef != null) return resolvedRef;
}
else if (valueExpr instanceof PyReferenceExpression) {
PsiElement element = ((PyReferenceExpression)valueExpr).followAssignmentsChain(resolveContext).getElement();
if (element != valueExpr && element instanceof PyExpression) {
return resolveStringIndex((PyExpression)element, indexElement);
}
}
return null;
}
@Nullable
private Ref<PyExpression> resolveNumericIndex(@NotNull PyExpression valueExpr, @NotNull Integer index) {
final PyResolveContext resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(myTypeEvalContext);
if (PyUtil.instanceOf(valueExpr, PyListLiteralExpression.class, PyTupleExpression.class, PyStringLiteralExpression.class)) {
Ref<PyExpression> elementRef = getElementByIndex(valueExpr, index);
if (elementRef != null) return elementRef;
}
else if (valueExpr instanceof PyDictLiteralExpression) {
return getElementFromDictLiteral((PyDictLiteralExpression)valueExpr, index);
}
else if (valueExpr instanceof PyReferenceExpression) {
PsiElement element = ((PyReferenceExpression)valueExpr).followAssignmentsChain(resolveContext).getElement();
if (element != null && element != valueExpr && element instanceof PyExpression) {
//noinspection ConstantConditions
return resolveNumericIndex(PyPsiUtils.flattenParens((PyExpression)element), index);
}
}
return null;
}
@Nullable
private Ref<PyExpression> getElementFromDictLiteral(@NotNull PyDictLiteralExpression valueExpr,
@NotNull Integer index) {
boolean allKeysForSure = true;
final PyKeyValueExpression[] elements = valueExpr.getElements();
for (PyKeyValueExpression element : elements) {
final PyNumericLiteralExpression key = PyUtil.as(element.getKey(), PyNumericLiteralExpression.class);
if (key != null && new Long(index).equals(key.getLongValue())) {
return Ref.create(element.getValue());
}
else if (!(element.getKey() instanceof PyLiteralExpression)) {
allKeysForSure = false;
}
}
PyDoubleStarExpression[] starExpressions = PsiTreeUtil.getChildrenOfType(valueExpr, PyDoubleStarExpression.class);
if (starExpressions != null) {
for (PyDoubleStarExpression expression : starExpressions) {
PyExpression underStarExpr = PyPsiUtils.flattenParens(expression.getExpression());
if (underStarExpr != null) {
if (underStarExpr instanceof PyDictLiteralExpression) {
Ref<PyExpression> expr = getElementFromDictLiteral((PyDictLiteralExpression)underStarExpr, index);
allKeysForSure = expr != null;
if (expr != null && !expr.isNull()) return expr;
}
else if (underStarExpr instanceof PyCallExpression) {
Ref<PyExpression> expr = getElementFromCallExpression((PyCallExpression)underStarExpr, index.toString());
allKeysForSure = expr != null;
if (expr != null && !expr.isNull()) return expr;
}
else {
allKeysForSure = false;
}
}
}
}
return allKeysForSure ? Ref.create() : null;
}
@Nullable
private Ref<PyExpression> getElementFromCallExpression(@NotNull PyCallExpression valueExpr,
@NotNull String key) {
final PyExpression callee = valueExpr.getCallee();
if (callee != null && "dict".equals(callee.getName())) {
return resolveDictCall(valueExpr, key, true);
}
return null;
}
@Nullable
public static Ref<PyExpression> getElementByIndex(@NotNull PyExpression listTupleExpr, int index) {
boolean noElementsForSure = true;
int seenElementsNumber = 0;
PyExpression[] elements = getElementsFromListOrTuple(listTupleExpr);
for (PyExpression element : elements) {
if (element instanceof PyStarExpression) {
if (!LanguageLevel.forElement(element).isAtLeast(LanguageLevel.PYTHON35)) continue;
final PyExpression underStarExpr = PyPsiUtils.flattenParens(((PyStarExpression)element).getExpression());
if (PyUtil.instanceOf(underStarExpr, PyListLiteralExpression.class, PyTupleExpression.class)) {
PyExpression[] subsequenсeElements = getElementsFromListOrTuple(underStarExpr);
int subsequenceElementIndex = index - seenElementsNumber;
if (subsequenceElementIndex < subsequenсeElements.length) {
return Ref.create(subsequenсeElements[subsequenceElementIndex]);
}
if (noElementsForSure) noElementsForSure = Arrays.stream(subsequenсeElements).noneMatch(it -> it instanceof PyStarExpression);
seenElementsNumber += subsequenсeElements.length;
}
else {
noElementsForSure = false;
break;
}
}
else {
if (index == seenElementsNumber) {
return Ref.create(element);
}
seenElementsNumber++;
}
}
return noElementsForSure ? Ref.create() : null;
}
public static PyExpression[] getElementsFromListOrTuple(@NotNull final PyExpression expression) {
if (expression instanceof PyListLiteralExpression) {
return ((PyListLiteralExpression)expression).getElements();
}
else if (expression instanceof PyTupleExpression) {
return ((PyTupleExpression)expression).getElements();
}
else if (expression instanceof PyStringLiteralExpression) {
String value = ((PyStringLiteralExpression)expression).getStringValue();
if (value != null) {
// Strings might be packed as well as dicts, so we need to resolve somehow to string element.
// But string element isn't PyExpression so I decided to resolve to PyStringLiteralExpression for
// every string element
PyExpression[] result = new PyExpression[value.length()];
for (int i = 0; i < value.length(); i++) {
result[i] = expression;
}
return result;
}
}
return PyExpression.EMPTY_ARRAY;
}
@NotNull
private static List<PyStarArgument> getStarArguments(@NotNull PyArgumentList argumentList,
@SuppressWarnings("SameParameterValue") boolean isKeyword) {
return Arrays.stream(argumentList.getArguments())
.map(expression -> PyUtil.as(expression, PyStarArgument.class))
.filter(argument -> argument != null && argument.isKeyword() == isKeyword).collect(Collectors.toList());
}
@Nullable
private PsiElement resolvePercentString() {
final PyBinaryExpression binaryExpression = PsiTreeUtil.getParentOfType(getElement(), PyBinaryExpression.class);
if (binaryExpression != null) {
final PyExpression rightExpression = binaryExpression.getRightExpression();
if (rightExpression == null) {
return null;
}
boolean isKeyWordSubstitution = myChunk.getMappingKey() != null;
return isKeyWordSubstitution ? resolveKeywordPercent(rightExpression, myChunk.getMappingKey()) : resolvePositionalPercent(rightExpression);
}
return null;
}
@Nullable
private PyExpression resolveKeywordPercent(@NotNull PyExpression expression, @NotNull String key) {
final PyExpression containedExpr = PyPsiUtils.flattenParens(expression);
if (PyUtil.instanceOf(containedExpr, PyDictLiteralExpression.class, PyCallExpression.class)) {
final Ref<PyExpression> resolvedRef = getElementFromDictLiteral(containedExpr, key);
return resolvedRef != null ? resolvedRef.get() : containedExpr;
}
else if (PyUtil.instanceOf(containedExpr, PyLiteralExpression.class, PySetLiteralExpression.class,
PyListLiteralExpression.class, PyTupleExpression.class)) {
return null;
}
else if (containedExpr instanceof PyCallExpression) {
if (myChunk.getMappingKey() != null) {
Ref<PyExpression> elementRef = resolveDictCall((PyCallExpression)containedExpr, myChunk.getMappingKey(), true);
if (elementRef != null) return elementRef.get();
}
}
return containedExpr;
}
@Nullable
private PsiElement resolvePositionalPercent(@NotNull PyExpression expression) {
final PyExpression containedExpression = PyPsiUtils.flattenParens(expression);
if (containedExpression instanceof PyTupleExpression) {
final PyExpression[] elements = ((PyTupleExpression)containedExpression).getElements();
return myPosition < elements.length ? elements[myPosition] : null;
}
else if (containedExpression instanceof PyBinaryExpression && ((PyBinaryExpression)containedExpression).isOperator("+")) {
return resolveNotNestedBinaryExpression((PyBinaryExpression)containedExpression);
}
else if (containedExpression instanceof PyCallExpression) {
final PyExpression callee = ((PyCallExpression)containedExpression).getCallee();
if (callee != null && "dict".equals(callee.getName()) && myPosition != 0) {
return null;
}
}
else if (myPosition != 0 && PsiTreeUtil.instanceOf(containedExpression, PyLiteralExpression.class, PySetLiteralExpression.class,
PyListLiteralExpression.class, PyDictLiteralExpression.class)) {
return null;
}
return containedExpression;
}
@Nullable
private PsiElement resolveNotNestedBinaryExpression(@NotNull PyBinaryExpression containedExpression) {
PyExpression left = containedExpression.getLeftExpression();
PyExpression right = containedExpression.getRightExpression();
if (left instanceof PyParenthesizedExpression) {
PyExpression leftTuple = PyPsiUtils.flattenParens(left);
if (leftTuple instanceof PyTupleExpression) {
PyExpression[] leftTupleElements = ((PyTupleExpression)leftTuple).getElements();
int leftTupleLength = leftTupleElements.length;
if (leftTupleLength > myPosition) {
return leftTupleElements[myPosition];
}
if (right instanceof PyTupleExpression) {
PyExpression[] rightTupleElements = ((PyTupleExpression)right).getElements();
int rightLength = rightTupleElements.length;
if (leftTupleLength + rightLength > myPosition) return rightTupleElements[myPosition - leftTupleLength];
}
}
}
return containedExpression;
}
@Nullable
private static PyArgumentList getArgumentList(final PsiElement original) {
final PsiElement pyReferenceExpression = PsiTreeUtil.getParentOfType(original, PyReferenceExpression.class);
return PsiTreeUtil.getNextSiblingOfType(pyReferenceExpression, PyArgumentList.class);
}
@Nullable
private Ref<PyExpression> resolveKeywordStarExpression(@NotNull PyStarArgument starArgument) {
// TODO: support call, reference expressions here
final PyDictLiteralExpression dictExpr = PsiTreeUtil.getChildOfType(starArgument, PyDictLiteralExpression.class);
final PyCallExpression callExpression = PsiTreeUtil.getChildOfType(starArgument, PyCallExpression.class);
final String key = myChunk.getMappingKey();
assert key != null;
if (dictExpr != null) {
return getElementFromDictLiteral(dictExpr, key);
}
else if (callExpression != null) {
return resolveDictCall(callExpression, key, false);
}
return null;
}
@Nullable
private Ref<PyExpression> resolvePositionalStarExpression(@NotNull PyStarArgument starArgument, int argumentPosition) {
final PyExpression expr = PyPsiUtils.flattenParens(PsiTreeUtil.getChildOfAnyType(starArgument, PyListLiteralExpression.class, PyParenthesizedExpression.class,
PyStringLiteralExpression.class));
if (expr == null) {
return Ref.create(starArgument);
}
final int position = (myChunk.getPosition() != null ? myChunk.getPosition() : myPosition) - argumentPosition;
return getElementByIndex(expr, position);
}
@Nullable
private Ref<PyExpression> getElementFromDictLiteral(@NotNull PyExpression expression,
@NotNull String mappingKey) {
if (expression instanceof PyDictLiteralExpression) {
final PyKeyValueExpression[] keyValueExpressions = ((PyDictLiteralExpression)expression).getElements();
boolean allKeysForSure = true;
for (PyKeyValueExpression keyValueExpression : keyValueExpressions) {
PyExpression keyExpression = keyValueExpression.getKey();
if (keyExpression instanceof PyStringLiteralExpression) {
final PyStringLiteralExpression key = (PyStringLiteralExpression)keyExpression;
if (key.getStringValue().equals(mappingKey)) {
return Ref.create(keyValueExpression.getValue());
}
}
else if (!(keyExpression instanceof PyLiteralExpression)) {
allKeysForSure = false;
}
}
final LanguageLevel languageLevel = LanguageLevel.forElement(expression);
PyDoubleStarExpression[] starExpressions = PsiTreeUtil.getChildrenOfType(expression, PyDoubleStarExpression.class);
if (languageLevel.isAtLeast(LanguageLevel.PYTHON35) && starExpressions != null) {
for (PyDoubleStarExpression expr : starExpressions) {
PyExpression underStarExpr = PyPsiUtils.flattenParens(expr.getExpression());
if (underStarExpr != null) {
if (underStarExpr instanceof PyDictLiteralExpression) {
Ref<PyExpression> element = getElementFromDictLiteral(underStarExpr, mappingKey);
allKeysForSure = element != null;
if (element != null && !element.isNull()) return element;
}
else if (underStarExpr instanceof PyCallExpression) {
Ref<PyExpression> element = getElementFromCallExpression((PyCallExpression)underStarExpr, mappingKey);
allKeysForSure = element != null;
if (element != null && !element.isNull()) return element;
}
else {
allKeysForSure = false;
}
}
}
}
return allKeysForSure ? Ref.create() : null;
}
else if (expression instanceof PyCallExpression) {
return resolveDictCall((PyCallExpression)expression, mappingKey, false);
}
return null;
}
@Nullable
private Ref<PyExpression> resolveDictCall(@NotNull PyCallExpression expression, @NotNull String key, boolean goDeep) {
final PyExpression callee = expression.getCallee();
boolean allKeysForSure = true;
final LanguageLevel languageLevel = LanguageLevel.forElement(expression);
if (callee != null) {
final String name = callee.getName();
if ("dict".equals(name)) {
final PyArgumentList argumentList = expression.getArgumentList();
for (PyExpression arg : expression.getArguments()) {
if (languageLevel.isAtLeast(LanguageLevel.PYTHON35) && goDeep && arg instanceof PyStarExpression) {
PyExpression expr = ((PyStarExpression)arg).getExpression();
if (expr instanceof PyDictLiteralExpression) {
Ref<PyExpression> element = getElementFromDictLiteral(expr, key);
if (element != null) return element;
}
else if (expr instanceof PyCallExpression) {
Ref<PyExpression> element = resolveDictCall((PyCallExpression)expr, key, false);
if (element != null) return element;
}
else {
allKeysForSure = false;
}
}
if (!(arg instanceof PyKeywordArgument)) {
allKeysForSure = false;
}
}
if (argumentList != null) {
PyKeywordArgument argument = argumentList.getKeywordArgument(key);
if (argument != null) {
return Ref.create(argument);
}
else {
return allKeysForSure ? Ref.create() : null;
}
}
}
}
return Ref.create(expression);
}
@NotNull
@Override
public Object[] getVariants() {
return ArrayUtil.EMPTY_OBJECT_ARRAY;
}
}
| Fix resolving dict: 1) Remove dict call resolving part from getElementFromDictLiteral 2) Get rid of useless getElementFromCallExpression
| python/src/com/jetbrains/python/codeInsight/PySubstitutionChunkReference.java | Fix resolving dict: 1) Remove dict call resolving part from getElementFromDictLiteral 2) Get rid of useless getElementFromCallExpression |
|
Java | apache-2.0 | 5e2d6e3f633b6479b35f6889af7733b972f56fe3 | 0 | bobvdvalk/smokesignal | package nl.mawoo.smokesignal;
import nl.mawoo.smokesignal.gui.Cli;
import nl.mawoo.smokesignal.networking.P2P;
import nl.mawoo.smokesignal.networking.Peer;
import nl.mawoo.smokesignal.util.Util;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.Scanner;
/**
* Boot up the p2p application and listen for in and output
*
* @author Bob van der Valk
*/
// TODO: implement validation
// TODO: let others know about others in the network so they can connect
// TODO: Make sure it works with Android devices
public class SmokeSignal {
private static final Logger LOGGER = Logger.getLogger(SmokeSignal.class);
private static final Scanner SCANNER = new Scanner(System.in);
public static void main(String[] args) {
LOGGER.info(" ----- Starting SmokeSignal application -----");
LOGGER.info("Building socket");
ServerSocket serverSocket = buildSocket();
LOGGER.info("generating name");
String handleName = getRandomName();
P2P backend = new P2P(serverSocket);
Cli cli = new Cli(SCANNER, handleName, backend::connect);
backend.addNodeListener(socket -> {
try {
Peer peer = new Peer(socket);
cli.addPeer(peer);
peer.start();
} catch (IOException e) {
LOGGER.error("cannot start the peer. ", e);
}
});
backend.start();
cli.start();
LOGGER.info("Connect to other clients typing: /host:port . Like /localhost:8080");
}
/**
* Generate a random name for the client
* @return client-{randomnumber}
*/
private static String getRandomName() {
return "client-"+ Util.random4DigitNumber();
}
/**
* Use a random port number to build the socket
* @return Active server socket
*/
private static ServerSocket buildSocket() {
ServerSocket result = null;
while(result == null) {
try {
result = new ServerSocket(Util.random4DigitNumber());
} catch (IOException e) {
LOGGER.error("Could not connect to port. ", e);
}
}
LOGGER.info("connection found on port: "+ result.getLocalPort());
return result;
}
}
| src/main/java/nl/mawoo/smokesignal/SmokeSignal.java | package nl.mawoo.smokesignal;
import nl.mawoo.smokesignal.gui.Cli;
import nl.mawoo.smokesignal.networking.P2P;
import nl.mawoo.smokesignal.networking.Peer;
import nl.mawoo.smokesignal.util.Util;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.Scanner;
/**
* Boot up the p2p application and listen for in and output
*
* @author Bob van der Valk
*/
// TODO: implement validation
// TODO: let others know about others in the network so they can connect
// TODO: Make sure it works with Android devices
public class SmokeSignal {
private static final Logger LOGGER = Logger.getLogger(SmokeSignal.class);
private static final Scanner SCANNER = new Scanner(System.in);
public static void main(String[] args) {
LOGGER.info(" ----- Starting SmokeSignal application -----");
LOGGER.info("Building socket");
ServerSocket serverSocket = buildSocket();
LOGGER.info("generating name");
String handleName = getRandomName();
P2P backend = new P2P(serverSocket);
Cli cli = new Cli(SCANNER, handleName, backend::connect);
backend.addNodeListener(socket -> {
try {
Peer peer = new Peer(socket);
cli.addPeer(peer);
peer.start();
} catch (IOException e) {
LOGGER.error("cannot start the peer. ", e);
}
});
backend.start();
cli.start();
LOGGER.info("Connect to other clients typing: /host:port . Like /localhost:8080");
}
/**
* Generate a random name for the client
* @return client-{randomnumber}
*/
private static String getRandomName() {
return "client-"+ Util.random4DigitNumber();
}
/**
* Use a random port number to build the socket
* @return Active server socket
*/
private static ServerSocket buildSocket() {
ServerSocket result = null;
int port = Util.random4DigitNumber();
while(result == null) {
try {
result = new ServerSocket(port);
} catch (IOException e) {
LOGGER.error("Could not connect to port. "+ port, e);
}
}
LOGGER.info("connection found on port: "+ port);
return result;
}
}
| fix bug if a port is already used
| src/main/java/nl/mawoo/smokesignal/SmokeSignal.java | fix bug if a port is already used |
|
Java | apache-2.0 | e139a4652a8307080502bf98482fa2ff3951f53a | 0 | ened/ExoPlayer,ened/ExoPlayer,androidx/media,google/ExoPlayer,google/ExoPlayer,amzn/exoplayer-amazon-port,androidx/media,androidx/media,amzn/exoplayer-amazon-port,google/ExoPlayer,amzn/exoplayer-amazon-port,ened/ExoPlayer | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.video;
import static com.google.android.exoplayer2.mediacodec.MediaCodecInfo.KEEP_CODEC_RESULT_NO;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Point;
import android.media.MediaCodec;
import android.media.MediaCodecInfo.CodecCapabilities;
import android.media.MediaCodecInfo.CodecProfileLevel;
import android.media.MediaCrypto;
import android.media.MediaFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Pair;
import android.view.Surface;
import androidx.annotation.CallSuper;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.FormatHolder;
import com.google.android.exoplayer2.PlayerMessage.Target;
import com.google.android.exoplayer2.RendererCapabilities;
import com.google.android.exoplayer2.decoder.DecoderCounters;
import com.google.android.exoplayer2.decoder.DecoderInputBuffer;
import com.google.android.exoplayer2.drm.DrmInitData;
import com.google.android.exoplayer2.mediacodec.MediaCodecAdapter;
import com.google.android.exoplayer2.mediacodec.MediaCodecDecoderException;
import com.google.android.exoplayer2.mediacodec.MediaCodecInfo;
import com.google.android.exoplayer2.mediacodec.MediaCodecInfo.KeepCodecResult;
import com.google.android.exoplayer2.mediacodec.MediaCodecRenderer;
import com.google.android.exoplayer2.mediacodec.MediaCodecSelector;
import com.google.android.exoplayer2.mediacodec.MediaCodecUtil;
import com.google.android.exoplayer2.mediacodec.MediaCodecUtil.DecoderQueryException;
import com.google.android.exoplayer2.mediacodec.MediaFormatUtil;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.Log;
import com.google.android.exoplayer2.util.MimeTypes;
import com.google.android.exoplayer2.util.TraceUtil;
import com.google.android.exoplayer2.util.Util;
import com.google.android.exoplayer2.video.VideoRendererEventListener.EventDispatcher;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.List;
/**
* Decodes and renders video using {@link MediaCodec}.
*
* <p>This renderer accepts the following messages sent via {@link ExoPlayer#createMessage(Target)}
* on the playback thread:
*
* <ul>
* <li>Message with type {@link #MSG_SET_SURFACE} to set the output surface. The message payload
* should be the target {@link Surface}, or null.
* <li>Message with type {@link #MSG_SET_SCALING_MODE} to set the video scaling mode. The message
* payload should be one of the integer scaling modes in {@link VideoScalingMode}. Note that
* the scaling mode only applies if the {@link Surface} targeted by this renderer is owned by
* a {@link android.view.SurfaceView}.
* <li>Message with type {@link #MSG_SET_VIDEO_FRAME_METADATA_LISTENER} to set a listener for
* metadata associated with frames being rendered. The message payload should be the {@link
* VideoFrameMetadataListener}, or null.
* </ul>
*/
public class MediaCodecVideoRenderer extends MediaCodecRenderer {
private static final String TAG = "MediaCodecVideoRenderer";
private static final String KEY_CROP_LEFT = "crop-left";
private static final String KEY_CROP_RIGHT = "crop-right";
private static final String KEY_CROP_BOTTOM = "crop-bottom";
private static final String KEY_CROP_TOP = "crop-top";
// Long edge length in pixels for standard video formats, in decreasing in order.
private static final int[] STANDARD_LONG_EDGE_VIDEO_PX = new int[] {
1920, 1600, 1440, 1280, 960, 854, 640, 540, 480};
/**
* Scale factor for the initial maximum input size used to configure the codec in non-adaptive
* playbacks. See {@link #getCodecMaxValues(MediaCodecInfo, Format, Format[])}.
*/
private static final float INITIAL_FORMAT_MAX_INPUT_SIZE_SCALE_FACTOR = 1.5f;
/** Magic frame render timestamp that indicates the EOS in tunneling mode. */
private static final long TUNNELING_EOS_PRESENTATION_TIME_US = Long.MAX_VALUE;
private static boolean evaluatedDeviceNeedsSetOutputSurfaceWorkaround;
private static boolean deviceNeedsSetOutputSurfaceWorkaround;
private final Context context;
private final VideoFrameReleaseTimeHelper frameReleaseTimeHelper;
private final EventDispatcher eventDispatcher;
private final long allowedJoiningTimeMs;
private final int maxDroppedFramesToNotify;
private final boolean deviceNeedsNoPostProcessWorkaround;
private CodecMaxValues codecMaxValues;
private boolean codecNeedsSetOutputSurfaceWorkaround;
private boolean codecHandlesHdr10PlusOutOfBandMetadata;
@Nullable private Surface surface;
private float surfaceFrameRate;
@Nullable private Surface dummySurface;
private boolean haveReportedFirstFrameRenderedForCurrentSurface;
@VideoScalingMode private int scalingMode;
private boolean renderedFirstFrameAfterReset;
private boolean mayRenderFirstFrameAfterEnableIfNotStarted;
private boolean renderedFirstFrameAfterEnable;
private long initialPositionUs;
private long joiningDeadlineMs;
private long droppedFrameAccumulationStartTimeMs;
private int droppedFrames;
private int consecutiveDroppedFrameCount;
private int buffersInCodecCount;
private long lastRenderTimeUs;
private long totalVideoFrameProcessingOffsetUs;
private int videoFrameProcessingOffsetCount;
private int currentWidth;
private int currentHeight;
private int currentUnappliedRotationDegrees;
private float currentPixelWidthHeightRatio;
private float currentFrameRate;
private int reportedWidth;
private int reportedHeight;
private int reportedUnappliedRotationDegrees;
private float reportedPixelWidthHeightRatio;
private boolean tunneling;
private int tunnelingAudioSessionId;
/* package */ @Nullable OnFrameRenderedListenerV23 tunnelingOnFrameRenderedListener;
@Nullable private VideoFrameMetadataListener frameMetadataListener;
/**
* @param context A context.
* @param mediaCodecSelector A decoder selector.
*/
public MediaCodecVideoRenderer(Context context, MediaCodecSelector mediaCodecSelector) {
this(context, mediaCodecSelector, 0);
}
/**
* @param context A context.
* @param mediaCodecSelector A decoder selector.
* @param allowedJoiningTimeMs The maximum duration in milliseconds for which this video renderer
* can attempt to seamlessly join an ongoing playback.
*/
public MediaCodecVideoRenderer(Context context, MediaCodecSelector mediaCodecSelector,
long allowedJoiningTimeMs) {
this(
context,
mediaCodecSelector,
allowedJoiningTimeMs,
/* eventHandler= */ null,
/* eventListener= */ null,
/* maxDroppedFramesToNotify= */ -1);
}
/**
* @param context A context.
* @param mediaCodecSelector A decoder selector.
* @param allowedJoiningTimeMs The maximum duration in milliseconds for which this video renderer
* can attempt to seamlessly join an ongoing playback.
* @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
* null if delivery of events is not required.
* @param eventListener A listener of events. May be null if delivery of events is not required.
* @param maxDroppedFramesToNotify The maximum number of frames that can be dropped between
* invocations of {@link VideoRendererEventListener#onDroppedFrames(int, long)}.
*/
public MediaCodecVideoRenderer(
Context context,
MediaCodecSelector mediaCodecSelector,
long allowedJoiningTimeMs,
@Nullable Handler eventHandler,
@Nullable VideoRendererEventListener eventListener,
int maxDroppedFramesToNotify) {
this(
context,
mediaCodecSelector,
allowedJoiningTimeMs,
/* enableDecoderFallback= */ false,
eventHandler,
eventListener,
maxDroppedFramesToNotify);
}
/**
* @param context A context.
* @param mediaCodecSelector A decoder selector.
* @param allowedJoiningTimeMs The maximum duration in milliseconds for which this video renderer
* can attempt to seamlessly join an ongoing playback.
* @param enableDecoderFallback Whether to enable fallback to lower-priority decoders if decoder
* initialization fails. This may result in using a decoder that is slower/less efficient than
* the primary decoder.
* @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
* null if delivery of events is not required.
* @param eventListener A listener of events. May be null if delivery of events is not required.
* @param maxDroppedFramesToNotify The maximum number of frames that can be dropped between
* invocations of {@link VideoRendererEventListener#onDroppedFrames(int, long)}.
*/
public MediaCodecVideoRenderer(
Context context,
MediaCodecSelector mediaCodecSelector,
long allowedJoiningTimeMs,
boolean enableDecoderFallback,
@Nullable Handler eventHandler,
@Nullable VideoRendererEventListener eventListener,
int maxDroppedFramesToNotify) {
super(
C.TRACK_TYPE_VIDEO,
mediaCodecSelector,
enableDecoderFallback,
/* assumedMinimumCodecOperatingRate= */ 30);
this.allowedJoiningTimeMs = allowedJoiningTimeMs;
this.maxDroppedFramesToNotify = maxDroppedFramesToNotify;
this.context = context.getApplicationContext();
frameReleaseTimeHelper = new VideoFrameReleaseTimeHelper(this.context);
eventDispatcher = new EventDispatcher(eventHandler, eventListener);
deviceNeedsNoPostProcessWorkaround = deviceNeedsNoPostProcessWorkaround();
joiningDeadlineMs = C.TIME_UNSET;
currentWidth = Format.NO_VALUE;
currentHeight = Format.NO_VALUE;
currentPixelWidthHeightRatio = Format.NO_VALUE;
scalingMode = VIDEO_SCALING_MODE_DEFAULT;
clearReportedVideoSize();
}
@Override
public String getName() {
return TAG;
}
@Override
@Capabilities
protected int supportsFormat(MediaCodecSelector mediaCodecSelector, Format format)
throws DecoderQueryException {
String mimeType = format.sampleMimeType;
if (!MimeTypes.isVideo(mimeType)) {
return RendererCapabilities.create(FORMAT_UNSUPPORTED_TYPE);
}
@Nullable DrmInitData drmInitData = format.drmInitData;
// Assume encrypted content requires secure decoders.
boolean requiresSecureDecryption = drmInitData != null;
List<MediaCodecInfo> decoderInfos =
getDecoderInfos(
mediaCodecSelector,
format,
requiresSecureDecryption,
/* requiresTunnelingDecoder= */ false);
if (requiresSecureDecryption && decoderInfos.isEmpty()) {
// No secure decoders are available. Fall back to non-secure decoders.
decoderInfos =
getDecoderInfos(
mediaCodecSelector,
format,
/* requiresSecureDecoder= */ false,
/* requiresTunnelingDecoder= */ false);
}
if (decoderInfos.isEmpty()) {
return RendererCapabilities.create(FORMAT_UNSUPPORTED_SUBTYPE);
}
if (!supportsFormatDrm(format)) {
return RendererCapabilities.create(FORMAT_UNSUPPORTED_DRM);
}
// Check capabilities for the first decoder in the list, which takes priority.
MediaCodecInfo decoderInfo = decoderInfos.get(0);
boolean isFormatSupported = decoderInfo.isFormatSupported(format);
@AdaptiveSupport
int adaptiveSupport =
decoderInfo.isSeamlessAdaptationSupported(format)
? ADAPTIVE_SEAMLESS
: ADAPTIVE_NOT_SEAMLESS;
@TunnelingSupport int tunnelingSupport = TUNNELING_NOT_SUPPORTED;
if (isFormatSupported) {
List<MediaCodecInfo> tunnelingDecoderInfos =
getDecoderInfos(
mediaCodecSelector,
format,
requiresSecureDecryption,
/* requiresTunnelingDecoder= */ true);
if (!tunnelingDecoderInfos.isEmpty()) {
MediaCodecInfo tunnelingDecoderInfo = tunnelingDecoderInfos.get(0);
if (tunnelingDecoderInfo.isFormatSupported(format)
&& tunnelingDecoderInfo.isSeamlessAdaptationSupported(format)) {
tunnelingSupport = TUNNELING_SUPPORTED;
}
}
}
@FormatSupport
int formatSupport = isFormatSupported ? FORMAT_HANDLED : FORMAT_EXCEEDS_CAPABILITIES;
return RendererCapabilities.create(formatSupport, adaptiveSupport, tunnelingSupport);
}
@Override
protected List<MediaCodecInfo> getDecoderInfos(
MediaCodecSelector mediaCodecSelector, Format format, boolean requiresSecureDecoder)
throws DecoderQueryException {
return getDecoderInfos(mediaCodecSelector, format, requiresSecureDecoder, tunneling);
}
private static List<MediaCodecInfo> getDecoderInfos(
MediaCodecSelector mediaCodecSelector,
Format format,
boolean requiresSecureDecoder,
boolean requiresTunnelingDecoder)
throws DecoderQueryException {
@Nullable String mimeType = format.sampleMimeType;
if (mimeType == null) {
return Collections.emptyList();
}
List<MediaCodecInfo> decoderInfos =
mediaCodecSelector.getDecoderInfos(
mimeType, requiresSecureDecoder, requiresTunnelingDecoder);
decoderInfos = MediaCodecUtil.getDecoderInfosSortedByFormatSupport(decoderInfos, format);
if (MimeTypes.VIDEO_DOLBY_VISION.equals(mimeType)) {
// Fall back to H.264/AVC or H.265/HEVC for the relevant DV profiles.
@Nullable
Pair<Integer, Integer> codecProfileAndLevel = MediaCodecUtil.getCodecProfileAndLevel(format);
if (codecProfileAndLevel != null) {
int profile = codecProfileAndLevel.first;
if (profile == CodecProfileLevel.DolbyVisionProfileDvheDtr
|| profile == CodecProfileLevel.DolbyVisionProfileDvheSt) {
decoderInfos.addAll(
mediaCodecSelector.getDecoderInfos(
MimeTypes.VIDEO_H265, requiresSecureDecoder, requiresTunnelingDecoder));
} else if (profile == CodecProfileLevel.DolbyVisionProfileDvavSe) {
decoderInfos.addAll(
mediaCodecSelector.getDecoderInfos(
MimeTypes.VIDEO_H264, requiresSecureDecoder, requiresTunnelingDecoder));
}
}
}
return Collections.unmodifiableList(decoderInfos);
}
@Override
protected void onEnabled(boolean joining, boolean mayRenderStartOfStream)
throws ExoPlaybackException {
super.onEnabled(joining, mayRenderStartOfStream);
int oldTunnelingAudioSessionId = tunnelingAudioSessionId;
tunnelingAudioSessionId = getConfiguration().tunnelingAudioSessionId;
tunneling = tunnelingAudioSessionId != C.AUDIO_SESSION_ID_UNSET;
if (tunnelingAudioSessionId != oldTunnelingAudioSessionId) {
releaseCodec();
}
eventDispatcher.enabled(decoderCounters);
frameReleaseTimeHelper.enable();
mayRenderFirstFrameAfterEnableIfNotStarted = mayRenderStartOfStream;
renderedFirstFrameAfterEnable = false;
}
@Override
protected void onPositionReset(long positionUs, boolean joining) throws ExoPlaybackException {
super.onPositionReset(positionUs, joining);
clearRenderedFirstFrame();
initialPositionUs = C.TIME_UNSET;
consecutiveDroppedFrameCount = 0;
if (joining) {
setJoiningDeadlineMs();
} else {
joiningDeadlineMs = C.TIME_UNSET;
}
}
@Override
public boolean isReady() {
if (super.isReady()
&& (renderedFirstFrameAfterReset
|| (dummySurface != null && surface == dummySurface)
|| getCodec() == null
|| tunneling)) {
// Ready. If we were joining then we've now joined, so clear the joining deadline.
joiningDeadlineMs = C.TIME_UNSET;
return true;
} else if (joiningDeadlineMs == C.TIME_UNSET) {
// Not joining.
return false;
} else if (SystemClock.elapsedRealtime() < joiningDeadlineMs) {
// Joining and still within the joining deadline.
return true;
} else {
// The joining deadline has been exceeded. Give up and clear the deadline.
joiningDeadlineMs = C.TIME_UNSET;
return false;
}
}
@Override
protected void onStarted() {
super.onStarted();
droppedFrames = 0;
droppedFrameAccumulationStartTimeMs = SystemClock.elapsedRealtime();
lastRenderTimeUs = SystemClock.elapsedRealtime() * 1000;
totalVideoFrameProcessingOffsetUs = 0;
videoFrameProcessingOffsetCount = 0;
updateSurfaceFrameRate(/* isNewSurface= */ false);
}
@Override
protected void onStopped() {
joiningDeadlineMs = C.TIME_UNSET;
maybeNotifyDroppedFrames();
maybeNotifyVideoFrameProcessingOffset();
clearSurfaceFrameRate();
super.onStopped();
}
@Override
protected void onDisabled() {
clearReportedVideoSize();
clearRenderedFirstFrame();
haveReportedFirstFrameRenderedForCurrentSurface = false;
frameReleaseTimeHelper.disable();
tunnelingOnFrameRenderedListener = null;
try {
super.onDisabled();
} finally {
eventDispatcher.disabled(decoderCounters);
}
}
@Override
protected void onReset() {
try {
super.onReset();
} finally {
if (dummySurface != null) {
if (surface == dummySurface) {
surface = null;
}
dummySurface.release();
dummySurface = null;
}
}
}
@Override
public void handleMessage(int messageType, @Nullable Object message) throws ExoPlaybackException {
if (messageType == MSG_SET_SURFACE) {
setSurface((Surface) message);
} else if (messageType == MSG_SET_SCALING_MODE) {
scalingMode = (Integer) message;
MediaCodec codec = getCodec();
if (codec != null) {
codec.setVideoScalingMode(scalingMode);
}
} else if (messageType == MSG_SET_VIDEO_FRAME_METADATA_LISTENER) {
frameMetadataListener = (VideoFrameMetadataListener) message;
} else {
super.handleMessage(messageType, message);
}
}
private void setSurface(Surface surface) throws ExoPlaybackException {
if (surface == null) {
// Use a dummy surface if possible.
if (dummySurface != null) {
surface = dummySurface;
} else {
MediaCodecInfo codecInfo = getCodecInfo();
if (codecInfo != null && shouldUseDummySurface(codecInfo)) {
dummySurface = DummySurface.newInstanceV17(context, codecInfo.secure);
surface = dummySurface;
}
}
}
// We only need to update the codec if the surface has changed.
if (this.surface != surface) {
clearSurfaceFrameRate();
this.surface = surface;
haveReportedFirstFrameRenderedForCurrentSurface = false;
updateSurfaceFrameRate(/* isNewSurface= */ true);
@State int state = getState();
MediaCodec codec = getCodec();
if (codec != null) {
if (Util.SDK_INT >= 23 && surface != null && !codecNeedsSetOutputSurfaceWorkaround) {
setOutputSurfaceV23(codec, surface);
} else {
releaseCodec();
maybeInitCodecOrBypass();
}
}
if (surface != null && surface != dummySurface) {
// If we know the video size, report it again immediately.
maybeRenotifyVideoSizeChanged();
// We haven't rendered to the new surface yet.
clearRenderedFirstFrame();
if (state == STATE_STARTED) {
setJoiningDeadlineMs();
}
} else {
// The surface has been removed.
clearReportedVideoSize();
clearRenderedFirstFrame();
}
} else if (surface != null && surface != dummySurface) {
// The surface is set and unchanged. If we know the video size and/or have already rendered to
// the surface, report these again immediately.
maybeRenotifyVideoSizeChanged();
maybeRenotifyRenderedFirstFrame();
}
}
@Override
protected boolean shouldInitCodec(MediaCodecInfo codecInfo) {
return surface != null || shouldUseDummySurface(codecInfo);
}
@Override
protected boolean getCodecNeedsEosPropagation() {
// Since API 23, onFrameRenderedListener allows for detection of the renderer EOS.
return tunneling && Util.SDK_INT < 23;
}
@Override
protected void configureCodec(
MediaCodecInfo codecInfo,
MediaCodecAdapter codecAdapter,
Format format,
@Nullable MediaCrypto crypto,
float codecOperatingRate) {
String codecMimeType = codecInfo.codecMimeType;
codecMaxValues = getCodecMaxValues(codecInfo, format, getStreamFormats());
MediaFormat mediaFormat =
getMediaFormat(
format,
codecMimeType,
codecMaxValues,
codecOperatingRate,
deviceNeedsNoPostProcessWorkaround,
tunnelingAudioSessionId);
if (surface == null) {
if (!shouldUseDummySurface(codecInfo)) {
throw new IllegalStateException();
}
if (dummySurface == null) {
dummySurface = DummySurface.newInstanceV17(context, codecInfo.secure);
}
surface = dummySurface;
}
codecAdapter.configure(mediaFormat, surface, crypto, 0);
if (Util.SDK_INT >= 23 && tunneling) {
tunnelingOnFrameRenderedListener = new OnFrameRenderedListenerV23(codecAdapter.getCodec());
}
}
@Override
@KeepCodecResult
protected int canKeepCodec(
MediaCodec codec, MediaCodecInfo codecInfo, Format oldFormat, Format newFormat) {
if (newFormat.width > codecMaxValues.width
|| newFormat.height > codecMaxValues.height
|| getMaxInputSize(codecInfo, newFormat) > codecMaxValues.inputSize) {
return KEEP_CODEC_RESULT_NO;
}
return codecInfo.canKeepCodec(oldFormat, newFormat);
}
@CallSuper
@Override
protected void resetCodecStateForFlush() {
super.resetCodecStateForFlush();
buffersInCodecCount = 0;
}
@Override
public void setPlaybackSpeed(float playbackSpeed) throws ExoPlaybackException {
super.setPlaybackSpeed(playbackSpeed);
updateSurfaceFrameRate(/* isNewSurface= */ false);
}
@Override
protected float getCodecOperatingRateV23(
float playbackSpeed, Format format, Format[] streamFormats) {
// Use the highest known stream frame-rate up front, to avoid having to reconfigure the codec
// should an adaptive switch to that stream occur.
float maxFrameRate = -1;
for (Format streamFormat : streamFormats) {
float streamFrameRate = streamFormat.frameRate;
if (streamFrameRate != Format.NO_VALUE) {
maxFrameRate = max(maxFrameRate, streamFrameRate);
}
}
return maxFrameRate == -1 ? CODEC_OPERATING_RATE_UNSET : (maxFrameRate * playbackSpeed);
}
@Override
protected void onCodecInitialized(String name, long initializedTimestampMs,
long initializationDurationMs) {
eventDispatcher.decoderInitialized(name, initializedTimestampMs, initializationDurationMs);
codecNeedsSetOutputSurfaceWorkaround = codecNeedsSetOutputSurfaceWorkaround(name);
codecHandlesHdr10PlusOutOfBandMetadata =
Assertions.checkNotNull(getCodecInfo()).isHdr10PlusOutOfBandMetadataSupported();
}
@Override
protected void onCodecReleased(String name) {
eventDispatcher.decoderReleased(name);
}
@Override
protected void onInputFormatChanged(FormatHolder formatHolder) throws ExoPlaybackException {
super.onInputFormatChanged(formatHolder);
eventDispatcher.inputFormatChanged(formatHolder.format);
}
/**
* Called immediately before an input buffer is queued into the codec.
*
* <p>In tunneling mode for pre Marshmallow, the buffer is treated as if immediately output.
*
* @param buffer The buffer to be queued.
* @throws ExoPlaybackException Thrown if an error occurs handling the input buffer.
*/
@CallSuper
@Override
protected void onQueueInputBuffer(DecoderInputBuffer buffer) throws ExoPlaybackException {
// In tunneling mode the device may do frame rate conversion, so in general we can't keep track
// of the number of buffers in the codec.
if (!tunneling) {
buffersInCodecCount++;
}
if (Util.SDK_INT < 23 && tunneling) {
// In tunneled mode before API 23 we don't have a way to know when the buffer is output, so
// treat it as if it were output immediately.
onProcessedTunneledBuffer(buffer.timeUs);
}
}
@Override
protected void onOutputFormatChanged(Format format, @Nullable MediaFormat mediaFormat) {
@Nullable MediaCodec codec = getCodec();
if (codec != null) {
// Must be applied each time the output format changes.
codec.setVideoScalingMode(scalingMode);
}
if (tunneling) {
currentWidth = format.width;
currentHeight = format.height;
} else {
Assertions.checkNotNull(mediaFormat);
boolean hasCrop =
mediaFormat.containsKey(KEY_CROP_RIGHT)
&& mediaFormat.containsKey(KEY_CROP_LEFT)
&& mediaFormat.containsKey(KEY_CROP_BOTTOM)
&& mediaFormat.containsKey(KEY_CROP_TOP);
currentWidth =
hasCrop
? mediaFormat.getInteger(KEY_CROP_RIGHT) - mediaFormat.getInteger(KEY_CROP_LEFT) + 1
: mediaFormat.getInteger(MediaFormat.KEY_WIDTH);
currentHeight =
hasCrop
? mediaFormat.getInteger(KEY_CROP_BOTTOM) - mediaFormat.getInteger(KEY_CROP_TOP) + 1
: mediaFormat.getInteger(MediaFormat.KEY_HEIGHT);
}
currentPixelWidthHeightRatio = format.pixelWidthHeightRatio;
if (Util.SDK_INT >= 21) {
// On API level 21 and above the decoder applies the rotation when rendering to the surface.
// Hence currentUnappliedRotation should always be 0. For 90 and 270 degree rotations, we need
// to flip the width, height and pixel aspect ratio to reflect the rotation that was applied.
if (format.rotationDegrees == 90 || format.rotationDegrees == 270) {
int rotatedHeight = currentWidth;
currentWidth = currentHeight;
currentHeight = rotatedHeight;
currentPixelWidthHeightRatio = 1 / currentPixelWidthHeightRatio;
}
} else {
// On API level 20 and below the decoder does not apply the rotation.
currentUnappliedRotationDegrees = format.rotationDegrees;
}
currentFrameRate = format.frameRate;
updateSurfaceFrameRate(/* isNewSurface= */ false);
}
@Override
@TargetApi(29) // codecHandlesHdr10PlusOutOfBandMetadata is false if Util.SDK_INT < 29
protected void handleInputBufferSupplementalData(DecoderInputBuffer buffer)
throws ExoPlaybackException {
if (!codecHandlesHdr10PlusOutOfBandMetadata) {
return;
}
ByteBuffer data = Assertions.checkNotNull(buffer.supplementalData);
if (data.remaining() >= 7) {
// Check for HDR10+ out-of-band metadata. See User_data_registered_itu_t_t35 in ST 2094-40.
byte ituTT35CountryCode = data.get();
int ituTT35TerminalProviderCode = data.getShort();
int ituTT35TerminalProviderOrientedCode = data.getShort();
byte applicationIdentifier = data.get();
byte applicationVersion = data.get();
data.position(0);
if (ituTT35CountryCode == (byte) 0xB5
&& ituTT35TerminalProviderCode == 0x003C
&& ituTT35TerminalProviderOrientedCode == 0x0001
&& applicationIdentifier == 4
&& applicationVersion == 0) {
// The metadata size may vary so allocate a new array every time. This is not too
// inefficient because the metadata is only a few tens of bytes.
byte[] hdr10PlusInfo = new byte[data.remaining()];
data.get(hdr10PlusInfo);
data.position(0);
setHdr10PlusInfoV29(getCodec(), hdr10PlusInfo);
}
}
}
@Override
protected boolean processOutputBuffer(
long positionUs,
long elapsedRealtimeUs,
@Nullable MediaCodec codec,
@Nullable ByteBuffer buffer,
int bufferIndex,
int bufferFlags,
int sampleCount,
long bufferPresentationTimeUs,
boolean isDecodeOnlyBuffer,
boolean isLastBuffer,
Format format)
throws ExoPlaybackException {
Assertions.checkNotNull(codec); // Can not render video without codec
if (initialPositionUs == C.TIME_UNSET) {
initialPositionUs = positionUs;
}
long outputStreamOffsetUs = getOutputStreamOffsetUs();
long presentationTimeUs = bufferPresentationTimeUs - outputStreamOffsetUs;
if (isDecodeOnlyBuffer && !isLastBuffer) {
skipOutputBuffer(codec, bufferIndex, presentationTimeUs);
return true;
}
long earlyUs = bufferPresentationTimeUs - positionUs;
if (surface == dummySurface) {
// Skip frames in sync with playback, so we'll be at the right frame if the mode changes.
if (isBufferLate(earlyUs)) {
skipOutputBuffer(codec, bufferIndex, presentationTimeUs);
updateVideoFrameProcessingOffsetCounters(earlyUs);
return true;
}
return false;
}
long elapsedRealtimeNowUs = SystemClock.elapsedRealtime() * 1000;
long elapsedSinceLastRenderUs = elapsedRealtimeNowUs - lastRenderTimeUs;
boolean isStarted = getState() == STATE_STARTED;
boolean shouldRenderFirstFrame =
!renderedFirstFrameAfterEnable
? (isStarted || mayRenderFirstFrameAfterEnableIfNotStarted)
: !renderedFirstFrameAfterReset;
// Don't force output until we joined and the position reached the current stream.
boolean forceRenderOutputBuffer =
joiningDeadlineMs == C.TIME_UNSET
&& positionUs >= outputStreamOffsetUs
&& (shouldRenderFirstFrame
|| (isStarted && shouldForceRenderOutputBuffer(earlyUs, elapsedSinceLastRenderUs)));
if (forceRenderOutputBuffer) {
long releaseTimeNs = System.nanoTime();
notifyFrameMetadataListener(presentationTimeUs, releaseTimeNs, format);
if (Util.SDK_INT >= 21) {
renderOutputBufferV21(codec, bufferIndex, presentationTimeUs, releaseTimeNs);
} else {
renderOutputBuffer(codec, bufferIndex, presentationTimeUs);
}
updateVideoFrameProcessingOffsetCounters(earlyUs);
return true;
}
if (!isStarted || positionUs == initialPositionUs) {
return false;
}
// Fine-grained adjustment of earlyUs based on the elapsed time since the start of the current
// iteration of the rendering loop.
long elapsedSinceStartOfLoopUs = elapsedRealtimeNowUs - elapsedRealtimeUs;
earlyUs -= elapsedSinceStartOfLoopUs;
// Compute the buffer's desired release time in nanoseconds.
long systemTimeNs = System.nanoTime();
long unadjustedFrameReleaseTimeNs = systemTimeNs + (earlyUs * 1000);
// Apply a timestamp adjustment, if there is one.
long adjustedReleaseTimeNs = frameReleaseTimeHelper.adjustReleaseTime(
bufferPresentationTimeUs, unadjustedFrameReleaseTimeNs);
earlyUs = (adjustedReleaseTimeNs - systemTimeNs) / 1000;
boolean treatDroppedBuffersAsSkipped = joiningDeadlineMs != C.TIME_UNSET;
if (shouldDropBuffersToKeyframe(earlyUs, elapsedRealtimeUs, isLastBuffer)
&& maybeDropBuffersToKeyframe(
codec, bufferIndex, presentationTimeUs, positionUs, treatDroppedBuffersAsSkipped)) {
return false;
} else if (shouldDropOutputBuffer(earlyUs, elapsedRealtimeUs, isLastBuffer)) {
if (treatDroppedBuffersAsSkipped) {
skipOutputBuffer(codec, bufferIndex, presentationTimeUs);
} else {
dropOutputBuffer(codec, bufferIndex, presentationTimeUs);
}
updateVideoFrameProcessingOffsetCounters(earlyUs);
return true;
}
if (Util.SDK_INT >= 21) {
// Let the underlying framework time the release.
if (earlyUs < 50000) {
notifyFrameMetadataListener(presentationTimeUs, adjustedReleaseTimeNs, format);
renderOutputBufferV21(codec, bufferIndex, presentationTimeUs, adjustedReleaseTimeNs);
updateVideoFrameProcessingOffsetCounters(earlyUs);
return true;
}
} else {
// We need to time the release ourselves.
if (earlyUs < 30000) {
if (earlyUs > 11000) {
// We're a little too early to render the frame. Sleep until the frame can be rendered.
// Note: The 11ms threshold was chosen fairly arbitrarily.
try {
// Subtracting 10000 rather than 11000 ensures the sleep time will be at least 1ms.
Thread.sleep((earlyUs - 10000) / 1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
notifyFrameMetadataListener(presentationTimeUs, adjustedReleaseTimeNs, format);
renderOutputBuffer(codec, bufferIndex, presentationTimeUs);
updateVideoFrameProcessingOffsetCounters(earlyUs);
return true;
}
}
// We're either not playing, or it's not time to render the frame yet.
return false;
}
private void notifyFrameMetadataListener(
long presentationTimeUs, long releaseTimeNs, Format format) {
if (frameMetadataListener != null) {
frameMetadataListener.onVideoFrameAboutToBeRendered(
presentationTimeUs, releaseTimeNs, format, getCodecOutputMediaFormat());
}
}
/** Called when a buffer was processed in tunneling mode. */
protected void onProcessedTunneledBuffer(long presentationTimeUs) throws ExoPlaybackException {
updateOutputFormatForTime(presentationTimeUs);
maybeNotifyVideoSizeChanged();
decoderCounters.renderedOutputBufferCount++;
maybeNotifyRenderedFirstFrame();
onProcessedOutputBuffer(presentationTimeUs);
}
/** Called when a output EOS was received in tunneling mode. */
private void onProcessedTunneledEndOfStream() {
setPendingOutputEndOfStream();
}
@CallSuper
@Override
protected void onProcessedOutputBuffer(long presentationTimeUs) {
super.onProcessedOutputBuffer(presentationTimeUs);
if (!tunneling) {
buffersInCodecCount--;
}
}
@Override
protected void onProcessedStreamChange() {
super.onProcessedStreamChange();
clearRenderedFirstFrame();
}
/**
* Returns whether the buffer being processed should be dropped.
*
* @param earlyUs The time until the buffer should be presented in microseconds. A negative value
* indicates that the buffer is late.
* @param elapsedRealtimeUs {@link android.os.SystemClock#elapsedRealtime()} in microseconds,
* measured at the start of the current iteration of the rendering loop.
* @param isLastBuffer Whether the buffer is the last buffer in the current stream.
*/
protected boolean shouldDropOutputBuffer(
long earlyUs, long elapsedRealtimeUs, boolean isLastBuffer) {
return isBufferLate(earlyUs) && !isLastBuffer;
}
/**
* Returns whether to drop all buffers from the buffer being processed to the keyframe at or after
* the current playback position, if possible.
*
* @param earlyUs The time until the current buffer should be presented in microseconds. A
* negative value indicates that the buffer is late.
* @param elapsedRealtimeUs {@link android.os.SystemClock#elapsedRealtime()} in microseconds,
* measured at the start of the current iteration of the rendering loop.
* @param isLastBuffer Whether the buffer is the last buffer in the current stream.
*/
protected boolean shouldDropBuffersToKeyframe(
long earlyUs, long elapsedRealtimeUs, boolean isLastBuffer) {
return isBufferVeryLate(earlyUs) && !isLastBuffer;
}
/**
* Returns whether to force rendering an output buffer.
*
* @param earlyUs The time until the current buffer should be presented in microseconds. A
* negative value indicates that the buffer is late.
* @param elapsedSinceLastRenderUs The elapsed time since the last output buffer was rendered, in
* microseconds.
* @return Returns whether to force rendering an output buffer.
*/
protected boolean shouldForceRenderOutputBuffer(long earlyUs, long elapsedSinceLastRenderUs) {
// Force render late buffers every 100ms to avoid frozen video effect.
return isBufferLate(earlyUs) && elapsedSinceLastRenderUs > 100000;
}
/**
* Skips the output buffer with the specified index.
*
* @param codec The codec that owns the output buffer.
* @param index The index of the output buffer to skip.
* @param presentationTimeUs The presentation time of the output buffer, in microseconds.
*/
protected void skipOutputBuffer(MediaCodec codec, int index, long presentationTimeUs) {
TraceUtil.beginSection("skipVideoBuffer");
codec.releaseOutputBuffer(index, false);
TraceUtil.endSection();
decoderCounters.skippedOutputBufferCount++;
}
/**
* Drops the output buffer with the specified index.
*
* @param codec The codec that owns the output buffer.
* @param index The index of the output buffer to drop.
* @param presentationTimeUs The presentation time of the output buffer, in microseconds.
*/
protected void dropOutputBuffer(MediaCodec codec, int index, long presentationTimeUs) {
TraceUtil.beginSection("dropVideoBuffer");
codec.releaseOutputBuffer(index, false);
TraceUtil.endSection();
updateDroppedBufferCounters(1);
}
/**
* Drops frames from the current output buffer to the next keyframe at or before the playback
* position. If no such keyframe exists, as the playback position is inside the same group of
* pictures as the buffer being processed, returns {@code false}. Returns {@code true} otherwise.
*
* @param codec The codec that owns the output buffer.
* @param index The index of the output buffer to drop.
* @param presentationTimeUs The presentation time of the output buffer, in microseconds.
* @param positionUs The current playback position, in microseconds.
* @param treatDroppedBuffersAsSkipped Whether dropped buffers should be treated as intentionally
* skipped.
* @return Whether any buffers were dropped.
* @throws ExoPlaybackException If an error occurs flushing the codec.
*/
protected boolean maybeDropBuffersToKeyframe(
MediaCodec codec,
int index,
long presentationTimeUs,
long positionUs,
boolean treatDroppedBuffersAsSkipped)
throws ExoPlaybackException {
int droppedSourceBufferCount = skipSource(positionUs);
if (droppedSourceBufferCount == 0) {
return false;
}
decoderCounters.droppedToKeyframeCount++;
// We dropped some buffers to catch up, so update the decoder counters and flush the codec,
// which releases all pending buffers buffers including the current output buffer.
int totalDroppedBufferCount = buffersInCodecCount + droppedSourceBufferCount;
if (treatDroppedBuffersAsSkipped) {
decoderCounters.skippedOutputBufferCount += totalDroppedBufferCount;
} else {
updateDroppedBufferCounters(totalDroppedBufferCount);
}
flushOrReinitializeCodec();
return true;
}
/**
* Updates local counters and {@link DecoderCounters} to reflect that {@code droppedBufferCount}
* additional buffers were dropped.
*
* @param droppedBufferCount The number of additional dropped buffers.
*/
protected void updateDroppedBufferCounters(int droppedBufferCount) {
decoderCounters.droppedBufferCount += droppedBufferCount;
droppedFrames += droppedBufferCount;
consecutiveDroppedFrameCount += droppedBufferCount;
decoderCounters.maxConsecutiveDroppedBufferCount =
max(consecutiveDroppedFrameCount, decoderCounters.maxConsecutiveDroppedBufferCount);
if (maxDroppedFramesToNotify > 0 && droppedFrames >= maxDroppedFramesToNotify) {
maybeNotifyDroppedFrames();
}
}
/**
* Updates local counters and {@link DecoderCounters} with a new video frame processing offset.
*
* @param processingOffsetUs The video frame processing offset.
*/
protected void updateVideoFrameProcessingOffsetCounters(long processingOffsetUs) {
decoderCounters.addVideoFrameProcessingOffset(processingOffsetUs);
totalVideoFrameProcessingOffsetUs += processingOffsetUs;
videoFrameProcessingOffsetCount++;
}
/**
* Renders the output buffer with the specified index. This method is only called if the platform
* API version of the device is less than 21.
*
* @param codec The codec that owns the output buffer.
* @param index The index of the output buffer to drop.
* @param presentationTimeUs The presentation time of the output buffer, in microseconds.
*/
protected void renderOutputBuffer(MediaCodec codec, int index, long presentationTimeUs) {
maybeNotifyVideoSizeChanged();
TraceUtil.beginSection("releaseOutputBuffer");
codec.releaseOutputBuffer(index, true);
TraceUtil.endSection();
lastRenderTimeUs = SystemClock.elapsedRealtime() * 1000;
decoderCounters.renderedOutputBufferCount++;
consecutiveDroppedFrameCount = 0;
maybeNotifyRenderedFirstFrame();
}
/**
* Renders the output buffer with the specified index. This method is only called if the platform
* API version of the device is 21 or later.
*
* @param codec The codec that owns the output buffer.
* @param index The index of the output buffer to drop.
* @param presentationTimeUs The presentation time of the output buffer, in microseconds.
* @param releaseTimeNs The wallclock time at which the frame should be displayed, in nanoseconds.
*/
@RequiresApi(21)
protected void renderOutputBufferV21(
MediaCodec codec, int index, long presentationTimeUs, long releaseTimeNs) {
maybeNotifyVideoSizeChanged();
TraceUtil.beginSection("releaseOutputBuffer");
codec.releaseOutputBuffer(index, releaseTimeNs);
TraceUtil.endSection();
lastRenderTimeUs = SystemClock.elapsedRealtime() * 1000;
decoderCounters.renderedOutputBufferCount++;
consecutiveDroppedFrameCount = 0;
maybeNotifyRenderedFirstFrame();
}
/**
* Updates the frame-rate of the current {@link #surface} based on the renderer operating rate,
* frame-rate of the content, and whether the renderer is started.
*
* @param isNewSurface Whether the current {@link #surface} is new.
*/
private void updateSurfaceFrameRate(boolean isNewSurface) {
if (Util.SDK_INT < 30 || surface == null || surface == dummySurface) {
return;
}
boolean shouldSetFrameRate = getState() == STATE_STARTED && currentFrameRate != Format.NO_VALUE;
float surfaceFrameRate = shouldSetFrameRate ? currentFrameRate * getPlaybackSpeed() : 0;
// We always set the frame-rate if we have a new surface, since we have no way of knowing what
// it might have been set to previously.
if (this.surfaceFrameRate == surfaceFrameRate && !isNewSurface) {
return;
}
this.surfaceFrameRate = surfaceFrameRate;
setSurfaceFrameRateV30(surface, surfaceFrameRate);
}
/** Clears the frame-rate of the current {@link #surface}. */
private void clearSurfaceFrameRate() {
if (Util.SDK_INT < 30 || surface == null || surface == dummySurface || surfaceFrameRate == 0) {
return;
}
surfaceFrameRate = 0;
setSurfaceFrameRateV30(surface, /* frameRate= */ 0);
}
@RequiresApi(30)
private static void setSurfaceFrameRateV30(Surface surface, float frameRate) {
int compatibility =
frameRate == 0
? Surface.FRAME_RATE_COMPATIBILITY_DEFAULT
: Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE;
try {
surface.setFrameRate(frameRate, compatibility);
} catch (IllegalStateException e) {
Log.e(TAG, "Failed to call Surface.setFrameRate", e);
}
}
private boolean shouldUseDummySurface(MediaCodecInfo codecInfo) {
return Util.SDK_INT >= 23
&& !tunneling
&& !codecNeedsSetOutputSurfaceWorkaround(codecInfo.name)
&& (!codecInfo.secure || DummySurface.isSecureSupported(context));
}
private void setJoiningDeadlineMs() {
joiningDeadlineMs = allowedJoiningTimeMs > 0
? (SystemClock.elapsedRealtime() + allowedJoiningTimeMs) : C.TIME_UNSET;
}
private void clearRenderedFirstFrame() {
renderedFirstFrameAfterReset = false;
// The first frame notification is triggered by renderOutputBuffer or renderOutputBufferV21 for
// non-tunneled playback, onQueueInputBuffer for tunneled playback prior to API level 23, and
// OnFrameRenderedListenerV23.onFrameRenderedListener for tunneled playback on API level 23 and
// above.
if (Util.SDK_INT >= 23 && tunneling) {
MediaCodec codec = getCodec();
// If codec is null then the listener will be instantiated in configureCodec.
if (codec != null) {
tunnelingOnFrameRenderedListener = new OnFrameRenderedListenerV23(codec);
}
}
}
/* package */ void maybeNotifyRenderedFirstFrame() {
renderedFirstFrameAfterEnable = true;
if (!renderedFirstFrameAfterReset) {
renderedFirstFrameAfterReset = true;
eventDispatcher.renderedFirstFrame(surface);
haveReportedFirstFrameRenderedForCurrentSurface = true;
}
}
private void maybeRenotifyRenderedFirstFrame() {
if (haveReportedFirstFrameRenderedForCurrentSurface) {
eventDispatcher.renderedFirstFrame(surface);
}
}
private void clearReportedVideoSize() {
reportedWidth = Format.NO_VALUE;
reportedHeight = Format.NO_VALUE;
reportedPixelWidthHeightRatio = Format.NO_VALUE;
reportedUnappliedRotationDegrees = Format.NO_VALUE;
}
private void maybeNotifyVideoSizeChanged() {
if ((currentWidth != Format.NO_VALUE || currentHeight != Format.NO_VALUE)
&& (reportedWidth != currentWidth || reportedHeight != currentHeight
|| reportedUnappliedRotationDegrees != currentUnappliedRotationDegrees
|| reportedPixelWidthHeightRatio != currentPixelWidthHeightRatio)) {
eventDispatcher.videoSizeChanged(currentWidth, currentHeight, currentUnappliedRotationDegrees,
currentPixelWidthHeightRatio);
reportedWidth = currentWidth;
reportedHeight = currentHeight;
reportedUnappliedRotationDegrees = currentUnappliedRotationDegrees;
reportedPixelWidthHeightRatio = currentPixelWidthHeightRatio;
}
}
private void maybeRenotifyVideoSizeChanged() {
if (reportedWidth != Format.NO_VALUE || reportedHeight != Format.NO_VALUE) {
eventDispatcher.videoSizeChanged(reportedWidth, reportedHeight,
reportedUnappliedRotationDegrees, reportedPixelWidthHeightRatio);
}
}
private void maybeNotifyDroppedFrames() {
if (droppedFrames > 0) {
long now = SystemClock.elapsedRealtime();
long elapsedMs = now - droppedFrameAccumulationStartTimeMs;
eventDispatcher.droppedFrames(droppedFrames, elapsedMs);
droppedFrames = 0;
droppedFrameAccumulationStartTimeMs = now;
}
}
private void maybeNotifyVideoFrameProcessingOffset() {
if (videoFrameProcessingOffsetCount != 0) {
eventDispatcher.reportVideoFrameProcessingOffset(
totalVideoFrameProcessingOffsetUs, videoFrameProcessingOffsetCount);
totalVideoFrameProcessingOffsetUs = 0;
videoFrameProcessingOffsetCount = 0;
}
}
private static boolean isBufferLate(long earlyUs) {
// Class a buffer as late if it should have been presented more than 30 ms ago.
return earlyUs < -30000;
}
private static boolean isBufferVeryLate(long earlyUs) {
// Class a buffer as very late if it should have been presented more than 500 ms ago.
return earlyUs < -500000;
}
@RequiresApi(29)
private static void setHdr10PlusInfoV29(MediaCodec codec, byte[] hdr10PlusInfo) {
Bundle codecParameters = new Bundle();
codecParameters.putByteArray(MediaCodec.PARAMETER_KEY_HDR10_PLUS_INFO, hdr10PlusInfo);
codec.setParameters(codecParameters);
}
@RequiresApi(23)
protected void setOutputSurfaceV23(MediaCodec codec, Surface surface) {
codec.setOutputSurface(surface);
}
@RequiresApi(21)
private static void configureTunnelingV21(MediaFormat mediaFormat, int tunnelingAudioSessionId) {
mediaFormat.setFeatureEnabled(CodecCapabilities.FEATURE_TunneledPlayback, true);
mediaFormat.setInteger(MediaFormat.KEY_AUDIO_SESSION_ID, tunnelingAudioSessionId);
}
/**
* Returns the framework {@link MediaFormat} that should be used to configure the decoder.
*
* @param format The {@link Format} of media.
* @param codecMimeType The MIME type handled by the codec.
* @param codecMaxValues Codec max values that should be used when configuring the decoder.
* @param codecOperatingRate The codec operating rate, or {@link #CODEC_OPERATING_RATE_UNSET} if
* no codec operating rate should be set.
* @param deviceNeedsNoPostProcessWorkaround Whether the device is known to do post processing by
* default that isn't compatible with ExoPlayer.
* @param tunnelingAudioSessionId The audio session id to use for tunneling, or {@link
* C#AUDIO_SESSION_ID_UNSET} if tunneling should not be enabled.
* @return The framework {@link MediaFormat} that should be used to configure the decoder.
*/
@SuppressLint("InlinedApi")
@TargetApi(21) // tunnelingAudioSessionId is unset if Util.SDK_INT < 21
protected MediaFormat getMediaFormat(
Format format,
String codecMimeType,
CodecMaxValues codecMaxValues,
float codecOperatingRate,
boolean deviceNeedsNoPostProcessWorkaround,
int tunnelingAudioSessionId) {
MediaFormat mediaFormat = new MediaFormat();
// Set format parameters that should always be set.
mediaFormat.setString(MediaFormat.KEY_MIME, codecMimeType);
mediaFormat.setInteger(MediaFormat.KEY_WIDTH, format.width);
mediaFormat.setInteger(MediaFormat.KEY_HEIGHT, format.height);
MediaFormatUtil.setCsdBuffers(mediaFormat, format.initializationData);
// Set format parameters that may be unset.
MediaFormatUtil.maybeSetFloat(mediaFormat, MediaFormat.KEY_FRAME_RATE, format.frameRate);
MediaFormatUtil.maybeSetInteger(mediaFormat, MediaFormat.KEY_ROTATION, format.rotationDegrees);
MediaFormatUtil.maybeSetColorInfo(mediaFormat, format.colorInfo);
if (MimeTypes.VIDEO_DOLBY_VISION.equals(format.sampleMimeType)) {
// Some phones require the profile to be set on the codec.
// See https://github.com/google/ExoPlayer/pull/5438.
Pair<Integer, Integer> codecProfileAndLevel = MediaCodecUtil.getCodecProfileAndLevel(format);
if (codecProfileAndLevel != null) {
MediaFormatUtil.maybeSetInteger(
mediaFormat, MediaFormat.KEY_PROFILE, codecProfileAndLevel.first);
}
}
// Set codec max values.
mediaFormat.setInteger(MediaFormat.KEY_MAX_WIDTH, codecMaxValues.width);
mediaFormat.setInteger(MediaFormat.KEY_MAX_HEIGHT, codecMaxValues.height);
MediaFormatUtil.maybeSetInteger(
mediaFormat, MediaFormat.KEY_MAX_INPUT_SIZE, codecMaxValues.inputSize);
// Set codec configuration values.
if (Util.SDK_INT >= 23) {
mediaFormat.setInteger(MediaFormat.KEY_PRIORITY, 0 /* realtime priority */);
if (codecOperatingRate != CODEC_OPERATING_RATE_UNSET) {
mediaFormat.setFloat(MediaFormat.KEY_OPERATING_RATE, codecOperatingRate);
}
}
if (deviceNeedsNoPostProcessWorkaround) {
mediaFormat.setInteger("no-post-process", 1);
mediaFormat.setInteger("auto-frc", 0);
}
if (tunnelingAudioSessionId != C.AUDIO_SESSION_ID_UNSET) {
configureTunnelingV21(mediaFormat, tunnelingAudioSessionId);
}
return mediaFormat;
}
/**
* Returns {@link CodecMaxValues} suitable for configuring a codec for {@code format} in a way
* that will allow possible adaptation to other compatible formats in {@code streamFormats}.
*
* @param codecInfo Information about the {@link MediaCodec} being configured.
* @param format The {@link Format} for which the codec is being configured.
* @param streamFormats The possible stream formats.
* @return Suitable {@link CodecMaxValues}.
*/
protected CodecMaxValues getCodecMaxValues(
MediaCodecInfo codecInfo, Format format, Format[] streamFormats) {
int maxWidth = format.width;
int maxHeight = format.height;
int maxInputSize = getMaxInputSize(codecInfo, format);
if (streamFormats.length == 1) {
// The single entry in streamFormats must correspond to the format for which the codec is
// being configured.
if (maxInputSize != Format.NO_VALUE) {
int codecMaxInputSize =
getCodecMaxInputSize(codecInfo, format.sampleMimeType, format.width, format.height);
if (codecMaxInputSize != Format.NO_VALUE) {
// Scale up the initial video decoder maximum input size so playlist item transitions with
// small increases in maximum sample size don't require reinitialization. This only makes
// a difference if the exact maximum sample sizes are known from the container.
int scaledMaxInputSize =
(int) (maxInputSize * INITIAL_FORMAT_MAX_INPUT_SIZE_SCALE_FACTOR);
// Avoid exceeding the maximum expected for the codec.
maxInputSize = min(scaledMaxInputSize, codecMaxInputSize);
}
}
return new CodecMaxValues(maxWidth, maxHeight, maxInputSize);
}
boolean haveUnknownDimensions = false;
for (Format streamFormat : streamFormats) {
if (format.colorInfo != null && streamFormat.colorInfo == null) {
// streamFormat likely has incomplete color information. Copy the complete color information
// from format to avoid codec re-use being ruled out for only this reason.
streamFormat = streamFormat.buildUpon().setColorInfo(format.colorInfo).build();
}
if (codecInfo.canKeepCodec(format, streamFormat) != KEEP_CODEC_RESULT_NO) {
haveUnknownDimensions |=
(streamFormat.width == Format.NO_VALUE || streamFormat.height == Format.NO_VALUE);
maxWidth = max(maxWidth, streamFormat.width);
maxHeight = max(maxHeight, streamFormat.height);
maxInputSize = max(maxInputSize, getMaxInputSize(codecInfo, streamFormat));
}
}
if (haveUnknownDimensions) {
Log.w(TAG, "Resolutions unknown. Codec max resolution: " + maxWidth + "x" + maxHeight);
Point codecMaxSize = getCodecMaxSize(codecInfo, format);
if (codecMaxSize != null) {
maxWidth = max(maxWidth, codecMaxSize.x);
maxHeight = max(maxHeight, codecMaxSize.y);
maxInputSize =
max(
maxInputSize,
getCodecMaxInputSize(codecInfo, format.sampleMimeType, maxWidth, maxHeight));
Log.w(TAG, "Codec max resolution adjusted to: " + maxWidth + "x" + maxHeight);
}
}
return new CodecMaxValues(maxWidth, maxHeight, maxInputSize);
}
@Override
protected MediaCodecDecoderException createDecoderException(
Throwable cause, @Nullable MediaCodecInfo codecInfo) {
return new MediaCodecVideoDecoderException(cause, codecInfo, surface);
}
/**
* Returns a maximum video size to use when configuring a codec for {@code format} in a way that
* will allow possible adaptation to other compatible formats that are expected to have the same
* aspect ratio, but whose sizes are unknown.
*
* @param codecInfo Information about the {@link MediaCodec} being configured.
* @param format The {@link Format} for which the codec is being configured.
* @return The maximum video size to use, or null if the size of {@code format} should be used.
*/
private static Point getCodecMaxSize(MediaCodecInfo codecInfo, Format format) {
boolean isVerticalVideo = format.height > format.width;
int formatLongEdgePx = isVerticalVideo ? format.height : format.width;
int formatShortEdgePx = isVerticalVideo ? format.width : format.height;
float aspectRatio = (float) formatShortEdgePx / formatLongEdgePx;
for (int longEdgePx : STANDARD_LONG_EDGE_VIDEO_PX) {
int shortEdgePx = (int) (longEdgePx * aspectRatio);
if (longEdgePx <= formatLongEdgePx || shortEdgePx <= formatShortEdgePx) {
// Don't return a size not larger than the format for which the codec is being configured.
return null;
} else if (Util.SDK_INT >= 21) {
Point alignedSize = codecInfo.alignVideoSizeV21(isVerticalVideo ? shortEdgePx : longEdgePx,
isVerticalVideo ? longEdgePx : shortEdgePx);
float frameRate = format.frameRate;
if (codecInfo.isVideoSizeAndRateSupportedV21(alignedSize.x, alignedSize.y, frameRate)) {
return alignedSize;
}
} else {
try {
// Conservatively assume the codec requires 16px width and height alignment.
longEdgePx = Util.ceilDivide(longEdgePx, 16) * 16;
shortEdgePx = Util.ceilDivide(shortEdgePx, 16) * 16;
if (longEdgePx * shortEdgePx <= MediaCodecUtil.maxH264DecodableFrameSize()) {
return new Point(
isVerticalVideo ? shortEdgePx : longEdgePx,
isVerticalVideo ? longEdgePx : shortEdgePx);
}
} catch (DecoderQueryException e) {
// We tried our best. Give up!
return null;
}
}
}
return null;
}
/**
* Returns a maximum input buffer size for a given {@link MediaCodec} and {@link Format}.
*
* @param codecInfo Information about the {@link MediaCodec} being configured.
* @param format The format.
* @return A maximum input buffer size in bytes, or {@link Format#NO_VALUE} if a maximum could not
* be determined.
*/
protected static int getMaxInputSize(MediaCodecInfo codecInfo, Format format) {
if (format.maxInputSize != Format.NO_VALUE) {
// The format defines an explicit maximum input size. Add the total size of initialization
// data buffers, as they may need to be queued in the same input buffer as the largest sample.
int totalInitializationDataSize = 0;
int initializationDataCount = format.initializationData.size();
for (int i = 0; i < initializationDataCount; i++) {
totalInitializationDataSize += format.initializationData.get(i).length;
}
return format.maxInputSize + totalInitializationDataSize;
} else {
// Calculated maximum input sizes are overestimates, so it's not necessary to add the size of
// initialization data.
return getCodecMaxInputSize(codecInfo, format.sampleMimeType, format.width, format.height);
}
}
/**
* Returns a maximum input size for a given codec, MIME type, width and height.
*
* @param codecInfo Information about the {@link MediaCodec} being configured.
* @param sampleMimeType The format mime type.
* @param width The width in pixels.
* @param height The height in pixels.
* @return A maximum input size in bytes, or {@link Format#NO_VALUE} if a maximum could not be
* determined.
*/
private static int getCodecMaxInputSize(
MediaCodecInfo codecInfo, String sampleMimeType, int width, int height) {
if (width == Format.NO_VALUE || height == Format.NO_VALUE) {
// We can't infer a maximum input size without video dimensions.
return Format.NO_VALUE;
}
// Attempt to infer a maximum input size from the format.
int maxPixels;
int minCompressionRatio;
switch (sampleMimeType) {
case MimeTypes.VIDEO_H263:
case MimeTypes.VIDEO_MP4V:
maxPixels = width * height;
minCompressionRatio = 2;
break;
case MimeTypes.VIDEO_H264:
if ("BRAVIA 4K 2015".equals(Util.MODEL) // Sony Bravia 4K
|| ("Amazon".equals(Util.MANUFACTURER)
&& ("KFSOWI".equals(Util.MODEL) // Kindle Soho
|| ("AFTS".equals(Util.MODEL) && codecInfo.secure)))) { // Fire TV Gen 2
// Use the default value for cases where platform limitations may prevent buffers of the
// calculated maximum input size from being allocated.
return Format.NO_VALUE;
}
// Round up width/height to an integer number of macroblocks.
maxPixels = Util.ceilDivide(width, 16) * Util.ceilDivide(height, 16) * 16 * 16;
minCompressionRatio = 2;
break;
case MimeTypes.VIDEO_VP8:
// VPX does not specify a ratio so use the values from the platform's SoftVPX.cpp.
maxPixels = width * height;
minCompressionRatio = 2;
break;
case MimeTypes.VIDEO_H265:
case MimeTypes.VIDEO_VP9:
maxPixels = width * height;
minCompressionRatio = 4;
break;
default:
// Leave the default max input size.
return Format.NO_VALUE;
}
// Estimate the maximum input size assuming three channel 4:2:0 subsampled input frames.
return (maxPixels * 3) / (2 * minCompressionRatio);
}
/**
* Returns whether the device is known to do post processing by default that isn't compatible with
* ExoPlayer.
*
* @return Whether the device is known to do post processing by default that isn't compatible with
* ExoPlayer.
*/
private static boolean deviceNeedsNoPostProcessWorkaround() {
// Nvidia devices prior to M try to adjust the playback rate to better map the frame-rate of
// content to the refresh rate of the display. For example playback of 23.976fps content is
// adjusted to play at 1.001x speed when the output display is 60Hz. Unfortunately the
// implementation causes ExoPlayer's reported playback position to drift out of sync. Captions
// also lose sync [Internal: b/26453592]. Even after M, the devices may apply post processing
// operations that can modify frame output timestamps, which is incompatible with ExoPlayer's
// logic for skipping decode-only frames.
return "NVIDIA".equals(Util.MANUFACTURER);
}
/*
* TODO:
*
* 1. Validate that Android device certification now ensures correct behavior, and add a
* corresponding SDK_INT upper bound for applying the workaround (probably SDK_INT < 26).
* 2. Determine a complete list of affected devices.
* 3. Some of the devices in this list only fail to support setOutputSurface when switching from
* a SurfaceView provided Surface to a Surface of another type (e.g. TextureView/DummySurface),
* and vice versa. One hypothesis is that setOutputSurface fails when the surfaces have
* different pixel formats. If we can find a way to query the Surface instances to determine
* whether this case applies, then we'll be able to provide a more targeted workaround.
*/
/**
* Returns whether the codec is known to implement {@link MediaCodec#setOutputSurface(Surface)}
* incorrectly.
*
* <p>If true is returned then we fall back to releasing and re-instantiating the codec instead.
*
* @param name The name of the codec.
* @return True if the device is known to implement {@link MediaCodec#setOutputSurface(Surface)}
* incorrectly.
*/
protected boolean codecNeedsSetOutputSurfaceWorkaround(String name) {
if (name.startsWith("OMX.google")) {
// Google OMX decoders are not known to have this issue on any API level.
return false;
}
synchronized (MediaCodecVideoRenderer.class) {
if (!evaluatedDeviceNeedsSetOutputSurfaceWorkaround) {
deviceNeedsSetOutputSurfaceWorkaround = evaluateDeviceNeedsSetOutputSurfaceWorkaround();
evaluatedDeviceNeedsSetOutputSurfaceWorkaround = true;
}
}
return deviceNeedsSetOutputSurfaceWorkaround;
}
protected Surface getSurface() {
return surface;
}
protected static final class CodecMaxValues {
public final int width;
public final int height;
public final int inputSize;
public CodecMaxValues(int width, int height, int inputSize) {
this.width = width;
this.height = height;
this.inputSize = inputSize;
}
}
private static boolean evaluateDeviceNeedsSetOutputSurfaceWorkaround() {
if (Util.SDK_INT <= 28) {
// Workaround for MiTV devices which have been observed broken up to API 28.
// https://github.com/google/ExoPlayer/issues/5169,
// https://github.com/google/ExoPlayer/issues/6899.
// https://github.com/google/ExoPlayer/issues/8014.
switch (Util.DEVICE) {
case "dangal":
case "dangalUHD":
case "dangalFHD":
case "magnolia":
case "machuca":
return true;
default:
break; // Do nothing.
}
}
if (Util.SDK_INT <= 27 && "HWEML".equals(Util.DEVICE)) {
// Workaround for Huawei P20:
// https://github.com/google/ExoPlayer/issues/4468#issuecomment-459291645.
return true;
}
if (Util.SDK_INT <= 26) {
// In general, devices running API level 27 or later should be unaffected unless observed
// otherwise. Enable the workaround on a per-device basis. Works around:
// https://github.com/google/ExoPlayer/issues/3236,
// https://github.com/google/ExoPlayer/issues/3355,
// https://github.com/google/ExoPlayer/issues/3439,
// https://github.com/google/ExoPlayer/issues/3724,
// https://github.com/google/ExoPlayer/issues/3835,
// https://github.com/google/ExoPlayer/issues/4006,
// https://github.com/google/ExoPlayer/issues/4084,
// https://github.com/google/ExoPlayer/issues/4104,
// https://github.com/google/ExoPlayer/issues/4134,
// https://github.com/google/ExoPlayer/issues/4315,
// https://github.com/google/ExoPlayer/issues/4419,
// https://github.com/google/ExoPlayer/issues/4460,
// https://github.com/google/ExoPlayer/issues/4468,
// https://github.com/google/ExoPlayer/issues/5312,
// https://github.com/google/ExoPlayer/issues/6503.
// https://github.com/google/ExoPlayer/issues/8014,
// https://github.com/google/ExoPlayer/pull/8030.
switch (Util.DEVICE) {
case "1601":
case "1713":
case "1714":
case "601LV":
case "602LV":
case "A10-70F":
case "A10-70L":
case "A1601":
case "A2016a40":
case "A7000-a":
case "A7000plus":
case "A7010a48":
case "A7020a48":
case "AquaPowerM":
case "ASUS_X00AD_2":
case "Aura_Note_2":
case "b5":
case "BLACK-1X":
case "BRAVIA_ATV2":
case "BRAVIA_ATV3_4K":
case "C1":
case "ComioS1":
case "CP8676_I02":
case "CPH1609":
case "CPH1715":
case "CPY83_I00":
case "cv1":
case "cv3":
case "deb":
case "DM-01K":
case "E5643":
case "ELUGA_A3_Pro":
case "ELUGA_Note":
case "ELUGA_Prim":
case "ELUGA_Ray_X":
case "EverStar_S":
case "F01H":
case "F01J":
case "F02H":
case "F03H":
case "F04H":
case "F04J":
case "F3111":
case "F3113":
case "F3116":
case "F3211":
case "F3213":
case "F3215":
case "F3311":
case "flo":
case "fugu":
case "GiONEE_CBL7513":
case "GiONEE_GBL7319":
case "GIONEE_GBL7360":
case "GIONEE_SWW1609":
case "GIONEE_SWW1627":
case "GIONEE_SWW1631":
case "GIONEE_WBL5708":
case "GIONEE_WBL7365":
case "GIONEE_WBL7519":
case "griffin":
case "htc_e56ml_dtul":
case "hwALE-H":
case "HWBLN-H":
case "HWCAM-H":
case "HWVNS-H":
case "HWWAS-H":
case "i9031":
case "iball8735_9806":
case "Infinix-X572":
case "iris60":
case "itel_S41":
case "j2xlteins":
case "JGZ":
case "K50a40":
case "kate":
case "l5460":
case "le_x6":
case "LS-5017":
case "M04":
case "M5c":
case "manning":
case "marino_f":
case "MEIZU_M5":
case "mh":
case "mido":
case "MX6":
case "namath":
case "nicklaus_f":
case "NX541J":
case "NX573J":
case "OnePlus5T":
case "p212":
case "P681":
case "P85":
case "pacificrim":
case "panell_d":
case "panell_dl":
case "panell_ds":
case "panell_dt":
case "PB2-670M":
case "PGN528":
case "PGN610":
case "PGN611":
case "Phantom6":
case "Pixi4-7_3G":
case "Pixi5-10_4G":
case "PLE":
case "PRO7S":
case "Q350":
case "Q4260":
case "Q427":
case "Q4310":
case "Q5":
case "QM16XE_U":
case "QX1":
case "RAIJIN":
case "santoni":
case "Slate_Pro":
case "SVP-DTV15":
case "s905x018":
case "taido_row":
case "TB3-730F":
case "TB3-730X":
case "TB3-850F":
case "TB3-850M":
case "tcl_eu":
case "V1":
case "V23GB":
case "V5":
case "vernee_M5":
case "watson":
case "whyred":
case "woods_f":
case "woods_fn":
case "X3_HK":
case "XE2X":
case "XT1663":
case "Z12_PRO":
case "Z80":
return true;
default:
break; // Do nothing.
}
switch (Util.MODEL) {
case "AFTA":
case "AFTN":
case "JSN-L21":
return true;
default:
break; // Do nothing.
}
}
return false;
}
@RequiresApi(23)
private final class OnFrameRenderedListenerV23
implements MediaCodec.OnFrameRenderedListener, Handler.Callback {
private static final int HANDLE_FRAME_RENDERED = 0;
private final Handler handler;
public OnFrameRenderedListenerV23(MediaCodec codec) {
handler = Util.createHandlerForCurrentLooper(/* callback= */ this);
codec.setOnFrameRenderedListener(/* listener= */ this, handler);
}
@Override
public void onFrameRendered(MediaCodec codec, long presentationTimeUs, long nanoTime) {
// Workaround bug in MediaCodec that causes deadlock if you call directly back into the
// MediaCodec from this listener method.
// Deadlock occurs because MediaCodec calls this listener method holding a lock,
// which may also be required by calls made back into the MediaCodec.
// This was fixed in https://android-review.googlesource.com/1156807.
//
// The workaround queues the event for subsequent processing, where the lock will not be held.
if (Util.SDK_INT < 30) {
Message message =
Message.obtain(
handler,
/* what= */ HANDLE_FRAME_RENDERED,
/* arg1= */ (int) (presentationTimeUs >> 32),
/* arg2= */ (int) presentationTimeUs);
handler.sendMessageAtFrontOfQueue(message);
} else {
handleFrameRendered(presentationTimeUs);
}
}
@Override
public boolean handleMessage(Message message) {
switch (message.what) {
case HANDLE_FRAME_RENDERED:
handleFrameRendered(Util.toLong(message.arg1, message.arg2));
return true;
default:
return false;
}
}
private void handleFrameRendered(long presentationTimeUs) {
if (this != tunnelingOnFrameRenderedListener) {
// Stale event.
return;
}
if (presentationTimeUs == TUNNELING_EOS_PRESENTATION_TIME_US) {
onProcessedTunneledEndOfStream();
} else {
try {
onProcessedTunneledBuffer(presentationTimeUs);
} catch (ExoPlaybackException e) {
setPendingPlaybackException(e);
}
}
}
}
}
| library/core/src/main/java/com/google/android/exoplayer2/video/MediaCodecVideoRenderer.java | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.video;
import static com.google.android.exoplayer2.mediacodec.MediaCodecInfo.KEEP_CODEC_RESULT_NO;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Point;
import android.media.MediaCodec;
import android.media.MediaCodecInfo.CodecCapabilities;
import android.media.MediaCodecInfo.CodecProfileLevel;
import android.media.MediaCrypto;
import android.media.MediaFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Pair;
import android.view.Surface;
import androidx.annotation.CallSuper;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.FormatHolder;
import com.google.android.exoplayer2.PlayerMessage.Target;
import com.google.android.exoplayer2.RendererCapabilities;
import com.google.android.exoplayer2.decoder.DecoderCounters;
import com.google.android.exoplayer2.decoder.DecoderInputBuffer;
import com.google.android.exoplayer2.drm.DrmInitData;
import com.google.android.exoplayer2.mediacodec.MediaCodecAdapter;
import com.google.android.exoplayer2.mediacodec.MediaCodecDecoderException;
import com.google.android.exoplayer2.mediacodec.MediaCodecInfo;
import com.google.android.exoplayer2.mediacodec.MediaCodecInfo.KeepCodecResult;
import com.google.android.exoplayer2.mediacodec.MediaCodecRenderer;
import com.google.android.exoplayer2.mediacodec.MediaCodecSelector;
import com.google.android.exoplayer2.mediacodec.MediaCodecUtil;
import com.google.android.exoplayer2.mediacodec.MediaCodecUtil.DecoderQueryException;
import com.google.android.exoplayer2.mediacodec.MediaFormatUtil;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.Log;
import com.google.android.exoplayer2.util.MimeTypes;
import com.google.android.exoplayer2.util.TraceUtil;
import com.google.android.exoplayer2.util.Util;
import com.google.android.exoplayer2.video.VideoRendererEventListener.EventDispatcher;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.List;
/**
* Decodes and renders video using {@link MediaCodec}.
*
* <p>This renderer accepts the following messages sent via {@link ExoPlayer#createMessage(Target)}
* on the playback thread:
*
* <ul>
* <li>Message with type {@link #MSG_SET_SURFACE} to set the output surface. The message payload
* should be the target {@link Surface}, or null.
* <li>Message with type {@link #MSG_SET_SCALING_MODE} to set the video scaling mode. The message
* payload should be one of the integer scaling modes in {@link VideoScalingMode}. Note that
* the scaling mode only applies if the {@link Surface} targeted by this renderer is owned by
* a {@link android.view.SurfaceView}.
* <li>Message with type {@link #MSG_SET_VIDEO_FRAME_METADATA_LISTENER} to set a listener for
* metadata associated with frames being rendered. The message payload should be the {@link
* VideoFrameMetadataListener}, or null.
* </ul>
*/
public class MediaCodecVideoRenderer extends MediaCodecRenderer {
private static final String TAG = "MediaCodecVideoRenderer";
private static final String KEY_CROP_LEFT = "crop-left";
private static final String KEY_CROP_RIGHT = "crop-right";
private static final String KEY_CROP_BOTTOM = "crop-bottom";
private static final String KEY_CROP_TOP = "crop-top";
// Long edge length in pixels for standard video formats, in decreasing in order.
private static final int[] STANDARD_LONG_EDGE_VIDEO_PX = new int[] {
1920, 1600, 1440, 1280, 960, 854, 640, 540, 480};
/**
* Scale factor for the initial maximum input size used to configure the codec in non-adaptive
* playbacks. See {@link #getCodecMaxValues(MediaCodecInfo, Format, Format[])}.
*/
private static final float INITIAL_FORMAT_MAX_INPUT_SIZE_SCALE_FACTOR = 1.5f;
/** Magic frame render timestamp that indicates the EOS in tunneling mode. */
private static final long TUNNELING_EOS_PRESENTATION_TIME_US = Long.MAX_VALUE;
private static boolean evaluatedDeviceNeedsSetOutputSurfaceWorkaround;
private static boolean deviceNeedsSetOutputSurfaceWorkaround;
private final Context context;
private final VideoFrameReleaseTimeHelper frameReleaseTimeHelper;
private final EventDispatcher eventDispatcher;
private final long allowedJoiningTimeMs;
private final int maxDroppedFramesToNotify;
private final boolean deviceNeedsNoPostProcessWorkaround;
private CodecMaxValues codecMaxValues;
private boolean codecNeedsSetOutputSurfaceWorkaround;
private boolean codecHandlesHdr10PlusOutOfBandMetadata;
@Nullable private Surface surface;
private float surfaceFrameRate;
@Nullable private Surface dummySurface;
private boolean haveReportedFirstFrameRenderedForCurrentSurface;
@VideoScalingMode private int scalingMode;
private boolean renderedFirstFrameAfterReset;
private boolean mayRenderFirstFrameAfterEnableIfNotStarted;
private boolean renderedFirstFrameAfterEnable;
private long initialPositionUs;
private long joiningDeadlineMs;
private long droppedFrameAccumulationStartTimeMs;
private int droppedFrames;
private int consecutiveDroppedFrameCount;
private int buffersInCodecCount;
private long lastRenderTimeUs;
private long totalVideoFrameProcessingOffsetUs;
private int videoFrameProcessingOffsetCount;
private int currentWidth;
private int currentHeight;
private int currentUnappliedRotationDegrees;
private float currentPixelWidthHeightRatio;
private float currentFrameRate;
private int reportedWidth;
private int reportedHeight;
private int reportedUnappliedRotationDegrees;
private float reportedPixelWidthHeightRatio;
private boolean tunneling;
private int tunnelingAudioSessionId;
/* package */ @Nullable OnFrameRenderedListenerV23 tunnelingOnFrameRenderedListener;
@Nullable private VideoFrameMetadataListener frameMetadataListener;
/**
* @param context A context.
* @param mediaCodecSelector A decoder selector.
*/
public MediaCodecVideoRenderer(Context context, MediaCodecSelector mediaCodecSelector) {
this(context, mediaCodecSelector, 0);
}
/**
* @param context A context.
* @param mediaCodecSelector A decoder selector.
* @param allowedJoiningTimeMs The maximum duration in milliseconds for which this video renderer
* can attempt to seamlessly join an ongoing playback.
*/
public MediaCodecVideoRenderer(Context context, MediaCodecSelector mediaCodecSelector,
long allowedJoiningTimeMs) {
this(
context,
mediaCodecSelector,
allowedJoiningTimeMs,
/* eventHandler= */ null,
/* eventListener= */ null,
/* maxDroppedFramesToNotify= */ -1);
}
/**
* @param context A context.
* @param mediaCodecSelector A decoder selector.
* @param allowedJoiningTimeMs The maximum duration in milliseconds for which this video renderer
* can attempt to seamlessly join an ongoing playback.
* @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
* null if delivery of events is not required.
* @param eventListener A listener of events. May be null if delivery of events is not required.
* @param maxDroppedFramesToNotify The maximum number of frames that can be dropped between
* invocations of {@link VideoRendererEventListener#onDroppedFrames(int, long)}.
*/
public MediaCodecVideoRenderer(
Context context,
MediaCodecSelector mediaCodecSelector,
long allowedJoiningTimeMs,
@Nullable Handler eventHandler,
@Nullable VideoRendererEventListener eventListener,
int maxDroppedFramesToNotify) {
this(
context,
mediaCodecSelector,
allowedJoiningTimeMs,
/* enableDecoderFallback= */ false,
eventHandler,
eventListener,
maxDroppedFramesToNotify);
}
/**
* @param context A context.
* @param mediaCodecSelector A decoder selector.
* @param allowedJoiningTimeMs The maximum duration in milliseconds for which this video renderer
* can attempt to seamlessly join an ongoing playback.
* @param enableDecoderFallback Whether to enable fallback to lower-priority decoders if decoder
* initialization fails. This may result in using a decoder that is slower/less efficient than
* the primary decoder.
* @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
* null if delivery of events is not required.
* @param eventListener A listener of events. May be null if delivery of events is not required.
* @param maxDroppedFramesToNotify The maximum number of frames that can be dropped between
* invocations of {@link VideoRendererEventListener#onDroppedFrames(int, long)}.
*/
public MediaCodecVideoRenderer(
Context context,
MediaCodecSelector mediaCodecSelector,
long allowedJoiningTimeMs,
boolean enableDecoderFallback,
@Nullable Handler eventHandler,
@Nullable VideoRendererEventListener eventListener,
int maxDroppedFramesToNotify) {
super(
C.TRACK_TYPE_VIDEO,
mediaCodecSelector,
enableDecoderFallback,
/* assumedMinimumCodecOperatingRate= */ 30);
this.allowedJoiningTimeMs = allowedJoiningTimeMs;
this.maxDroppedFramesToNotify = maxDroppedFramesToNotify;
this.context = context.getApplicationContext();
frameReleaseTimeHelper = new VideoFrameReleaseTimeHelper(this.context);
eventDispatcher = new EventDispatcher(eventHandler, eventListener);
deviceNeedsNoPostProcessWorkaround = deviceNeedsNoPostProcessWorkaround();
joiningDeadlineMs = C.TIME_UNSET;
currentWidth = Format.NO_VALUE;
currentHeight = Format.NO_VALUE;
currentPixelWidthHeightRatio = Format.NO_VALUE;
scalingMode = VIDEO_SCALING_MODE_DEFAULT;
clearReportedVideoSize();
}
@Override
public String getName() {
return TAG;
}
@Override
@Capabilities
protected int supportsFormat(MediaCodecSelector mediaCodecSelector, Format format)
throws DecoderQueryException {
String mimeType = format.sampleMimeType;
if (!MimeTypes.isVideo(mimeType)) {
return RendererCapabilities.create(FORMAT_UNSUPPORTED_TYPE);
}
@Nullable DrmInitData drmInitData = format.drmInitData;
// Assume encrypted content requires secure decoders.
boolean requiresSecureDecryption = drmInitData != null;
List<MediaCodecInfo> decoderInfos =
getDecoderInfos(
mediaCodecSelector,
format,
requiresSecureDecryption,
/* requiresTunnelingDecoder= */ false);
if (requiresSecureDecryption && decoderInfos.isEmpty()) {
// No secure decoders are available. Fall back to non-secure decoders.
decoderInfos =
getDecoderInfos(
mediaCodecSelector,
format,
/* requiresSecureDecoder= */ false,
/* requiresTunnelingDecoder= */ false);
}
if (decoderInfos.isEmpty()) {
return RendererCapabilities.create(FORMAT_UNSUPPORTED_SUBTYPE);
}
if (!supportsFormatDrm(format)) {
return RendererCapabilities.create(FORMAT_UNSUPPORTED_DRM);
}
// Check capabilities for the first decoder in the list, which takes priority.
MediaCodecInfo decoderInfo = decoderInfos.get(0);
boolean isFormatSupported = decoderInfo.isFormatSupported(format);
@AdaptiveSupport
int adaptiveSupport =
decoderInfo.isSeamlessAdaptationSupported(format)
? ADAPTIVE_SEAMLESS
: ADAPTIVE_NOT_SEAMLESS;
@TunnelingSupport int tunnelingSupport = TUNNELING_NOT_SUPPORTED;
if (isFormatSupported) {
List<MediaCodecInfo> tunnelingDecoderInfos =
getDecoderInfos(
mediaCodecSelector,
format,
requiresSecureDecryption,
/* requiresTunnelingDecoder= */ true);
if (!tunnelingDecoderInfos.isEmpty()) {
MediaCodecInfo tunnelingDecoderInfo = tunnelingDecoderInfos.get(0);
if (tunnelingDecoderInfo.isFormatSupported(format)
&& tunnelingDecoderInfo.isSeamlessAdaptationSupported(format)) {
tunnelingSupport = TUNNELING_SUPPORTED;
}
}
}
@FormatSupport
int formatSupport = isFormatSupported ? FORMAT_HANDLED : FORMAT_EXCEEDS_CAPABILITIES;
return RendererCapabilities.create(formatSupport, adaptiveSupport, tunnelingSupport);
}
@Override
protected List<MediaCodecInfo> getDecoderInfos(
MediaCodecSelector mediaCodecSelector, Format format, boolean requiresSecureDecoder)
throws DecoderQueryException {
return getDecoderInfos(mediaCodecSelector, format, requiresSecureDecoder, tunneling);
}
private static List<MediaCodecInfo> getDecoderInfos(
MediaCodecSelector mediaCodecSelector,
Format format,
boolean requiresSecureDecoder,
boolean requiresTunnelingDecoder)
throws DecoderQueryException {
@Nullable String mimeType = format.sampleMimeType;
if (mimeType == null) {
return Collections.emptyList();
}
List<MediaCodecInfo> decoderInfos =
mediaCodecSelector.getDecoderInfos(
mimeType, requiresSecureDecoder, requiresTunnelingDecoder);
decoderInfos = MediaCodecUtil.getDecoderInfosSortedByFormatSupport(decoderInfos, format);
if (MimeTypes.VIDEO_DOLBY_VISION.equals(mimeType)) {
// Fall back to H.264/AVC or H.265/HEVC for the relevant DV profiles.
@Nullable
Pair<Integer, Integer> codecProfileAndLevel = MediaCodecUtil.getCodecProfileAndLevel(format);
if (codecProfileAndLevel != null) {
int profile = codecProfileAndLevel.first;
if (profile == CodecProfileLevel.DolbyVisionProfileDvheDtr
|| profile == CodecProfileLevel.DolbyVisionProfileDvheSt) {
decoderInfos.addAll(
mediaCodecSelector.getDecoderInfos(
MimeTypes.VIDEO_H265, requiresSecureDecoder, requiresTunnelingDecoder));
} else if (profile == CodecProfileLevel.DolbyVisionProfileDvavSe) {
decoderInfos.addAll(
mediaCodecSelector.getDecoderInfos(
MimeTypes.VIDEO_H264, requiresSecureDecoder, requiresTunnelingDecoder));
}
}
}
return Collections.unmodifiableList(decoderInfos);
}
@Override
protected void onEnabled(boolean joining, boolean mayRenderStartOfStream)
throws ExoPlaybackException {
super.onEnabled(joining, mayRenderStartOfStream);
int oldTunnelingAudioSessionId = tunnelingAudioSessionId;
tunnelingAudioSessionId = getConfiguration().tunnelingAudioSessionId;
tunneling = tunnelingAudioSessionId != C.AUDIO_SESSION_ID_UNSET;
if (tunnelingAudioSessionId != oldTunnelingAudioSessionId) {
releaseCodec();
}
eventDispatcher.enabled(decoderCounters);
frameReleaseTimeHelper.enable();
mayRenderFirstFrameAfterEnableIfNotStarted = mayRenderStartOfStream;
renderedFirstFrameAfterEnable = false;
}
@Override
protected void onPositionReset(long positionUs, boolean joining) throws ExoPlaybackException {
super.onPositionReset(positionUs, joining);
clearRenderedFirstFrame();
initialPositionUs = C.TIME_UNSET;
consecutiveDroppedFrameCount = 0;
if (joining) {
setJoiningDeadlineMs();
} else {
joiningDeadlineMs = C.TIME_UNSET;
}
}
@Override
public boolean isReady() {
if (super.isReady()
&& (renderedFirstFrameAfterReset
|| (dummySurface != null && surface == dummySurface)
|| getCodec() == null
|| tunneling)) {
// Ready. If we were joining then we've now joined, so clear the joining deadline.
joiningDeadlineMs = C.TIME_UNSET;
return true;
} else if (joiningDeadlineMs == C.TIME_UNSET) {
// Not joining.
return false;
} else if (SystemClock.elapsedRealtime() < joiningDeadlineMs) {
// Joining and still within the joining deadline.
return true;
} else {
// The joining deadline has been exceeded. Give up and clear the deadline.
joiningDeadlineMs = C.TIME_UNSET;
return false;
}
}
@Override
protected void onStarted() {
super.onStarted();
droppedFrames = 0;
droppedFrameAccumulationStartTimeMs = SystemClock.elapsedRealtime();
lastRenderTimeUs = SystemClock.elapsedRealtime() * 1000;
totalVideoFrameProcessingOffsetUs = 0;
videoFrameProcessingOffsetCount = 0;
updateSurfaceFrameRate(/* isNewSurface= */ false);
}
@Override
protected void onStopped() {
joiningDeadlineMs = C.TIME_UNSET;
maybeNotifyDroppedFrames();
maybeNotifyVideoFrameProcessingOffset();
clearSurfaceFrameRate();
super.onStopped();
}
@Override
protected void onDisabled() {
clearReportedVideoSize();
clearRenderedFirstFrame();
haveReportedFirstFrameRenderedForCurrentSurface = false;
frameReleaseTimeHelper.disable();
tunnelingOnFrameRenderedListener = null;
try {
super.onDisabled();
} finally {
eventDispatcher.disabled(decoderCounters);
}
}
@Override
protected void onReset() {
try {
super.onReset();
} finally {
if (dummySurface != null) {
if (surface == dummySurface) {
surface = null;
}
dummySurface.release();
dummySurface = null;
}
}
}
@Override
public void handleMessage(int messageType, @Nullable Object message) throws ExoPlaybackException {
if (messageType == MSG_SET_SURFACE) {
setSurface((Surface) message);
} else if (messageType == MSG_SET_SCALING_MODE) {
scalingMode = (Integer) message;
MediaCodec codec = getCodec();
if (codec != null) {
codec.setVideoScalingMode(scalingMode);
}
} else if (messageType == MSG_SET_VIDEO_FRAME_METADATA_LISTENER) {
frameMetadataListener = (VideoFrameMetadataListener) message;
} else {
super.handleMessage(messageType, message);
}
}
private void setSurface(Surface surface) throws ExoPlaybackException {
if (surface == null) {
// Use a dummy surface if possible.
if (dummySurface != null) {
surface = dummySurface;
} else {
MediaCodecInfo codecInfo = getCodecInfo();
if (codecInfo != null && shouldUseDummySurface(codecInfo)) {
dummySurface = DummySurface.newInstanceV17(context, codecInfo.secure);
surface = dummySurface;
}
}
}
// We only need to update the codec if the surface has changed.
if (this.surface != surface) {
clearSurfaceFrameRate();
this.surface = surface;
haveReportedFirstFrameRenderedForCurrentSurface = false;
updateSurfaceFrameRate(/* isNewSurface= */ true);
@State int state = getState();
MediaCodec codec = getCodec();
if (codec != null) {
if (Util.SDK_INT >= 23 && surface != null && !codecNeedsSetOutputSurfaceWorkaround) {
setOutputSurfaceV23(codec, surface);
} else {
releaseCodec();
maybeInitCodecOrBypass();
}
}
if (surface != null && surface != dummySurface) {
// If we know the video size, report it again immediately.
maybeRenotifyVideoSizeChanged();
// We haven't rendered to the new surface yet.
clearRenderedFirstFrame();
if (state == STATE_STARTED) {
setJoiningDeadlineMs();
}
} else {
// The surface has been removed.
clearReportedVideoSize();
clearRenderedFirstFrame();
}
} else if (surface != null && surface != dummySurface) {
// The surface is set and unchanged. If we know the video size and/or have already rendered to
// the surface, report these again immediately.
maybeRenotifyVideoSizeChanged();
maybeRenotifyRenderedFirstFrame();
}
}
@Override
protected boolean shouldInitCodec(MediaCodecInfo codecInfo) {
return surface != null || shouldUseDummySurface(codecInfo);
}
@Override
protected boolean getCodecNeedsEosPropagation() {
// Since API 23, onFrameRenderedListener allows for detection of the renderer EOS.
return tunneling && Util.SDK_INT < 23;
}
@Override
protected void configureCodec(
MediaCodecInfo codecInfo,
MediaCodecAdapter codecAdapter,
Format format,
@Nullable MediaCrypto crypto,
float codecOperatingRate) {
String codecMimeType = codecInfo.codecMimeType;
codecMaxValues = getCodecMaxValues(codecInfo, format, getStreamFormats());
MediaFormat mediaFormat =
getMediaFormat(
format,
codecMimeType,
codecMaxValues,
codecOperatingRate,
deviceNeedsNoPostProcessWorkaround,
tunnelingAudioSessionId);
if (surface == null) {
if (!shouldUseDummySurface(codecInfo)) {
throw new IllegalStateException();
}
if (dummySurface == null) {
dummySurface = DummySurface.newInstanceV17(context, codecInfo.secure);
}
surface = dummySurface;
}
codecAdapter.configure(mediaFormat, surface, crypto, 0);
if (Util.SDK_INT >= 23 && tunneling) {
tunnelingOnFrameRenderedListener = new OnFrameRenderedListenerV23(codecAdapter.getCodec());
}
}
@Override
@KeepCodecResult
protected int canKeepCodec(
MediaCodec codec, MediaCodecInfo codecInfo, Format oldFormat, Format newFormat) {
if (newFormat.width > codecMaxValues.width
|| newFormat.height > codecMaxValues.height
|| getMaxInputSize(codecInfo, newFormat) > codecMaxValues.inputSize) {
return KEEP_CODEC_RESULT_NO;
}
return codecInfo.canKeepCodec(oldFormat, newFormat);
}
@CallSuper
@Override
protected void resetCodecStateForFlush() {
super.resetCodecStateForFlush();
buffersInCodecCount = 0;
}
@Override
public void setPlaybackSpeed(float playbackSpeed) throws ExoPlaybackException {
super.setPlaybackSpeed(playbackSpeed);
updateSurfaceFrameRate(/* isNewSurface= */ false);
}
@Override
protected float getCodecOperatingRateV23(
float playbackSpeed, Format format, Format[] streamFormats) {
// Use the highest known stream frame-rate up front, to avoid having to reconfigure the codec
// should an adaptive switch to that stream occur.
float maxFrameRate = -1;
for (Format streamFormat : streamFormats) {
float streamFrameRate = streamFormat.frameRate;
if (streamFrameRate != Format.NO_VALUE) {
maxFrameRate = max(maxFrameRate, streamFrameRate);
}
}
return maxFrameRate == -1 ? CODEC_OPERATING_RATE_UNSET : (maxFrameRate * playbackSpeed);
}
@Override
protected void onCodecInitialized(String name, long initializedTimestampMs,
long initializationDurationMs) {
eventDispatcher.decoderInitialized(name, initializedTimestampMs, initializationDurationMs);
codecNeedsSetOutputSurfaceWorkaround = codecNeedsSetOutputSurfaceWorkaround(name);
codecHandlesHdr10PlusOutOfBandMetadata =
Assertions.checkNotNull(getCodecInfo()).isHdr10PlusOutOfBandMetadataSupported();
}
@Override
protected void onCodecReleased(String name) {
eventDispatcher.decoderReleased(name);
}
@Override
protected void onInputFormatChanged(FormatHolder formatHolder) throws ExoPlaybackException {
super.onInputFormatChanged(formatHolder);
eventDispatcher.inputFormatChanged(formatHolder.format);
}
/**
* Called immediately before an input buffer is queued into the codec.
*
* <p>In tunneling mode for pre Marshmallow, the buffer is treated as if immediately output.
*
* @param buffer The buffer to be queued.
* @throws ExoPlaybackException Thrown if an error occurs handling the input buffer.
*/
@CallSuper
@Override
protected void onQueueInputBuffer(DecoderInputBuffer buffer) throws ExoPlaybackException {
// In tunneling mode the device may do frame rate conversion, so in general we can't keep track
// of the number of buffers in the codec.
if (!tunneling) {
buffersInCodecCount++;
}
if (Util.SDK_INT < 23 && tunneling) {
// In tunneled mode before API 23 we don't have a way to know when the buffer is output, so
// treat it as if it were output immediately.
onProcessedTunneledBuffer(buffer.timeUs);
}
}
@Override
protected void onOutputFormatChanged(Format format, @Nullable MediaFormat mediaFormat) {
@Nullable MediaCodec codec = getCodec();
if (codec != null) {
// Must be applied each time the output format changes.
codec.setVideoScalingMode(scalingMode);
}
if (tunneling) {
currentWidth = format.width;
currentHeight = format.height;
} else {
Assertions.checkNotNull(mediaFormat);
boolean hasCrop =
mediaFormat.containsKey(KEY_CROP_RIGHT)
&& mediaFormat.containsKey(KEY_CROP_LEFT)
&& mediaFormat.containsKey(KEY_CROP_BOTTOM)
&& mediaFormat.containsKey(KEY_CROP_TOP);
currentWidth =
hasCrop
? mediaFormat.getInteger(KEY_CROP_RIGHT) - mediaFormat.getInteger(KEY_CROP_LEFT) + 1
: mediaFormat.getInteger(MediaFormat.KEY_WIDTH);
currentHeight =
hasCrop
? mediaFormat.getInteger(KEY_CROP_BOTTOM) - mediaFormat.getInteger(KEY_CROP_TOP) + 1
: mediaFormat.getInteger(MediaFormat.KEY_HEIGHT);
}
currentPixelWidthHeightRatio = format.pixelWidthHeightRatio;
if (Util.SDK_INT >= 21) {
// On API level 21 and above the decoder applies the rotation when rendering to the surface.
// Hence currentUnappliedRotation should always be 0. For 90 and 270 degree rotations, we need
// to flip the width, height and pixel aspect ratio to reflect the rotation that was applied.
if (format.rotationDegrees == 90 || format.rotationDegrees == 270) {
int rotatedHeight = currentWidth;
currentWidth = currentHeight;
currentHeight = rotatedHeight;
currentPixelWidthHeightRatio = 1 / currentPixelWidthHeightRatio;
}
} else {
// On API level 20 and below the decoder does not apply the rotation.
currentUnappliedRotationDegrees = format.rotationDegrees;
}
currentFrameRate = format.frameRate;
updateSurfaceFrameRate(/* isNewSurface= */ false);
}
@Override
@TargetApi(29) // codecHandlesHdr10PlusOutOfBandMetadata is false if Util.SDK_INT < 29
protected void handleInputBufferSupplementalData(DecoderInputBuffer buffer)
throws ExoPlaybackException {
if (!codecHandlesHdr10PlusOutOfBandMetadata) {
return;
}
ByteBuffer data = Assertions.checkNotNull(buffer.supplementalData);
if (data.remaining() >= 7) {
// Check for HDR10+ out-of-band metadata. See User_data_registered_itu_t_t35 in ST 2094-40.
byte ituTT35CountryCode = data.get();
int ituTT35TerminalProviderCode = data.getShort();
int ituTT35TerminalProviderOrientedCode = data.getShort();
byte applicationIdentifier = data.get();
byte applicationVersion = data.get();
data.position(0);
if (ituTT35CountryCode == (byte) 0xB5
&& ituTT35TerminalProviderCode == 0x003C
&& ituTT35TerminalProviderOrientedCode == 0x0001
&& applicationIdentifier == 4
&& applicationVersion == 0) {
// The metadata size may vary so allocate a new array every time. This is not too
// inefficient because the metadata is only a few tens of bytes.
byte[] hdr10PlusInfo = new byte[data.remaining()];
data.get(hdr10PlusInfo);
data.position(0);
setHdr10PlusInfoV29(getCodec(), hdr10PlusInfo);
}
}
}
@Override
protected boolean processOutputBuffer(
long positionUs,
long elapsedRealtimeUs,
@Nullable MediaCodec codec,
@Nullable ByteBuffer buffer,
int bufferIndex,
int bufferFlags,
int sampleCount,
long bufferPresentationTimeUs,
boolean isDecodeOnlyBuffer,
boolean isLastBuffer,
Format format)
throws ExoPlaybackException {
Assertions.checkNotNull(codec); // Can not render video without codec
if (initialPositionUs == C.TIME_UNSET) {
initialPositionUs = positionUs;
}
long outputStreamOffsetUs = getOutputStreamOffsetUs();
long presentationTimeUs = bufferPresentationTimeUs - outputStreamOffsetUs;
if (isDecodeOnlyBuffer && !isLastBuffer) {
skipOutputBuffer(codec, bufferIndex, presentationTimeUs);
return true;
}
long earlyUs = bufferPresentationTimeUs - positionUs;
if (surface == dummySurface) {
// Skip frames in sync with playback, so we'll be at the right frame if the mode changes.
if (isBufferLate(earlyUs)) {
skipOutputBuffer(codec, bufferIndex, presentationTimeUs);
updateVideoFrameProcessingOffsetCounters(earlyUs);
return true;
}
return false;
}
long elapsedRealtimeNowUs = SystemClock.elapsedRealtime() * 1000;
long elapsedSinceLastRenderUs = elapsedRealtimeNowUs - lastRenderTimeUs;
boolean isStarted = getState() == STATE_STARTED;
boolean shouldRenderFirstFrame =
!renderedFirstFrameAfterEnable
? (isStarted || mayRenderFirstFrameAfterEnableIfNotStarted)
: !renderedFirstFrameAfterReset;
// Don't force output until we joined and the position reached the current stream.
boolean forceRenderOutputBuffer =
joiningDeadlineMs == C.TIME_UNSET
&& positionUs >= outputStreamOffsetUs
&& (shouldRenderFirstFrame
|| (isStarted && shouldForceRenderOutputBuffer(earlyUs, elapsedSinceLastRenderUs)));
if (forceRenderOutputBuffer) {
long releaseTimeNs = System.nanoTime();
notifyFrameMetadataListener(presentationTimeUs, releaseTimeNs, format);
if (Util.SDK_INT >= 21) {
renderOutputBufferV21(codec, bufferIndex, presentationTimeUs, releaseTimeNs);
} else {
renderOutputBuffer(codec, bufferIndex, presentationTimeUs);
}
updateVideoFrameProcessingOffsetCounters(earlyUs);
return true;
}
if (!isStarted || positionUs == initialPositionUs) {
return false;
}
// Fine-grained adjustment of earlyUs based on the elapsed time since the start of the current
// iteration of the rendering loop.
long elapsedSinceStartOfLoopUs = elapsedRealtimeNowUs - elapsedRealtimeUs;
earlyUs -= elapsedSinceStartOfLoopUs;
// Compute the buffer's desired release time in nanoseconds.
long systemTimeNs = System.nanoTime();
long unadjustedFrameReleaseTimeNs = systemTimeNs + (earlyUs * 1000);
// Apply a timestamp adjustment, if there is one.
long adjustedReleaseTimeNs = frameReleaseTimeHelper.adjustReleaseTime(
bufferPresentationTimeUs, unadjustedFrameReleaseTimeNs);
earlyUs = (adjustedReleaseTimeNs - systemTimeNs) / 1000;
boolean treatDroppedBuffersAsSkipped = joiningDeadlineMs != C.TIME_UNSET;
if (shouldDropBuffersToKeyframe(earlyUs, elapsedRealtimeUs, isLastBuffer)
&& maybeDropBuffersToKeyframe(
codec, bufferIndex, presentationTimeUs, positionUs, treatDroppedBuffersAsSkipped)) {
return false;
} else if (shouldDropOutputBuffer(earlyUs, elapsedRealtimeUs, isLastBuffer)) {
if (treatDroppedBuffersAsSkipped) {
skipOutputBuffer(codec, bufferIndex, presentationTimeUs);
} else {
dropOutputBuffer(codec, bufferIndex, presentationTimeUs);
}
updateVideoFrameProcessingOffsetCounters(earlyUs);
return true;
}
if (Util.SDK_INT >= 21) {
// Let the underlying framework time the release.
if (earlyUs < 50000) {
notifyFrameMetadataListener(presentationTimeUs, adjustedReleaseTimeNs, format);
renderOutputBufferV21(codec, bufferIndex, presentationTimeUs, adjustedReleaseTimeNs);
updateVideoFrameProcessingOffsetCounters(earlyUs);
return true;
}
} else {
// We need to time the release ourselves.
if (earlyUs < 30000) {
if (earlyUs > 11000) {
// We're a little too early to render the frame. Sleep until the frame can be rendered.
// Note: The 11ms threshold was chosen fairly arbitrarily.
try {
// Subtracting 10000 rather than 11000 ensures the sleep time will be at least 1ms.
Thread.sleep((earlyUs - 10000) / 1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
notifyFrameMetadataListener(presentationTimeUs, adjustedReleaseTimeNs, format);
renderOutputBuffer(codec, bufferIndex, presentationTimeUs);
updateVideoFrameProcessingOffsetCounters(earlyUs);
return true;
}
}
// We're either not playing, or it's not time to render the frame yet.
return false;
}
private void notifyFrameMetadataListener(
long presentationTimeUs, long releaseTimeNs, Format format) {
if (frameMetadataListener != null) {
frameMetadataListener.onVideoFrameAboutToBeRendered(
presentationTimeUs, releaseTimeNs, format, getCodecOutputMediaFormat());
}
}
/** Called when a buffer was processed in tunneling mode. */
protected void onProcessedTunneledBuffer(long presentationTimeUs) throws ExoPlaybackException {
updateOutputFormatForTime(presentationTimeUs);
maybeNotifyVideoSizeChanged();
decoderCounters.renderedOutputBufferCount++;
maybeNotifyRenderedFirstFrame();
onProcessedOutputBuffer(presentationTimeUs);
}
/** Called when a output EOS was received in tunneling mode. */
private void onProcessedTunneledEndOfStream() {
setPendingOutputEndOfStream();
}
@CallSuper
@Override
protected void onProcessedOutputBuffer(long presentationTimeUs) {
super.onProcessedOutputBuffer(presentationTimeUs);
if (!tunneling) {
buffersInCodecCount--;
}
}
@Override
protected void onProcessedStreamChange() {
super.onProcessedStreamChange();
clearRenderedFirstFrame();
}
/**
* Returns whether the buffer being processed should be dropped.
*
* @param earlyUs The time until the buffer should be presented in microseconds. A negative value
* indicates that the buffer is late.
* @param elapsedRealtimeUs {@link android.os.SystemClock#elapsedRealtime()} in microseconds,
* measured at the start of the current iteration of the rendering loop.
* @param isLastBuffer Whether the buffer is the last buffer in the current stream.
*/
protected boolean shouldDropOutputBuffer(
long earlyUs, long elapsedRealtimeUs, boolean isLastBuffer) {
return isBufferLate(earlyUs) && !isLastBuffer;
}
/**
* Returns whether to drop all buffers from the buffer being processed to the keyframe at or after
* the current playback position, if possible.
*
* @param earlyUs The time until the current buffer should be presented in microseconds. A
* negative value indicates that the buffer is late.
* @param elapsedRealtimeUs {@link android.os.SystemClock#elapsedRealtime()} in microseconds,
* measured at the start of the current iteration of the rendering loop.
* @param isLastBuffer Whether the buffer is the last buffer in the current stream.
*/
protected boolean shouldDropBuffersToKeyframe(
long earlyUs, long elapsedRealtimeUs, boolean isLastBuffer) {
return isBufferVeryLate(earlyUs) && !isLastBuffer;
}
/**
* Returns whether to force rendering an output buffer.
*
* @param earlyUs The time until the current buffer should be presented in microseconds. A
* negative value indicates that the buffer is late.
* @param elapsedSinceLastRenderUs The elapsed time since the last output buffer was rendered, in
* microseconds.
* @return Returns whether to force rendering an output buffer.
*/
protected boolean shouldForceRenderOutputBuffer(long earlyUs, long elapsedSinceLastRenderUs) {
// Force render late buffers every 100ms to avoid frozen video effect.
return isBufferLate(earlyUs) && elapsedSinceLastRenderUs > 100000;
}
/**
* Skips the output buffer with the specified index.
*
* @param codec The codec that owns the output buffer.
* @param index The index of the output buffer to skip.
* @param presentationTimeUs The presentation time of the output buffer, in microseconds.
*/
protected void skipOutputBuffer(MediaCodec codec, int index, long presentationTimeUs) {
TraceUtil.beginSection("skipVideoBuffer");
codec.releaseOutputBuffer(index, false);
TraceUtil.endSection();
decoderCounters.skippedOutputBufferCount++;
}
/**
* Drops the output buffer with the specified index.
*
* @param codec The codec that owns the output buffer.
* @param index The index of the output buffer to drop.
* @param presentationTimeUs The presentation time of the output buffer, in microseconds.
*/
protected void dropOutputBuffer(MediaCodec codec, int index, long presentationTimeUs) {
TraceUtil.beginSection("dropVideoBuffer");
codec.releaseOutputBuffer(index, false);
TraceUtil.endSection();
updateDroppedBufferCounters(1);
}
/**
* Drops frames from the current output buffer to the next keyframe at or before the playback
* position. If no such keyframe exists, as the playback position is inside the same group of
* pictures as the buffer being processed, returns {@code false}. Returns {@code true} otherwise.
*
* @param codec The codec that owns the output buffer.
* @param index The index of the output buffer to drop.
* @param presentationTimeUs The presentation time of the output buffer, in microseconds.
* @param positionUs The current playback position, in microseconds.
* @param treatDroppedBuffersAsSkipped Whether dropped buffers should be treated as intentionally
* skipped.
* @return Whether any buffers were dropped.
* @throws ExoPlaybackException If an error occurs flushing the codec.
*/
protected boolean maybeDropBuffersToKeyframe(
MediaCodec codec,
int index,
long presentationTimeUs,
long positionUs,
boolean treatDroppedBuffersAsSkipped)
throws ExoPlaybackException {
int droppedSourceBufferCount = skipSource(positionUs);
if (droppedSourceBufferCount == 0) {
return false;
}
decoderCounters.droppedToKeyframeCount++;
// We dropped some buffers to catch up, so update the decoder counters and flush the codec,
// which releases all pending buffers buffers including the current output buffer.
int totalDroppedBufferCount = buffersInCodecCount + droppedSourceBufferCount;
if (treatDroppedBuffersAsSkipped) {
decoderCounters.skippedOutputBufferCount += totalDroppedBufferCount;
} else {
updateDroppedBufferCounters(totalDroppedBufferCount);
}
flushOrReinitializeCodec();
return true;
}
/**
* Updates local counters and {@link DecoderCounters} to reflect that {@code droppedBufferCount}
* additional buffers were dropped.
*
* @param droppedBufferCount The number of additional dropped buffers.
*/
protected void updateDroppedBufferCounters(int droppedBufferCount) {
decoderCounters.droppedBufferCount += droppedBufferCount;
droppedFrames += droppedBufferCount;
consecutiveDroppedFrameCount += droppedBufferCount;
decoderCounters.maxConsecutiveDroppedBufferCount =
max(consecutiveDroppedFrameCount, decoderCounters.maxConsecutiveDroppedBufferCount);
if (maxDroppedFramesToNotify > 0 && droppedFrames >= maxDroppedFramesToNotify) {
maybeNotifyDroppedFrames();
}
}
/**
* Updates local counters and {@link DecoderCounters} with a new video frame processing offset.
*
* @param processingOffsetUs The video frame processing offset.
*/
protected void updateVideoFrameProcessingOffsetCounters(long processingOffsetUs) {
decoderCounters.addVideoFrameProcessingOffset(processingOffsetUs);
totalVideoFrameProcessingOffsetUs += processingOffsetUs;
videoFrameProcessingOffsetCount++;
}
/**
* Renders the output buffer with the specified index. This method is only called if the platform
* API version of the device is less than 21.
*
* @param codec The codec that owns the output buffer.
* @param index The index of the output buffer to drop.
* @param presentationTimeUs The presentation time of the output buffer, in microseconds.
*/
protected void renderOutputBuffer(MediaCodec codec, int index, long presentationTimeUs) {
maybeNotifyVideoSizeChanged();
TraceUtil.beginSection("releaseOutputBuffer");
codec.releaseOutputBuffer(index, true);
TraceUtil.endSection();
lastRenderTimeUs = SystemClock.elapsedRealtime() * 1000;
decoderCounters.renderedOutputBufferCount++;
consecutiveDroppedFrameCount = 0;
maybeNotifyRenderedFirstFrame();
}
/**
* Renders the output buffer with the specified index. This method is only called if the platform
* API version of the device is 21 or later.
*
* @param codec The codec that owns the output buffer.
* @param index The index of the output buffer to drop.
* @param presentationTimeUs The presentation time of the output buffer, in microseconds.
* @param releaseTimeNs The wallclock time at which the frame should be displayed, in nanoseconds.
*/
@RequiresApi(21)
protected void renderOutputBufferV21(
MediaCodec codec, int index, long presentationTimeUs, long releaseTimeNs) {
maybeNotifyVideoSizeChanged();
TraceUtil.beginSection("releaseOutputBuffer");
codec.releaseOutputBuffer(index, releaseTimeNs);
TraceUtil.endSection();
lastRenderTimeUs = SystemClock.elapsedRealtime() * 1000;
decoderCounters.renderedOutputBufferCount++;
consecutiveDroppedFrameCount = 0;
maybeNotifyRenderedFirstFrame();
}
/**
* Updates the frame-rate of the current {@link #surface} based on the renderer operating rate,
* frame-rate of the content, and whether the renderer is started.
*
* @param isNewSurface Whether the current {@link #surface} is new.
*/
private void updateSurfaceFrameRate(boolean isNewSurface) {
if (Util.SDK_INT < 30 || surface == null || surface == dummySurface) {
return;
}
boolean shouldSetFrameRate = getState() == STATE_STARTED && currentFrameRate != Format.NO_VALUE;
float surfaceFrameRate = shouldSetFrameRate ? currentFrameRate * getPlaybackSpeed() : 0;
// We always set the frame-rate if we have a new surface, since we have no way of knowing what
// it might have been set to previously.
if (this.surfaceFrameRate == surfaceFrameRate && !isNewSurface) {
return;
}
this.surfaceFrameRate = surfaceFrameRate;
setSurfaceFrameRateV30(surface, surfaceFrameRate);
}
/** Clears the frame-rate of the current {@link #surface}. */
private void clearSurfaceFrameRate() {
if (Util.SDK_INT < 30 || surface == null || surface == dummySurface || surfaceFrameRate == 0) {
return;
}
surfaceFrameRate = 0;
setSurfaceFrameRateV30(surface, /* frameRate= */ 0);
}
@RequiresApi(30)
private static void setSurfaceFrameRateV30(Surface surface, float frameRate) {
int compatibility =
frameRate == 0
? Surface.FRAME_RATE_COMPATIBILITY_DEFAULT
: Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE;
surface.setFrameRate(frameRate, compatibility);
}
private boolean shouldUseDummySurface(MediaCodecInfo codecInfo) {
return Util.SDK_INT >= 23
&& !tunneling
&& !codecNeedsSetOutputSurfaceWorkaround(codecInfo.name)
&& (!codecInfo.secure || DummySurface.isSecureSupported(context));
}
private void setJoiningDeadlineMs() {
joiningDeadlineMs = allowedJoiningTimeMs > 0
? (SystemClock.elapsedRealtime() + allowedJoiningTimeMs) : C.TIME_UNSET;
}
private void clearRenderedFirstFrame() {
renderedFirstFrameAfterReset = false;
// The first frame notification is triggered by renderOutputBuffer or renderOutputBufferV21 for
// non-tunneled playback, onQueueInputBuffer for tunneled playback prior to API level 23, and
// OnFrameRenderedListenerV23.onFrameRenderedListener for tunneled playback on API level 23 and
// above.
if (Util.SDK_INT >= 23 && tunneling) {
MediaCodec codec = getCodec();
// If codec is null then the listener will be instantiated in configureCodec.
if (codec != null) {
tunnelingOnFrameRenderedListener = new OnFrameRenderedListenerV23(codec);
}
}
}
/* package */ void maybeNotifyRenderedFirstFrame() {
renderedFirstFrameAfterEnable = true;
if (!renderedFirstFrameAfterReset) {
renderedFirstFrameAfterReset = true;
eventDispatcher.renderedFirstFrame(surface);
haveReportedFirstFrameRenderedForCurrentSurface = true;
}
}
private void maybeRenotifyRenderedFirstFrame() {
if (haveReportedFirstFrameRenderedForCurrentSurface) {
eventDispatcher.renderedFirstFrame(surface);
}
}
private void clearReportedVideoSize() {
reportedWidth = Format.NO_VALUE;
reportedHeight = Format.NO_VALUE;
reportedPixelWidthHeightRatio = Format.NO_VALUE;
reportedUnappliedRotationDegrees = Format.NO_VALUE;
}
private void maybeNotifyVideoSizeChanged() {
if ((currentWidth != Format.NO_VALUE || currentHeight != Format.NO_VALUE)
&& (reportedWidth != currentWidth || reportedHeight != currentHeight
|| reportedUnappliedRotationDegrees != currentUnappliedRotationDegrees
|| reportedPixelWidthHeightRatio != currentPixelWidthHeightRatio)) {
eventDispatcher.videoSizeChanged(currentWidth, currentHeight, currentUnappliedRotationDegrees,
currentPixelWidthHeightRatio);
reportedWidth = currentWidth;
reportedHeight = currentHeight;
reportedUnappliedRotationDegrees = currentUnappliedRotationDegrees;
reportedPixelWidthHeightRatio = currentPixelWidthHeightRatio;
}
}
private void maybeRenotifyVideoSizeChanged() {
if (reportedWidth != Format.NO_VALUE || reportedHeight != Format.NO_VALUE) {
eventDispatcher.videoSizeChanged(reportedWidth, reportedHeight,
reportedUnappliedRotationDegrees, reportedPixelWidthHeightRatio);
}
}
private void maybeNotifyDroppedFrames() {
if (droppedFrames > 0) {
long now = SystemClock.elapsedRealtime();
long elapsedMs = now - droppedFrameAccumulationStartTimeMs;
eventDispatcher.droppedFrames(droppedFrames, elapsedMs);
droppedFrames = 0;
droppedFrameAccumulationStartTimeMs = now;
}
}
private void maybeNotifyVideoFrameProcessingOffset() {
if (videoFrameProcessingOffsetCount != 0) {
eventDispatcher.reportVideoFrameProcessingOffset(
totalVideoFrameProcessingOffsetUs, videoFrameProcessingOffsetCount);
totalVideoFrameProcessingOffsetUs = 0;
videoFrameProcessingOffsetCount = 0;
}
}
private static boolean isBufferLate(long earlyUs) {
// Class a buffer as late if it should have been presented more than 30 ms ago.
return earlyUs < -30000;
}
private static boolean isBufferVeryLate(long earlyUs) {
// Class a buffer as very late if it should have been presented more than 500 ms ago.
return earlyUs < -500000;
}
@RequiresApi(29)
private static void setHdr10PlusInfoV29(MediaCodec codec, byte[] hdr10PlusInfo) {
Bundle codecParameters = new Bundle();
codecParameters.putByteArray(MediaCodec.PARAMETER_KEY_HDR10_PLUS_INFO, hdr10PlusInfo);
codec.setParameters(codecParameters);
}
@RequiresApi(23)
protected void setOutputSurfaceV23(MediaCodec codec, Surface surface) {
codec.setOutputSurface(surface);
}
@RequiresApi(21)
private static void configureTunnelingV21(MediaFormat mediaFormat, int tunnelingAudioSessionId) {
mediaFormat.setFeatureEnabled(CodecCapabilities.FEATURE_TunneledPlayback, true);
mediaFormat.setInteger(MediaFormat.KEY_AUDIO_SESSION_ID, tunnelingAudioSessionId);
}
/**
* Returns the framework {@link MediaFormat} that should be used to configure the decoder.
*
* @param format The {@link Format} of media.
* @param codecMimeType The MIME type handled by the codec.
* @param codecMaxValues Codec max values that should be used when configuring the decoder.
* @param codecOperatingRate The codec operating rate, or {@link #CODEC_OPERATING_RATE_UNSET} if
* no codec operating rate should be set.
* @param deviceNeedsNoPostProcessWorkaround Whether the device is known to do post processing by
* default that isn't compatible with ExoPlayer.
* @param tunnelingAudioSessionId The audio session id to use for tunneling, or {@link
* C#AUDIO_SESSION_ID_UNSET} if tunneling should not be enabled.
* @return The framework {@link MediaFormat} that should be used to configure the decoder.
*/
@SuppressLint("InlinedApi")
@TargetApi(21) // tunnelingAudioSessionId is unset if Util.SDK_INT < 21
protected MediaFormat getMediaFormat(
Format format,
String codecMimeType,
CodecMaxValues codecMaxValues,
float codecOperatingRate,
boolean deviceNeedsNoPostProcessWorkaround,
int tunnelingAudioSessionId) {
MediaFormat mediaFormat = new MediaFormat();
// Set format parameters that should always be set.
mediaFormat.setString(MediaFormat.KEY_MIME, codecMimeType);
mediaFormat.setInteger(MediaFormat.KEY_WIDTH, format.width);
mediaFormat.setInteger(MediaFormat.KEY_HEIGHT, format.height);
MediaFormatUtil.setCsdBuffers(mediaFormat, format.initializationData);
// Set format parameters that may be unset.
MediaFormatUtil.maybeSetFloat(mediaFormat, MediaFormat.KEY_FRAME_RATE, format.frameRate);
MediaFormatUtil.maybeSetInteger(mediaFormat, MediaFormat.KEY_ROTATION, format.rotationDegrees);
MediaFormatUtil.maybeSetColorInfo(mediaFormat, format.colorInfo);
if (MimeTypes.VIDEO_DOLBY_VISION.equals(format.sampleMimeType)) {
// Some phones require the profile to be set on the codec.
// See https://github.com/google/ExoPlayer/pull/5438.
Pair<Integer, Integer> codecProfileAndLevel = MediaCodecUtil.getCodecProfileAndLevel(format);
if (codecProfileAndLevel != null) {
MediaFormatUtil.maybeSetInteger(
mediaFormat, MediaFormat.KEY_PROFILE, codecProfileAndLevel.first);
}
}
// Set codec max values.
mediaFormat.setInteger(MediaFormat.KEY_MAX_WIDTH, codecMaxValues.width);
mediaFormat.setInteger(MediaFormat.KEY_MAX_HEIGHT, codecMaxValues.height);
MediaFormatUtil.maybeSetInteger(
mediaFormat, MediaFormat.KEY_MAX_INPUT_SIZE, codecMaxValues.inputSize);
// Set codec configuration values.
if (Util.SDK_INT >= 23) {
mediaFormat.setInteger(MediaFormat.KEY_PRIORITY, 0 /* realtime priority */);
if (codecOperatingRate != CODEC_OPERATING_RATE_UNSET) {
mediaFormat.setFloat(MediaFormat.KEY_OPERATING_RATE, codecOperatingRate);
}
}
if (deviceNeedsNoPostProcessWorkaround) {
mediaFormat.setInteger("no-post-process", 1);
mediaFormat.setInteger("auto-frc", 0);
}
if (tunnelingAudioSessionId != C.AUDIO_SESSION_ID_UNSET) {
configureTunnelingV21(mediaFormat, tunnelingAudioSessionId);
}
return mediaFormat;
}
/**
* Returns {@link CodecMaxValues} suitable for configuring a codec for {@code format} in a way
* that will allow possible adaptation to other compatible formats in {@code streamFormats}.
*
* @param codecInfo Information about the {@link MediaCodec} being configured.
* @param format The {@link Format} for which the codec is being configured.
* @param streamFormats The possible stream formats.
* @return Suitable {@link CodecMaxValues}.
*/
protected CodecMaxValues getCodecMaxValues(
MediaCodecInfo codecInfo, Format format, Format[] streamFormats) {
int maxWidth = format.width;
int maxHeight = format.height;
int maxInputSize = getMaxInputSize(codecInfo, format);
if (streamFormats.length == 1) {
// The single entry in streamFormats must correspond to the format for which the codec is
// being configured.
if (maxInputSize != Format.NO_VALUE) {
int codecMaxInputSize =
getCodecMaxInputSize(codecInfo, format.sampleMimeType, format.width, format.height);
if (codecMaxInputSize != Format.NO_VALUE) {
// Scale up the initial video decoder maximum input size so playlist item transitions with
// small increases in maximum sample size don't require reinitialization. This only makes
// a difference if the exact maximum sample sizes are known from the container.
int scaledMaxInputSize =
(int) (maxInputSize * INITIAL_FORMAT_MAX_INPUT_SIZE_SCALE_FACTOR);
// Avoid exceeding the maximum expected for the codec.
maxInputSize = min(scaledMaxInputSize, codecMaxInputSize);
}
}
return new CodecMaxValues(maxWidth, maxHeight, maxInputSize);
}
boolean haveUnknownDimensions = false;
for (Format streamFormat : streamFormats) {
if (format.colorInfo != null && streamFormat.colorInfo == null) {
// streamFormat likely has incomplete color information. Copy the complete color information
// from format to avoid codec re-use being ruled out for only this reason.
streamFormat = streamFormat.buildUpon().setColorInfo(format.colorInfo).build();
}
if (codecInfo.canKeepCodec(format, streamFormat) != KEEP_CODEC_RESULT_NO) {
haveUnknownDimensions |=
(streamFormat.width == Format.NO_VALUE || streamFormat.height == Format.NO_VALUE);
maxWidth = max(maxWidth, streamFormat.width);
maxHeight = max(maxHeight, streamFormat.height);
maxInputSize = max(maxInputSize, getMaxInputSize(codecInfo, streamFormat));
}
}
if (haveUnknownDimensions) {
Log.w(TAG, "Resolutions unknown. Codec max resolution: " + maxWidth + "x" + maxHeight);
Point codecMaxSize = getCodecMaxSize(codecInfo, format);
if (codecMaxSize != null) {
maxWidth = max(maxWidth, codecMaxSize.x);
maxHeight = max(maxHeight, codecMaxSize.y);
maxInputSize =
max(
maxInputSize,
getCodecMaxInputSize(codecInfo, format.sampleMimeType, maxWidth, maxHeight));
Log.w(TAG, "Codec max resolution adjusted to: " + maxWidth + "x" + maxHeight);
}
}
return new CodecMaxValues(maxWidth, maxHeight, maxInputSize);
}
@Override
protected MediaCodecDecoderException createDecoderException(
Throwable cause, @Nullable MediaCodecInfo codecInfo) {
return new MediaCodecVideoDecoderException(cause, codecInfo, surface);
}
/**
* Returns a maximum video size to use when configuring a codec for {@code format} in a way that
* will allow possible adaptation to other compatible formats that are expected to have the same
* aspect ratio, but whose sizes are unknown.
*
* @param codecInfo Information about the {@link MediaCodec} being configured.
* @param format The {@link Format} for which the codec is being configured.
* @return The maximum video size to use, or null if the size of {@code format} should be used.
*/
private static Point getCodecMaxSize(MediaCodecInfo codecInfo, Format format) {
boolean isVerticalVideo = format.height > format.width;
int formatLongEdgePx = isVerticalVideo ? format.height : format.width;
int formatShortEdgePx = isVerticalVideo ? format.width : format.height;
float aspectRatio = (float) formatShortEdgePx / formatLongEdgePx;
for (int longEdgePx : STANDARD_LONG_EDGE_VIDEO_PX) {
int shortEdgePx = (int) (longEdgePx * aspectRatio);
if (longEdgePx <= formatLongEdgePx || shortEdgePx <= formatShortEdgePx) {
// Don't return a size not larger than the format for which the codec is being configured.
return null;
} else if (Util.SDK_INT >= 21) {
Point alignedSize = codecInfo.alignVideoSizeV21(isVerticalVideo ? shortEdgePx : longEdgePx,
isVerticalVideo ? longEdgePx : shortEdgePx);
float frameRate = format.frameRate;
if (codecInfo.isVideoSizeAndRateSupportedV21(alignedSize.x, alignedSize.y, frameRate)) {
return alignedSize;
}
} else {
try {
// Conservatively assume the codec requires 16px width and height alignment.
longEdgePx = Util.ceilDivide(longEdgePx, 16) * 16;
shortEdgePx = Util.ceilDivide(shortEdgePx, 16) * 16;
if (longEdgePx * shortEdgePx <= MediaCodecUtil.maxH264DecodableFrameSize()) {
return new Point(
isVerticalVideo ? shortEdgePx : longEdgePx,
isVerticalVideo ? longEdgePx : shortEdgePx);
}
} catch (DecoderQueryException e) {
// We tried our best. Give up!
return null;
}
}
}
return null;
}
/**
* Returns a maximum input buffer size for a given {@link MediaCodec} and {@link Format}.
*
* @param codecInfo Information about the {@link MediaCodec} being configured.
* @param format The format.
* @return A maximum input buffer size in bytes, or {@link Format#NO_VALUE} if a maximum could not
* be determined.
*/
protected static int getMaxInputSize(MediaCodecInfo codecInfo, Format format) {
if (format.maxInputSize != Format.NO_VALUE) {
// The format defines an explicit maximum input size. Add the total size of initialization
// data buffers, as they may need to be queued in the same input buffer as the largest sample.
int totalInitializationDataSize = 0;
int initializationDataCount = format.initializationData.size();
for (int i = 0; i < initializationDataCount; i++) {
totalInitializationDataSize += format.initializationData.get(i).length;
}
return format.maxInputSize + totalInitializationDataSize;
} else {
// Calculated maximum input sizes are overestimates, so it's not necessary to add the size of
// initialization data.
return getCodecMaxInputSize(codecInfo, format.sampleMimeType, format.width, format.height);
}
}
/**
* Returns a maximum input size for a given codec, MIME type, width and height.
*
* @param codecInfo Information about the {@link MediaCodec} being configured.
* @param sampleMimeType The format mime type.
* @param width The width in pixels.
* @param height The height in pixels.
* @return A maximum input size in bytes, or {@link Format#NO_VALUE} if a maximum could not be
* determined.
*/
private static int getCodecMaxInputSize(
MediaCodecInfo codecInfo, String sampleMimeType, int width, int height) {
if (width == Format.NO_VALUE || height == Format.NO_VALUE) {
// We can't infer a maximum input size without video dimensions.
return Format.NO_VALUE;
}
// Attempt to infer a maximum input size from the format.
int maxPixels;
int minCompressionRatio;
switch (sampleMimeType) {
case MimeTypes.VIDEO_H263:
case MimeTypes.VIDEO_MP4V:
maxPixels = width * height;
minCompressionRatio = 2;
break;
case MimeTypes.VIDEO_H264:
if ("BRAVIA 4K 2015".equals(Util.MODEL) // Sony Bravia 4K
|| ("Amazon".equals(Util.MANUFACTURER)
&& ("KFSOWI".equals(Util.MODEL) // Kindle Soho
|| ("AFTS".equals(Util.MODEL) && codecInfo.secure)))) { // Fire TV Gen 2
// Use the default value for cases where platform limitations may prevent buffers of the
// calculated maximum input size from being allocated.
return Format.NO_VALUE;
}
// Round up width/height to an integer number of macroblocks.
maxPixels = Util.ceilDivide(width, 16) * Util.ceilDivide(height, 16) * 16 * 16;
minCompressionRatio = 2;
break;
case MimeTypes.VIDEO_VP8:
// VPX does not specify a ratio so use the values from the platform's SoftVPX.cpp.
maxPixels = width * height;
minCompressionRatio = 2;
break;
case MimeTypes.VIDEO_H265:
case MimeTypes.VIDEO_VP9:
maxPixels = width * height;
minCompressionRatio = 4;
break;
default:
// Leave the default max input size.
return Format.NO_VALUE;
}
// Estimate the maximum input size assuming three channel 4:2:0 subsampled input frames.
return (maxPixels * 3) / (2 * minCompressionRatio);
}
/**
* Returns whether the device is known to do post processing by default that isn't compatible with
* ExoPlayer.
*
* @return Whether the device is known to do post processing by default that isn't compatible with
* ExoPlayer.
*/
private static boolean deviceNeedsNoPostProcessWorkaround() {
// Nvidia devices prior to M try to adjust the playback rate to better map the frame-rate of
// content to the refresh rate of the display. For example playback of 23.976fps content is
// adjusted to play at 1.001x speed when the output display is 60Hz. Unfortunately the
// implementation causes ExoPlayer's reported playback position to drift out of sync. Captions
// also lose sync [Internal: b/26453592]. Even after M, the devices may apply post processing
// operations that can modify frame output timestamps, which is incompatible with ExoPlayer's
// logic for skipping decode-only frames.
return "NVIDIA".equals(Util.MANUFACTURER);
}
/*
* TODO:
*
* 1. Validate that Android device certification now ensures correct behavior, and add a
* corresponding SDK_INT upper bound for applying the workaround (probably SDK_INT < 26).
* 2. Determine a complete list of affected devices.
* 3. Some of the devices in this list only fail to support setOutputSurface when switching from
* a SurfaceView provided Surface to a Surface of another type (e.g. TextureView/DummySurface),
* and vice versa. One hypothesis is that setOutputSurface fails when the surfaces have
* different pixel formats. If we can find a way to query the Surface instances to determine
* whether this case applies, then we'll be able to provide a more targeted workaround.
*/
/**
* Returns whether the codec is known to implement {@link MediaCodec#setOutputSurface(Surface)}
* incorrectly.
*
* <p>If true is returned then we fall back to releasing and re-instantiating the codec instead.
*
* @param name The name of the codec.
* @return True if the device is known to implement {@link MediaCodec#setOutputSurface(Surface)}
* incorrectly.
*/
protected boolean codecNeedsSetOutputSurfaceWorkaround(String name) {
if (name.startsWith("OMX.google")) {
// Google OMX decoders are not known to have this issue on any API level.
return false;
}
synchronized (MediaCodecVideoRenderer.class) {
if (!evaluatedDeviceNeedsSetOutputSurfaceWorkaround) {
deviceNeedsSetOutputSurfaceWorkaround = evaluateDeviceNeedsSetOutputSurfaceWorkaround();
evaluatedDeviceNeedsSetOutputSurfaceWorkaround = true;
}
}
return deviceNeedsSetOutputSurfaceWorkaround;
}
protected Surface getSurface() {
return surface;
}
protected static final class CodecMaxValues {
public final int width;
public final int height;
public final int inputSize;
public CodecMaxValues(int width, int height, int inputSize) {
this.width = width;
this.height = height;
this.inputSize = inputSize;
}
}
private static boolean evaluateDeviceNeedsSetOutputSurfaceWorkaround() {
if (Util.SDK_INT <= 28) {
// Workaround for MiTV devices which have been observed broken up to API 28.
// https://github.com/google/ExoPlayer/issues/5169,
// https://github.com/google/ExoPlayer/issues/6899.
// https://github.com/google/ExoPlayer/issues/8014.
switch (Util.DEVICE) {
case "dangal":
case "dangalUHD":
case "dangalFHD":
case "magnolia":
case "machuca":
return true;
default:
break; // Do nothing.
}
}
if (Util.SDK_INT <= 27 && "HWEML".equals(Util.DEVICE)) {
// Workaround for Huawei P20:
// https://github.com/google/ExoPlayer/issues/4468#issuecomment-459291645.
return true;
}
if (Util.SDK_INT <= 26) {
// In general, devices running API level 27 or later should be unaffected unless observed
// otherwise. Enable the workaround on a per-device basis. Works around:
// https://github.com/google/ExoPlayer/issues/3236,
// https://github.com/google/ExoPlayer/issues/3355,
// https://github.com/google/ExoPlayer/issues/3439,
// https://github.com/google/ExoPlayer/issues/3724,
// https://github.com/google/ExoPlayer/issues/3835,
// https://github.com/google/ExoPlayer/issues/4006,
// https://github.com/google/ExoPlayer/issues/4084,
// https://github.com/google/ExoPlayer/issues/4104,
// https://github.com/google/ExoPlayer/issues/4134,
// https://github.com/google/ExoPlayer/issues/4315,
// https://github.com/google/ExoPlayer/issues/4419,
// https://github.com/google/ExoPlayer/issues/4460,
// https://github.com/google/ExoPlayer/issues/4468,
// https://github.com/google/ExoPlayer/issues/5312,
// https://github.com/google/ExoPlayer/issues/6503.
// https://github.com/google/ExoPlayer/issues/8014,
// https://github.com/google/ExoPlayer/pull/8030.
switch (Util.DEVICE) {
case "1601":
case "1713":
case "1714":
case "601LV":
case "602LV":
case "A10-70F":
case "A10-70L":
case "A1601":
case "A2016a40":
case "A7000-a":
case "A7000plus":
case "A7010a48":
case "A7020a48":
case "AquaPowerM":
case "ASUS_X00AD_2":
case "Aura_Note_2":
case "b5":
case "BLACK-1X":
case "BRAVIA_ATV2":
case "BRAVIA_ATV3_4K":
case "C1":
case "ComioS1":
case "CP8676_I02":
case "CPH1609":
case "CPH1715":
case "CPY83_I00":
case "cv1":
case "cv3":
case "deb":
case "DM-01K":
case "E5643":
case "ELUGA_A3_Pro":
case "ELUGA_Note":
case "ELUGA_Prim":
case "ELUGA_Ray_X":
case "EverStar_S":
case "F01H":
case "F01J":
case "F02H":
case "F03H":
case "F04H":
case "F04J":
case "F3111":
case "F3113":
case "F3116":
case "F3211":
case "F3213":
case "F3215":
case "F3311":
case "flo":
case "fugu":
case "GiONEE_CBL7513":
case "GiONEE_GBL7319":
case "GIONEE_GBL7360":
case "GIONEE_SWW1609":
case "GIONEE_SWW1627":
case "GIONEE_SWW1631":
case "GIONEE_WBL5708":
case "GIONEE_WBL7365":
case "GIONEE_WBL7519":
case "griffin":
case "htc_e56ml_dtul":
case "hwALE-H":
case "HWBLN-H":
case "HWCAM-H":
case "HWVNS-H":
case "HWWAS-H":
case "i9031":
case "iball8735_9806":
case "Infinix-X572":
case "iris60":
case "itel_S41":
case "j2xlteins":
case "JGZ":
case "K50a40":
case "kate":
case "l5460":
case "le_x6":
case "LS-5017":
case "M04":
case "M5c":
case "manning":
case "marino_f":
case "MEIZU_M5":
case "mh":
case "mido":
case "MX6":
case "namath":
case "nicklaus_f":
case "NX541J":
case "NX573J":
case "OnePlus5T":
case "p212":
case "P681":
case "P85":
case "pacificrim":
case "panell_d":
case "panell_dl":
case "panell_ds":
case "panell_dt":
case "PB2-670M":
case "PGN528":
case "PGN610":
case "PGN611":
case "Phantom6":
case "Pixi4-7_3G":
case "Pixi5-10_4G":
case "PLE":
case "PRO7S":
case "Q350":
case "Q4260":
case "Q427":
case "Q4310":
case "Q5":
case "QM16XE_U":
case "QX1":
case "RAIJIN":
case "santoni":
case "Slate_Pro":
case "SVP-DTV15":
case "s905x018":
case "taido_row":
case "TB3-730F":
case "TB3-730X":
case "TB3-850F":
case "TB3-850M":
case "tcl_eu":
case "V1":
case "V23GB":
case "V5":
case "vernee_M5":
case "watson":
case "whyred":
case "woods_f":
case "woods_fn":
case "X3_HK":
case "XE2X":
case "XT1663":
case "Z12_PRO":
case "Z80":
return true;
default:
break; // Do nothing.
}
switch (Util.MODEL) {
case "AFTA":
case "AFTN":
case "JSN-L21":
return true;
default:
break; // Do nothing.
}
}
return false;
}
@RequiresApi(23)
private final class OnFrameRenderedListenerV23
implements MediaCodec.OnFrameRenderedListener, Handler.Callback {
private static final int HANDLE_FRAME_RENDERED = 0;
private final Handler handler;
public OnFrameRenderedListenerV23(MediaCodec codec) {
handler = Util.createHandlerForCurrentLooper(/* callback= */ this);
codec.setOnFrameRenderedListener(/* listener= */ this, handler);
}
@Override
public void onFrameRendered(MediaCodec codec, long presentationTimeUs, long nanoTime) {
// Workaround bug in MediaCodec that causes deadlock if you call directly back into the
// MediaCodec from this listener method.
// Deadlock occurs because MediaCodec calls this listener method holding a lock,
// which may also be required by calls made back into the MediaCodec.
// This was fixed in https://android-review.googlesource.com/1156807.
//
// The workaround queues the event for subsequent processing, where the lock will not be held.
if (Util.SDK_INT < 30) {
Message message =
Message.obtain(
handler,
/* what= */ HANDLE_FRAME_RENDERED,
/* arg1= */ (int) (presentationTimeUs >> 32),
/* arg2= */ (int) presentationTimeUs);
handler.sendMessageAtFrontOfQueue(message);
} else {
handleFrameRendered(presentationTimeUs);
}
}
@Override
public boolean handleMessage(Message message) {
switch (message.what) {
case HANDLE_FRAME_RENDERED:
handleFrameRendered(Util.toLong(message.arg1, message.arg2));
return true;
default:
return false;
}
}
private void handleFrameRendered(long presentationTimeUs) {
if (this != tunnelingOnFrameRenderedListener) {
// Stale event.
return;
}
if (presentationTimeUs == TUNNELING_EOS_PRESENTATION_TIME_US) {
onProcessedTunneledEndOfStream();
} else {
try {
onProcessedTunneledBuffer(presentationTimeUs);
} catch (ExoPlaybackException e) {
setPendingPlaybackException(e);
}
}
}
}
}
| Short term fix for setFrameRate ISE when surface is not valid
PiperOrigin-RevId: 340314496
| library/core/src/main/java/com/google/android/exoplayer2/video/MediaCodecVideoRenderer.java | Short term fix for setFrameRate ISE when surface is not valid |
|
Java | apache-2.0 | d4df939cd194a3ce507a7ff7f24ba9703b6cc49d | 0 | ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,dslomov/intellij-community,joewalnes/idea-community,caot/intellij-community,da1z/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,consulo/consulo,adedayo/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,semonte/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,blademainer/intellij-community,hurricup/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,ryano144/intellij-community,da1z/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,joewalnes/idea-community,michaelgallacher/intellij-community,petteyg/intellij-community,fitermay/intellij-community,joewalnes/idea-community,holmes/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,xfournet/intellij-community,allotria/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,retomerz/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,fnouama/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,xfournet/intellij-community,izonder/intellij-community,suncycheng/intellij-community,slisson/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,consulo/consulo,suncycheng/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,retomerz/intellij-community,holmes/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,caot/intellij-community,samthor/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,kool79/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,caot/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,semonte/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,joewalnes/idea-community,orekyuu/intellij-community,joewalnes/idea-community,diorcety/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,blademainer/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,da1z/intellij-community,fitermay/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,asedunov/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,ernestp/consulo,tmpgit/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,FHannes/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,vladmm/intellij-community,slisson/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,holmes/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,ernestp/consulo,vladmm/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,allotria/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,da1z/intellij-community,xfournet/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,consulo/consulo,signed/intellij-community,FHannes/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,kdwink/intellij-community,diorcety/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,signed/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,blademainer/intellij-community,da1z/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,apixandru/intellij-community,adedayo/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,allotria/intellij-community,signed/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,da1z/intellij-community,izonder/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,supersven/intellij-community,clumsy/intellij-community,slisson/intellij-community,kdwink/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,caot/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,signed/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,ibinti/intellij-community,allotria/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,ernestp/consulo,kool79/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,adedayo/intellij-community,kool79/intellij-community,slisson/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,joewalnes/idea-community,ivan-fedorov/intellij-community,FHannes/intellij-community,ryano144/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,ernestp/consulo,petteyg/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,apixandru/intellij-community,vladmm/intellij-community,apixandru/intellij-community,petteyg/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,allotria/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,asedunov/intellij-community,caot/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,signed/intellij-community,samthor/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,kdwink/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,signed/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,joewalnes/idea-community,ibinti/intellij-community,fitermay/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,clumsy/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,amith01994/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,kool79/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,fnouama/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,samthor/intellij-community,robovm/robovm-studio,joewalnes/idea-community,signed/intellij-community,jagguli/intellij-community,vladmm/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,caot/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,jagguli/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,kool79/intellij-community,da1z/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,allotria/intellij-community,signed/intellij-community,holmes/intellij-community,supersven/intellij-community,clumsy/intellij-community,kool79/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,holmes/intellij-community,izonder/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,robovm/robovm-studio,asedunov/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,ernestp/consulo,apixandru/intellij-community,wreckJ/intellij-community,supersven/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,blademainer/intellij-community,joewalnes/idea-community,clumsy/intellij-community,salguarnieri/intellij-community,caot/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,kdwink/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,supersven/intellij-community,holmes/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,supersven/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,consulo/consulo,jagguli/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,slisson/intellij-community,caot/intellij-community,holmes/intellij-community,holmes/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,kdwink/intellij-community,ernestp/consulo,diorcety/intellij-community,asedunov/intellij-community,adedayo/intellij-community,da1z/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,signed/intellij-community,FHannes/intellij-community,consulo/consulo,youdonghai/intellij-community,semonte/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,akosyakov/intellij-community,signed/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,fitermay/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,caot/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,retomerz/intellij-community,caot/intellij-community,jagguli/intellij-community,allotria/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,blademainer/intellij-community,hurricup/intellij-community,signed/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,izonder/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,slisson/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,kdwink/intellij-community,izonder/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,kool79/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,vladmm/intellij-community,xfournet/intellij-community,robovm/robovm-studio,ryano144/intellij-community,ryano144/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,adedayo/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,semonte/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,consulo/consulo | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vcs.update;
import com.intellij.history.Label;
import com.intellij.history.LocalHistory;
import com.intellij.history.LocalHistoryAction;
import com.intellij.ide.errorTreeView.HotfixData;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ex.ProjectManagerEx;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vcs.actions.AbstractVcsAction;
import com.intellij.openapi.vcs.actions.VcsContext;
import com.intellij.openapi.vcs.changes.RemoteRevisionsCache;
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager;
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManagerImpl;
import com.intellij.openapi.vcs.changes.committed.CommittedChangesAdapter;
import com.intellij.openapi.vcs.changes.committed.CommittedChangesCache;
import com.intellij.openapi.vcs.changes.committed.IntoSelfVirtualFileConvertor;
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager;
import com.intellij.openapi.vcs.ex.ProjectLevelVcsManagerEx;
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.ui.OptionsDialog;
import com.intellij.vcsUtil.VcsUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.*;
public abstract class AbstractCommonUpdateAction extends AbstractVcsAction {
private final static Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.update.AbstractCommonUpdateAction");
private final ActionInfo myActionInfo;
private final ScopeInfo myScopeInfo;
protected AbstractCommonUpdateAction(ActionInfo actionInfo, ScopeInfo scopeInfo) {
myActionInfo = actionInfo;
myScopeInfo = scopeInfo;
}
private String getCompleteActionName(VcsContext dataContext) {
return myActionInfo.getActionName(myScopeInfo.getScopeName(dataContext, myActionInfo));
}
protected void actionPerformed(final VcsContext context) {
final Project project = context.getProject();
boolean showUpdateOptions = myActionInfo.showOptions(project);
if (project != null) {
try {
final FilePath[] filePaths = myScopeInfo.getRoots(context, myActionInfo);
final FilePath[] roots = filterDescindingFiles(filterRoots(filePaths, context), project);
if (roots.length == 0) {
return;
}
final Map<AbstractVcs, Collection<FilePath>> vcsToVirtualFiles = createVcsToFilesMap(roots, project);
if (showUpdateOptions || OptionsDialog.shiftIsPressed(context.getModifiers())) {
showOptionsDialog(vcsToVirtualFiles, project, context);
}
for (AbstractVcs vcs : vcsToVirtualFiles.keySet()) {
final UpdateEnvironment updateEnvironment = myActionInfo.getEnvironment(vcs);
if ((updateEnvironment != null) && (! updateEnvironment.validateOptions(vcsToVirtualFiles.get(vcs)))) {
// messages already shown
return;
}
}
if (ApplicationManager.getApplication().isDispatchThread()) {
ApplicationManager.getApplication().saveAll();
}
Task.Backgroundable task = new Updater(project, roots, vcsToVirtualFiles);
ProgressManager.getInstance().run(task);
}
catch (ProcessCanceledException e1) {
//ignore
}
}
}
private boolean canGroupByChangelist(final Set<AbstractVcs> abstractVcses) {
if (myActionInfo.canGroupByChangelist()) {
for(AbstractVcs vcs: abstractVcses) {
if (vcs.getCachingCommittedChangesProvider() != null) {
return true;
}
}
}
return false;
}
private static boolean someSessionWasCanceled(List<UpdateSession> updateSessions) {
for (UpdateSession updateSession : updateSessions) {
if (updateSession.isCanceled()) {
return true;
}
}
return false;
}
private static String getAllFilesAreUpToDateMessage(FilePath[] roots) {
if (roots.length == 1 && !roots[0].isDirectory()) {
return VcsBundle.message("message.text.file.is.up.to.date");
}
else {
return VcsBundle.message("message.text.all.files.are.up.to.date");
}
}
private void showOptionsDialog(final Map<AbstractVcs, Collection<FilePath>> updateEnvToVirtualFiles, final Project project,
final VcsContext dataContext) {
LinkedHashMap<Configurable, AbstractVcs> envToConfMap = createConfigurableToEnvMap(updateEnvToVirtualFiles);
if (!envToConfMap.isEmpty()) {
UpdateOrStatusOptionsDialog dialogOrStatus = myActionInfo.createOptionsDialog(project, envToConfMap,
myScopeInfo.getScopeName(dataContext,
myActionInfo));
dialogOrStatus.show();
if (!dialogOrStatus.isOK()) {
throw new ProcessCanceledException();
}
}
}
private LinkedHashMap<Configurable, AbstractVcs> createConfigurableToEnvMap(Map<AbstractVcs, Collection<FilePath>> updateEnvToVirtualFiles) {
LinkedHashMap<Configurable, AbstractVcs> envToConfMap = new LinkedHashMap<Configurable, AbstractVcs>();
for (AbstractVcs vcs : updateEnvToVirtualFiles.keySet()) {
Configurable configurable = myActionInfo.getEnvironment(vcs).createConfigurable(updateEnvToVirtualFiles.get(vcs));
if (configurable != null) {
envToConfMap.put(configurable, vcs);
}
}
return envToConfMap;
}
private Map<AbstractVcs,Collection<FilePath>> createVcsToFilesMap(FilePath[] roots, Project project) {
HashMap<AbstractVcs, Collection<FilePath>> resultPrep = new HashMap<AbstractVcs, Collection<FilePath>>();
for (FilePath file : roots) {
AbstractVcs vcs = VcsUtil.getVcsFor(project, file);
if (vcs != null) {
UpdateEnvironment updateEnvironment = myActionInfo.getEnvironment(vcs);
if (updateEnvironment != null) {
if (!resultPrep.containsKey(vcs)) resultPrep.put(vcs, new HashSet<FilePath>());
resultPrep.get(vcs).add(file);
}
}
}
final Map<AbstractVcs, Collection<FilePath>> result = new HashMap<AbstractVcs, Collection<FilePath>>();
for (Map.Entry<AbstractVcs, Collection<FilePath>> entry : resultPrep.entrySet()) {
final AbstractVcs vcs = entry.getKey();
final List<FilePath> paths = new ArrayList<FilePath>(entry.getValue());
final List<VirtualFile> files = ObjectsConvertor.convert(paths, ObjectsConvertor.FILEPATH_TO_VIRTUAL, ObjectsConvertor.NOT_NULL);
result.put(vcs, ObjectsConvertor.vf2fp(vcs.filterUniqueRoots(files, IntoSelfVirtualFileConvertor.getInstance())));
}
return result;
}
private static boolean containsParent(FilePath[] array, FilePath file) {
for (FilePath virtualFile : array) {
if (virtualFile == file) continue;
if (VfsUtil.isAncestor(virtualFile.getIOFile(), file.getIOFile(), false)) return true;
}
return false;
}
@NotNull
private FilePath[] filterRoots(FilePath[] roots, VcsContext vcsContext) {
final ArrayList<FilePath> result = new ArrayList<FilePath>();
final Project project = vcsContext.getProject();
for (FilePath file : roots) {
AbstractVcs vcs = VcsUtil.getVcsFor(project, file);
if (vcs != null) {
if (!myScopeInfo.filterExistsInVcs() || AbstractVcs.fileInVcsByFileStatus(project, file)) {
UpdateEnvironment updateEnvironment = myActionInfo.getEnvironment(vcs);
if (updateEnvironment != null) {
result.add(file);
}
}
else {
final VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile != null && virtualFile.isDirectory()) {
final VirtualFile[] vcsRoots = ProjectLevelVcsManager.getInstance(vcsContext.getProject()).getAllVersionedRoots();
for(VirtualFile vcsRoot: vcsRoots) {
if (VfsUtil.isAncestor(virtualFile, vcsRoot, false)) {
result.add(file);
}
}
}
}
}
}
return result.toArray(new FilePath[result.size()]);
}
protected abstract boolean filterRootsBeforeAction();
protected void update(VcsContext vcsContext, Presentation presentation) {
Project project = vcsContext.getProject();
if (project != null) {
String actionName = getCompleteActionName(vcsContext);
if (myActionInfo.showOptions(project) || OptionsDialog.shiftIsPressed(vcsContext.getModifiers())) {
actionName += "...";
}
presentation.setText(actionName);
presentation.setVisible(true);
presentation.setEnabled(true);
if (supportingVcsesAreEmpty(vcsContext.getProject(), myActionInfo)) {
presentation.setVisible(false);
presentation.setEnabled(false);
}
if (filterRootsBeforeAction()) {
FilePath[] roots = filterRoots(myScopeInfo.getRoots(vcsContext, myActionInfo), vcsContext);
if (roots.length == 0) {
presentation.setVisible(false);
presentation.setEnabled(false);
}
}
if (presentation.isVisible() && presentation.isEnabled() &&
ProjectLevelVcsManager.getInstance(project).isBackgroundVcsOperationRunning()) {
presentation.setEnabled(false);
}
} else {
presentation.setVisible(false);
presentation.setEnabled(false);
}
}
protected boolean forceSyncUpdate(final AnActionEvent e) {
return true;
}
private static boolean supportingVcsesAreEmpty(final Project project, final ActionInfo actionInfo) {
if (project == null) return true;
final AbstractVcs[] allActiveVcss = ProjectLevelVcsManager.getInstance(project).getAllActiveVcss();
for (AbstractVcs activeVcs : allActiveVcss) {
if (actionInfo.getEnvironment(activeVcs) != null) return false;
}
return true;
}
private class Updater extends Task.Backgroundable {
private final Project myProject;
private final ProjectLevelVcsManagerEx myProjectLevelVcsManager;
private UpdatedFiles myUpdatedFiles;
private final FilePath[] myRoots;
private final Map<AbstractVcs, Collection<FilePath>> myVcsToVirtualFiles;
private final Map<HotfixData, List<VcsException>> myGroupedExceptions;
private final List<UpdateSession> myUpdateSessions;
private int myUpdateNumber;
// vcs name, context object
private final Map<AbstractVcs, SequentialUpdatesContext> myContextInfo;
private VcsDirtyScopeManager myDirtyScopeManager;
private Label myBefore;
private Label myAfter;
public Updater(final Project project, final FilePath[] roots, final Map<AbstractVcs, Collection<FilePath>> vcsToVirtualFiles) {
super(project, getTemplatePresentation().getText(), true, VcsConfiguration.getInstance(project).getUpdateOption());
myProject = project;
myProjectLevelVcsManager = ProjectLevelVcsManagerEx.getInstanceEx(project);
myDirtyScopeManager = VcsDirtyScopeManager.getInstance(myProject);
myRoots = roots;
myVcsToVirtualFiles = vcsToVirtualFiles;
myUpdatedFiles = UpdatedFiles.create();
myGroupedExceptions = new HashMap<HotfixData, List<VcsException>>();
myUpdateSessions = new ArrayList<UpdateSession>();
// create from outside without any context; context is created by vcses
myContextInfo = new HashMap<AbstractVcs, SequentialUpdatesContext>();
myUpdateNumber = 1;
}
private void reset() {
myUpdatedFiles = UpdatedFiles.create();
myGroupedExceptions.clear();
myUpdateSessions.clear();
++ myUpdateNumber;
}
private void suspendIfNeeded() {
if (! myActionInfo.canChangeFileStatus()) {
// i.e. for update but not for integrate or status
((VcsDirtyScopeManagerImpl) myDirtyScopeManager).suspendMe();
}
}
private void releaseIfNeeded() {
if (! myActionInfo.canChangeFileStatus()) {
// i.e. for update but not for integrate or status
((VcsDirtyScopeManagerImpl) myDirtyScopeManager).reanimate();
}
}
public void run(@NotNull final ProgressIndicator indicator) {
suspendIfNeeded();
try {
runImpl(indicator);
} catch (Throwable t) {
releaseIfNeeded();
if (t instanceof Error) {
throw ((Error) t);
} else if (t instanceof RuntimeException) {
throw ((RuntimeException) t);
}
throw new RuntimeException(t);
}
}
private void runImpl(@NotNull final ProgressIndicator indicator) {
ProjectManagerEx.getInstanceEx().blockReloadingProjectOnExternalChanges();
myProjectLevelVcsManager.startBackgroundVcsOperation();
myBefore = LocalHistory.putSystemLabel(myProject, "Before update");
ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
try {
int toBeProcessed = myVcsToVirtualFiles.size();
int processed = 0;
for (AbstractVcs vcs : myVcsToVirtualFiles.keySet()) {
final UpdateEnvironment updateEnvironment = myActionInfo.getEnvironment(vcs);
updateEnvironment.fillGroups(myUpdatedFiles);
Collection<FilePath> files = myVcsToVirtualFiles.get(vcs);
final SequentialUpdatesContext context = myContextInfo.get(vcs);
final Ref<SequentialUpdatesContext> refContext = new Ref<SequentialUpdatesContext>(context);
UpdateSession updateSession =
updateEnvironment.updateDirectories(files.toArray(new FilePath[files.size()]), myUpdatedFiles, progressIndicator, refContext);
myContextInfo.put(vcs, refContext.get());
processed++;
if (progressIndicator != null) {
progressIndicator.setFraction((double)processed / (double)toBeProcessed);
progressIndicator.setText2("");
}
final List<VcsException> exceptionList = updateSession.getExceptions();
gatherExceptions(vcs, exceptionList);
myUpdateSessions.add(updateSession);
}
} finally {
try {
if (progressIndicator != null) {
progressIndicator.setText(VcsBundle.message("progress.text.synchronizing.files"));
progressIndicator.setText2("");
}
doVfsRefresh();
} finally {
myAfter = LocalHistory.putSystemLabel(myProject, "After update");
myProjectLevelVcsManager.stopBackgroundVcsOperation();
}
}
}
private void gatherExceptions(final AbstractVcs vcs, final List<VcsException> exceptionList) {
final VcsExceptionsHotFixer fixer = vcs.getVcsExceptionsHotFixer();
if (fixer == null) {
putExceptions(null, exceptionList);
} else {
putExceptions(fixer.groupExceptions(ActionType.update, exceptionList));
}
}
private void putExceptions(final Map<HotfixData, List<VcsException>> map) {
for (Map.Entry<HotfixData, List<VcsException>> entry : map.entrySet()) {
putExceptions(entry.getKey(), entry.getValue());
}
}
private void putExceptions(final HotfixData key, @NotNull final List<VcsException> list) {
if (list.isEmpty()) return;
List<VcsException> exceptionList = myGroupedExceptions.get(key);
if (exceptionList == null) {
exceptionList = new ArrayList<VcsException>();
myGroupedExceptions.put(key, exceptionList);
}
exceptionList.addAll(list);
}
private void doVfsRefresh() {
final String actionName = VcsBundle.message("local.history.update.from.vcs");
final LocalHistoryAction action = LocalHistory.startAction(myProject, actionName);
try {
LOG.info("Calling refresh files after update for roots: " + Arrays.toString(myRoots));
RefreshVFsSynchronously.updateAllChanged(myUpdatedFiles);
}
finally {
action.finish();
LocalHistory.putSystemLabel(myProject, actionName);
}
}
@Nullable
public NotificationInfo getNotificationInfo() {
StringBuffer text = new StringBuffer();
final List<FileGroup> groups = myUpdatedFiles.getTopLevelGroups();
for (FileGroup group : groups) {
appendGroup(text, group);
}
return new NotificationInfo("VCS Update", "VCS Update Finished", text.toString(), true);
}
private void appendGroup(final StringBuffer text, final FileGroup group) {
final int s = group.getFiles().size();
if (s > 0) {
if (text.length() > 0) text.append("\n");
text.append(s + " Files " + group.getUpdateName());
}
final List<FileGroup> list = group.getChildren();
for (FileGroup g : list) {
appendGroup(text, g);
}
}
public void onSuccess() {
try {
onSuccessImpl();
} finally {
releaseIfNeeded();
}
}
private void onSuccessImpl() {
if (myProject.isDisposed()) {
ProjectManagerEx.getInstanceEx().unblockReloadingProjectOnExternalChanges();
return;
}
boolean continueChain = false;
for (SequentialUpdatesContext context : myContextInfo.values()) {
continueChain |= context != null;
}
final boolean continueChainFinal = continueChain;
final boolean someSessionWasCancelled = someSessionWasCanceled(myUpdateSessions);
if (! someSessionWasCancelled) {
for (final UpdateSession updateSession : myUpdateSessions) {
updateSession.onRefreshFilesCompleted();
}
}
if (myActionInfo.canChangeFileStatus()) {
final List<VirtualFile> files = new ArrayList<VirtualFile>();
final RemoteRevisionsCache revisionsCache = RemoteRevisionsCache.getInstance(myProject);
revisionsCache.invalidate(myUpdatedFiles);
UpdateFilesHelper.iterateFileGroupFiles(myUpdatedFiles, new UpdateFilesHelper.Callback() {
public void onFile(final String filePath, final String groupId) {
@NonNls final String path = VfsUtil.pathToUrl(filePath.replace(File.separatorChar, '/'));
final VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(path);
if (file != null) {
files.add(file);
}
}
});
myDirtyScopeManager.filesDirty(files, null);
}
final boolean updateSuccess = (! someSessionWasCancelled) && (myGroupedExceptions.isEmpty());
if (! someSessionWasCancelled) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
if (myProject.isDisposed()) {
ProjectManagerEx.getInstanceEx().unblockReloadingProjectOnExternalChanges();
return;
}
if (! myGroupedExceptions.isEmpty()) {
if (continueChainFinal) {
gatherContextInterruptedMessages();
}
AbstractVcsHelper.getInstance(myProject).showErrors(myGroupedExceptions, VcsBundle.message("message.title.vcs.update.errors",
getTemplatePresentation().getText()));
}
else {
final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator != null) {
indicator.setText(VcsBundle.message("progress.text.updating.done"));
}
}
final boolean noMerged = myUpdatedFiles.getGroupById(FileGroup.MERGED_WITH_CONFLICT_ID).isEmpty();
if (myUpdatedFiles.isEmpty() && myGroupedExceptions.isEmpty()) {
ToolWindowManager.getInstance(myProject).notifyByBalloon(
ChangesViewContentManager.TOOLWINDOW_ID, MessageType.INFO, getAllFilesAreUpToDateMessage(myRoots));
}
else if (! myUpdatedFiles.isEmpty()) {
showUpdateTree(continueChainFinal && updateSuccess && noMerged);
final CommittedChangesCache cache = CommittedChangesCache.getInstance(myProject);
cache.processUpdatedFiles(myUpdatedFiles);
}
ProjectManagerEx.getInstanceEx().unblockReloadingProjectOnExternalChanges();
if (continueChainFinal && updateSuccess) {
if (!noMerged) {
showContextInterruptedError();
} else {
// trigger next update; for CVS when updating from several branvhes simultaneously
reset();
ProgressManager.getInstance().run(Updater.this);
}
}
}
});
} else if (continueChain) {
// since error
showContextInterruptedError();
ProjectManagerEx.getInstanceEx().unblockReloadingProjectOnExternalChanges();
}
}
private void showContextInterruptedError() {
gatherContextInterruptedMessages();
AbstractVcsHelper.getInstance(myProject).showErrors(myGroupedExceptions,
VcsBundle.message("message.title.vcs.update.errors", getTemplatePresentation().getText()));
}
private void gatherContextInterruptedMessages() {
for (Map.Entry<AbstractVcs, SequentialUpdatesContext> entry : myContextInfo.entrySet()) {
final SequentialUpdatesContext context = entry.getValue();
if (context == null) continue;
final VcsException exception = new VcsException(context.getMessageWhenInterruptedBeforeStart());
gatherExceptions(entry.getKey(), Collections.singletonList(exception));
}
}
private void showUpdateTree(final boolean willBeContinued) {
RestoreUpdateTree restoreUpdateTree = RestoreUpdateTree.getInstance(myProject);
restoreUpdateTree.registerUpdateInformation(myUpdatedFiles, myActionInfo);
final String text = getTemplatePresentation().getText() + ((willBeContinued || (myUpdateNumber > 1)) ? ("#" + myUpdateNumber) : "");
final UpdateInfoTree updateInfoTree = myProjectLevelVcsManager.showUpdateProjectInfo(myUpdatedFiles, text, myActionInfo);
updateInfoTree.setBefore(myBefore);
updateInfoTree.setAfter(myAfter);
// todo make temporal listener of changes reload
if (updateInfoTree != null) {
updateInfoTree.setCanGroupByChangeList(canGroupByChangelist(myVcsToVirtualFiles.keySet()));
final MessageBusConnection messageBusConnection = myProject.getMessageBus().connect();
messageBusConnection.subscribe(CommittedChangesCache.COMMITTED_TOPIC, new CommittedChangesAdapter() {
public void incomingChangesUpdated(final List<CommittedChangeList> receivedChanges) {
if (receivedChanges != null) {
updateInfoTree.setChangeLists(receivedChanges);
messageBusConnection.disconnect();
}
}
});
}
}
public void onCancel() {
onSuccess();
}
}
}
| platform/vcs-impl/src/com/intellij/openapi/vcs/update/AbstractCommonUpdateAction.java | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vcs.update;
import com.intellij.history.Label;
import com.intellij.history.LocalHistory;
import com.intellij.history.LocalHistoryAction;
import com.intellij.ide.errorTreeView.HotfixData;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ex.ProjectManagerEx;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vcs.actions.AbstractVcsAction;
import com.intellij.openapi.vcs.actions.VcsContext;
import com.intellij.openapi.vcs.changes.RemoteRevisionsCache;
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager;
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManagerImpl;
import com.intellij.openapi.vcs.changes.committed.CommittedChangesAdapter;
import com.intellij.openapi.vcs.changes.committed.CommittedChangesCache;
import com.intellij.openapi.vcs.changes.committed.IntoSelfVirtualFileConvertor;
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager;
import com.intellij.openapi.vcs.ex.ProjectLevelVcsManagerEx;
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.ui.OptionsDialog;
import com.intellij.vcsUtil.VcsUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.*;
public abstract class AbstractCommonUpdateAction extends AbstractVcsAction {
private final static Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.update.AbstractCommonUpdateAction");
private final ActionInfo myActionInfo;
private final ScopeInfo myScopeInfo;
protected AbstractCommonUpdateAction(ActionInfo actionInfo, ScopeInfo scopeInfo) {
myActionInfo = actionInfo;
myScopeInfo = scopeInfo;
}
private String getCompleteActionName(VcsContext dataContext) {
return myActionInfo.getActionName(myScopeInfo.getScopeName(dataContext, myActionInfo));
}
protected void actionPerformed(final VcsContext context) {
final Project project = context.getProject();
boolean showUpdateOptions = myActionInfo.showOptions(project);
if (project != null) {
try {
final FilePath[] filePaths = myScopeInfo.getRoots(context, myActionInfo);
final FilePath[] roots = filterDescindingFiles(filterRoots(filePaths, context), project);
if (roots.length == 0) {
return;
}
final Map<AbstractVcs, Collection<FilePath>> vcsToVirtualFiles = createVcsToFilesMap(roots, project);
if (showUpdateOptions || OptionsDialog.shiftIsPressed(context.getModifiers())) {
showOptionsDialog(vcsToVirtualFiles, project, context);
}
for (AbstractVcs vcs : vcsToVirtualFiles.keySet()) {
final UpdateEnvironment updateEnvironment = myActionInfo.getEnvironment(vcs);
if ((updateEnvironment != null) && (! updateEnvironment.validateOptions(vcsToVirtualFiles.get(vcs)))) {
// messages already shown
return;
}
}
if (ApplicationManager.getApplication().isDispatchThread()) {
ApplicationManager.getApplication().saveAll();
}
Task.Backgroundable task = new Updater(project, roots, vcsToVirtualFiles);
ProgressManager.getInstance().run(task);
}
catch (ProcessCanceledException e1) {
//ignore
}
}
}
private boolean canGroupByChangelist(final Set<AbstractVcs> abstractVcses) {
if (myActionInfo.canGroupByChangelist()) {
for(AbstractVcs vcs: abstractVcses) {
if (vcs.getCachingCommittedChangesProvider() != null) {
return true;
}
}
}
return false;
}
private static boolean someSessionWasCanceled(List<UpdateSession> updateSessions) {
for (UpdateSession updateSession : updateSessions) {
if (updateSession.isCanceled()) {
return true;
}
}
return false;
}
private static String getAllFilesAreUpToDateMessage(FilePath[] roots) {
if (roots.length == 1 && !roots[0].isDirectory()) {
return VcsBundle.message("message.text.file.is.up.to.date");
}
else {
return VcsBundle.message("message.text.all.files.are.up.to.date");
}
}
private void showOptionsDialog(final Map<AbstractVcs, Collection<FilePath>> updateEnvToVirtualFiles, final Project project,
final VcsContext dataContext) {
LinkedHashMap<Configurable, AbstractVcs> envToConfMap = createConfigurableToEnvMap(updateEnvToVirtualFiles);
if (!envToConfMap.isEmpty()) {
UpdateOrStatusOptionsDialog dialogOrStatus = myActionInfo.createOptionsDialog(project, envToConfMap,
myScopeInfo.getScopeName(dataContext,
myActionInfo));
dialogOrStatus.show();
if (!dialogOrStatus.isOK()) {
throw new ProcessCanceledException();
}
}
}
private LinkedHashMap<Configurable, AbstractVcs> createConfigurableToEnvMap(Map<AbstractVcs, Collection<FilePath>> updateEnvToVirtualFiles) {
LinkedHashMap<Configurable, AbstractVcs> envToConfMap = new LinkedHashMap<Configurable, AbstractVcs>();
for (AbstractVcs vcs : updateEnvToVirtualFiles.keySet()) {
Configurable configurable = myActionInfo.getEnvironment(vcs).createConfigurable(updateEnvToVirtualFiles.get(vcs));
if (configurable != null) {
envToConfMap.put(configurable, vcs);
}
}
return envToConfMap;
}
private Map<AbstractVcs,Collection<FilePath>> createVcsToFilesMap(FilePath[] roots, Project project) {
HashMap<AbstractVcs, Collection<FilePath>> resultPrep = new HashMap<AbstractVcs, Collection<FilePath>>();
for (FilePath file : roots) {
AbstractVcs vcs = VcsUtil.getVcsFor(project, file);
if (vcs != null) {
UpdateEnvironment updateEnvironment = myActionInfo.getEnvironment(vcs);
if (updateEnvironment != null) {
if (!resultPrep.containsKey(vcs)) resultPrep.put(vcs, new HashSet<FilePath>());
resultPrep.get(vcs).add(file);
}
}
}
final Map<AbstractVcs, Collection<FilePath>> result = new HashMap<AbstractVcs, Collection<FilePath>>();
for (Map.Entry<AbstractVcs, Collection<FilePath>> entry : resultPrep.entrySet()) {
final AbstractVcs vcs = entry.getKey();
final List<FilePath> paths = new ArrayList<FilePath>(entry.getValue());
final List<VirtualFile> files = ObjectsConvertor.convert(paths, ObjectsConvertor.FILEPATH_TO_VIRTUAL, ObjectsConvertor.NOT_NULL);
result.put(vcs, ObjectsConvertor.vf2fp(vcs.filterUniqueRoots(files, IntoSelfVirtualFileConvertor.getInstance())));
}
return result;
}
private static boolean containsParent(FilePath[] array, FilePath file) {
for (FilePath virtualFile : array) {
if (virtualFile == file) continue;
if (VfsUtil.isAncestor(virtualFile.getIOFile(), file.getIOFile(), false)) return true;
}
return false;
}
@NotNull
private FilePath[] filterRoots(FilePath[] roots, VcsContext vcsContext) {
final ArrayList<FilePath> result = new ArrayList<FilePath>();
final Project project = vcsContext.getProject();
for (FilePath file : roots) {
AbstractVcs vcs = VcsUtil.getVcsFor(project, file);
if (vcs != null) {
if (!myScopeInfo.filterExistsInVcs() || AbstractVcs.fileInVcsByFileStatus(project, file)) {
UpdateEnvironment updateEnvironment = myActionInfo.getEnvironment(vcs);
if (updateEnvironment != null) {
result.add(file);
}
}
else {
final VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile != null && virtualFile.isDirectory()) {
final VirtualFile[] vcsRoots = ProjectLevelVcsManager.getInstance(vcsContext.getProject()).getAllVersionedRoots();
for(VirtualFile vcsRoot: vcsRoots) {
if (VfsUtil.isAncestor(virtualFile, vcsRoot, false)) {
result.add(file);
}
}
}
}
}
}
return result.toArray(new FilePath[result.size()]);
}
protected abstract boolean filterRootsBeforeAction();
protected void update(VcsContext vcsContext, Presentation presentation) {
Project project = vcsContext.getProject();
if (project != null) {
String actionName = getCompleteActionName(vcsContext);
if (myActionInfo.showOptions(project) || OptionsDialog.shiftIsPressed(vcsContext.getModifiers())) {
actionName += "...";
}
presentation.setText(actionName);
presentation.setVisible(true);
presentation.setEnabled(true);
if (supportingVcsesAreEmpty(vcsContext.getProject(), myActionInfo)) {
presentation.setVisible(false);
presentation.setEnabled(false);
}
if (filterRootsBeforeAction()) {
FilePath[] roots = filterRoots(myScopeInfo.getRoots(vcsContext, myActionInfo), vcsContext);
if (roots.length == 0) {
presentation.setVisible(false);
presentation.setEnabled(false);
}
}
if (presentation.isVisible() && presentation.isEnabled() &&
ProjectLevelVcsManager.getInstance(project).isBackgroundVcsOperationRunning()) {
presentation.setEnabled(false);
}
} else {
presentation.setVisible(false);
presentation.setEnabled(false);
}
}
protected boolean forceSyncUpdate(final AnActionEvent e) {
return true;
}
private static boolean supportingVcsesAreEmpty(final Project project, final ActionInfo actionInfo) {
if (project == null) return true;
final AbstractVcs[] allActiveVcss = ProjectLevelVcsManager.getInstance(project).getAllActiveVcss();
for (AbstractVcs activeVcs : allActiveVcss) {
if (actionInfo.getEnvironment(activeVcs) != null) return false;
}
return true;
}
private class Updater extends Task.Backgroundable {
private final Project myProject;
private final ProjectLevelVcsManagerEx myProjectLevelVcsManager;
private UpdatedFiles myUpdatedFiles;
private final FilePath[] myRoots;
private final Map<AbstractVcs, Collection<FilePath>> myVcsToVirtualFiles;
private final Map<HotfixData, List<VcsException>> myGroupedExceptions;
private final List<UpdateSession> myUpdateSessions;
private int myUpdateNumber;
// vcs name, context object
private final Map<AbstractVcs, SequentialUpdatesContext> myContextInfo;
private VcsDirtyScopeManager myDirtyScopeManager;
private Label myBefore;
private Label myAfter;
public Updater(final Project project, final FilePath[] roots, final Map<AbstractVcs, Collection<FilePath>> vcsToVirtualFiles) {
super(project, getTemplatePresentation().getText(), true, VcsConfiguration.getInstance(project).getUpdateOption());
myProject = project;
myProjectLevelVcsManager = ProjectLevelVcsManagerEx.getInstanceEx(project);
myDirtyScopeManager = VcsDirtyScopeManager.getInstance(myProject);
myRoots = roots;
myVcsToVirtualFiles = vcsToVirtualFiles;
myUpdatedFiles = UpdatedFiles.create();
myGroupedExceptions = new HashMap<HotfixData, List<VcsException>>();
myUpdateSessions = new ArrayList<UpdateSession>();
// create from outside without any context; context is created by vcses
myContextInfo = new HashMap<AbstractVcs, SequentialUpdatesContext>();
myUpdateNumber = 1;
}
private void reset() {
myUpdatedFiles = UpdatedFiles.create();
myGroupedExceptions.clear();
myUpdateSessions.clear();
++ myUpdateNumber;
}
private void suspendIfNeeded() {
if (! myActionInfo.canChangeFileStatus()) {
// i.e. for update but not for integrate or status
((VcsDirtyScopeManagerImpl) myDirtyScopeManager).suspendMe();
}
}
private void releaseIfNeeded() {
if (! myActionInfo.canChangeFileStatus()) {
// i.e. for update but not for integrate or status
((VcsDirtyScopeManagerImpl) myDirtyScopeManager).reanimate();
}
}
public void run(@NotNull final ProgressIndicator indicator) {
suspendIfNeeded();
try {
runImpl(indicator);
} catch (Throwable t) {
releaseIfNeeded();
if (t instanceof Error) {
throw ((Error) t);
} else if (t instanceof RuntimeException) {
throw ((RuntimeException) t);
}
throw new RuntimeException(t);
}
}
private void runImpl(@NotNull final ProgressIndicator indicator) {
ProjectManagerEx.getInstanceEx().blockReloadingProjectOnExternalChanges();
myProjectLevelVcsManager.startBackgroundVcsOperation();
myBefore = LocalHistory.putSystemLabel(myProject, "Before update");
ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
try {
int toBeProcessed = myVcsToVirtualFiles.size();
int processed = 0;
for (AbstractVcs vcs : myVcsToVirtualFiles.keySet()) {
final UpdateEnvironment updateEnvironment = myActionInfo.getEnvironment(vcs);
updateEnvironment.fillGroups(myUpdatedFiles);
Collection<FilePath> files = myVcsToVirtualFiles.get(vcs);
final SequentialUpdatesContext context = myContextInfo.get(vcs);
final Ref<SequentialUpdatesContext> refContext = new Ref<SequentialUpdatesContext>(context);
UpdateSession updateSession =
updateEnvironment.updateDirectories(files.toArray(new FilePath[files.size()]), myUpdatedFiles, progressIndicator, refContext);
myContextInfo.put(vcs, refContext.get());
processed++;
if (progressIndicator != null) {
progressIndicator.setFraction((double)processed / (double)toBeProcessed);
}
final List<VcsException> exceptionList = updateSession.getExceptions();
gatherExceptions(vcs, exceptionList);
myUpdateSessions.add(updateSession);
}
} finally {
try {
if (progressIndicator != null) {
progressIndicator.setText(VcsBundle.message("progress.text.synchronizing.files"));
progressIndicator.setText2("");
}
doVfsRefresh();
} finally {
myAfter = LocalHistory.putSystemLabel(myProject, "After update");
myProjectLevelVcsManager.stopBackgroundVcsOperation();
}
}
}
private void gatherExceptions(final AbstractVcs vcs, final List<VcsException> exceptionList) {
final VcsExceptionsHotFixer fixer = vcs.getVcsExceptionsHotFixer();
if (fixer == null) {
putExceptions(null, exceptionList);
} else {
putExceptions(fixer.groupExceptions(ActionType.update, exceptionList));
}
}
private void putExceptions(final Map<HotfixData, List<VcsException>> map) {
for (Map.Entry<HotfixData, List<VcsException>> entry : map.entrySet()) {
putExceptions(entry.getKey(), entry.getValue());
}
}
private void putExceptions(final HotfixData key, @NotNull final List<VcsException> list) {
if (list.isEmpty()) return;
List<VcsException> exceptionList = myGroupedExceptions.get(key);
if (exceptionList == null) {
exceptionList = new ArrayList<VcsException>();
myGroupedExceptions.put(key, exceptionList);
}
exceptionList.addAll(list);
}
private void doVfsRefresh() {
final String actionName = VcsBundle.message("local.history.update.from.vcs");
final LocalHistoryAction action = LocalHistory.startAction(myProject, actionName);
try {
LOG.info("Calling refresh files after update for roots: " + Arrays.toString(myRoots));
RefreshVFsSynchronously.updateAllChanged(myUpdatedFiles);
}
finally {
action.finish();
LocalHistory.putSystemLabel(myProject, actionName);
}
}
@Nullable
public NotificationInfo getNotificationInfo() {
StringBuffer text = new StringBuffer();
final List<FileGroup> groups = myUpdatedFiles.getTopLevelGroups();
for (FileGroup group : groups) {
appendGroup(text, group);
}
return new NotificationInfo("VCS Update", "VCS Update Finished", text.toString(), true);
}
private void appendGroup(final StringBuffer text, final FileGroup group) {
final int s = group.getFiles().size();
if (s > 0) {
if (text.length() > 0) text.append("\n");
text.append(s + " Files " + group.getUpdateName());
}
final List<FileGroup> list = group.getChildren();
for (FileGroup g : list) {
appendGroup(text, g);
}
}
public void onSuccess() {
try {
onSuccessImpl();
} finally {
releaseIfNeeded();
}
}
private void onSuccessImpl() {
if (myProject.isDisposed()) {
ProjectManagerEx.getInstanceEx().unblockReloadingProjectOnExternalChanges();
return;
}
boolean continueChain = false;
for (SequentialUpdatesContext context : myContextInfo.values()) {
continueChain |= context != null;
}
final boolean continueChainFinal = continueChain;
final boolean someSessionWasCancelled = someSessionWasCanceled(myUpdateSessions);
if (! someSessionWasCancelled) {
for (final UpdateSession updateSession : myUpdateSessions) {
updateSession.onRefreshFilesCompleted();
}
}
if (myActionInfo.canChangeFileStatus()) {
final List<VirtualFile> files = new ArrayList<VirtualFile>();
final RemoteRevisionsCache revisionsCache = RemoteRevisionsCache.getInstance(myProject);
revisionsCache.invalidate(myUpdatedFiles);
UpdateFilesHelper.iterateFileGroupFiles(myUpdatedFiles, new UpdateFilesHelper.Callback() {
public void onFile(final String filePath, final String groupId) {
@NonNls final String path = VfsUtil.pathToUrl(filePath.replace(File.separatorChar, '/'));
final VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(path);
if (file != null) {
files.add(file);
}
}
});
myDirtyScopeManager.filesDirty(files, null);
}
final boolean updateSuccess = (! someSessionWasCancelled) && (myGroupedExceptions.isEmpty());
if (! someSessionWasCancelled) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
if (myProject.isDisposed()) {
ProjectManagerEx.getInstanceEx().unblockReloadingProjectOnExternalChanges();
return;
}
if (! myGroupedExceptions.isEmpty()) {
if (continueChainFinal) {
gatherContextInterruptedMessages();
}
AbstractVcsHelper.getInstance(myProject).showErrors(myGroupedExceptions, VcsBundle.message("message.title.vcs.update.errors",
getTemplatePresentation().getText()));
}
else {
final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator != null) {
indicator.setText(VcsBundle.message("progress.text.updating.done"));
}
}
final boolean noMerged = myUpdatedFiles.getGroupById(FileGroup.MERGED_WITH_CONFLICT_ID).isEmpty();
if (myUpdatedFiles.isEmpty() && myGroupedExceptions.isEmpty()) {
ToolWindowManager.getInstance(myProject).notifyByBalloon(
ChangesViewContentManager.TOOLWINDOW_ID, MessageType.INFO, getAllFilesAreUpToDateMessage(myRoots));
}
else if (! myUpdatedFiles.isEmpty()) {
showUpdateTree(continueChainFinal && updateSuccess && noMerged);
final CommittedChangesCache cache = CommittedChangesCache.getInstance(myProject);
cache.processUpdatedFiles(myUpdatedFiles);
}
ProjectManagerEx.getInstanceEx().unblockReloadingProjectOnExternalChanges();
if (continueChainFinal && updateSuccess) {
if (!noMerged) {
showContextInterruptedError();
} else {
// trigger next update; for CVS when updating from several branvhes simultaneously
reset();
ProgressManager.getInstance().run(Updater.this);
}
}
}
});
} else if (continueChain) {
// since error
showContextInterruptedError();
ProjectManagerEx.getInstanceEx().unblockReloadingProjectOnExternalChanges();
}
}
private void showContextInterruptedError() {
gatherContextInterruptedMessages();
AbstractVcsHelper.getInstance(myProject).showErrors(myGroupedExceptions,
VcsBundle.message("message.title.vcs.update.errors", getTemplatePresentation().getText()));
}
private void gatherContextInterruptedMessages() {
for (Map.Entry<AbstractVcs, SequentialUpdatesContext> entry : myContextInfo.entrySet()) {
final SequentialUpdatesContext context = entry.getValue();
if (context == null) continue;
final VcsException exception = new VcsException(context.getMessageWhenInterruptedBeforeStart());
gatherExceptions(entry.getKey(), Collections.singletonList(exception));
}
}
private void showUpdateTree(final boolean willBeContinued) {
RestoreUpdateTree restoreUpdateTree = RestoreUpdateTree.getInstance(myProject);
restoreUpdateTree.registerUpdateInformation(myUpdatedFiles, myActionInfo);
final String text = getTemplatePresentation().getText() + ((willBeContinued || (myUpdateNumber > 1)) ? ("#" + myUpdateNumber) : "");
final UpdateInfoTree updateInfoTree = myProjectLevelVcsManager.showUpdateProjectInfo(myUpdatedFiles, text, myActionInfo);
updateInfoTree.setBefore(myBefore);
updateInfoTree.setAfter(myAfter);
// todo make temporal listener of changes reload
if (updateInfoTree != null) {
updateInfoTree.setCanGroupByChangeList(canGroupByChangelist(myVcsToVirtualFiles.keySet()));
final MessageBusConnection messageBusConnection = myProject.getMessageBus().connect();
messageBusConnection.subscribe(CommittedChangesCache.COMMITTED_TOPIC, new CommittedChangesAdapter() {
public void incomingChangesUpdated(final List<CommittedChangeList> receivedChanges) {
if (receivedChanges != null) {
updateInfoTree.setChangeLists(receivedChanges);
messageBusConnection.disconnect();
}
}
});
}
}
public void onCancel() {
onSuccess();
}
}
}
| IDEA-50457 (Information on progress is strange)
| platform/vcs-impl/src/com/intellij/openapi/vcs/update/AbstractCommonUpdateAction.java | IDEA-50457 (Information on progress is strange) |
|
Java | apache-2.0 | 245dbd208c1b7e5cde3e4e59313f48534f64e1b2 | 0 | apache/incubator-tajo,yeeunshim/tajo_test,yeeunshim/tajo_test,yeeunshim/tajo_test,gruter/tajo-cdh,apache/incubator-tajo,yeeunshim/tajo_test,gruter/tajo-cdh,apache/incubator-tajo,apache/incubator-tajo,gruter/tajo-cdh,gruter/tajo-cdh | /**
* 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.tajo.engine.parser;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.TerminalNodeImpl;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tajo.algebra.*;
import org.apache.tajo.common.TajoDataTypes;
import org.apache.tajo.engine.parser.HiveQLParser.TableAllColumnsContext;
import java.math.BigInteger;
import java.util.*;
public class HiveQLAnalyzer extends HiveQLParserBaseVisitor<Expr> {
private static final Log LOG = LogFactory.getLog(HiveQLAnalyzer.class.getName());
private HiveQLParser parser;
public Expr parse(String sql) {
HiveQLLexer lexer = new HiveQLLexer(new ANTLRNoCaseStringStream(sql));
CommonTokenStream tokens = new CommonTokenStream(lexer);
parser = new HiveQLParser(tokens);
parser.setBuildParseTree(true);
HiveQLParser.StatementContext context;
try {
context = parser.statement();
} catch (SQLParseError e) {
throw new SQLSyntaxError(e);
}
return visit(context);
}
@Override
public Expr visitStatement(HiveQLParser.StatementContext ctx) {
return visitExecStatement(ctx.execStatement());
}
@Override
public Expr visitQueryStatement(HiveQLParser.QueryStatementContext ctx) {
Expr current = null;
if (ctx.body != null) {
current = visitBody(ctx.body(0));
}
if (ctx.regular_body() != null) {
current = visitRegular_body(ctx.regular_body());
}
return current;
}
@Override
public Expr visitBody(HiveQLParser.BodyContext ctx) {
Expr current = null;
Insert insert = null;
Projection select = null;
if (ctx.insertClause() != null) {
insert = visitInsertClause(ctx.insertClause());
}
if (ctx.selectClause() != null) {
select = (Projection) visitSelectClause(ctx.selectClause());
if (ctx.selectClause().KW_DISTINCT() != null) {
select.setDistinct();
}
}
for (int i = 0; i < ctx.getParent().getChildCount(); i++) {
if (ctx.getParent().getChild(i) instanceof HiveQLParser.FromClauseContext) {
HiveQLParser.FromClauseContext fromClauseContext = (HiveQLParser.FromClauseContext) ctx.getParent().getChild(i);
Expr from = visitFromClause(fromClauseContext);
current = from;
}
}
if (ctx.whereClause() != null) {
Selection where = new Selection(visitWhereClause(ctx.whereClause()));
where.setChild(current);
current = where;
}
if (ctx.groupByClause() != null) {
Aggregation aggregation = visitGroupByClause(ctx.groupByClause());
aggregation.setChild(current);
current = aggregation;
if (ctx.havingClause() != null) {
Expr havingCondition = visitHavingClause(ctx.havingClause());
Having having = new Having(havingCondition);
having.setChild(current);
current = having;
}
}
if (ctx.orderByClause() != null) {
Sort sort = visitOrderByClause(ctx.orderByClause());
sort.setChild(current);
current = sort;
}
if (ctx.clusterByClause() != null) {
visitClusterByClause(ctx.clusterByClause());
}
if (ctx.distributeByClause() != null) {
visitDistributeByClause(ctx.distributeByClause());
}
if (ctx.sortByClause() != null) {
Sort sort = visitSortByClause(ctx.sortByClause());
sort.setChild(current);
current = sort;
}
if (ctx.window_clause() != null) {
Expr window = visitWindow_clause(ctx.window_clause());
}
if (ctx.limitClause() != null) {
Limit limit = visitLimitClause(ctx.limitClause());
limit.setChild(current);
current = limit;
}
Projection projection = new Projection();
projection.setNamedExprs(select.getNamedExprs());
if (current != null)
projection.setChild(current);
if (select.isDistinct())
projection.setDistinct();
if (insert != null) {
insert.setSubQuery(projection);
current = insert;
} else {
current = projection;
}
return current;
}
@Override
public Expr visitRegular_body(HiveQLParser.Regular_bodyContext ctx) {
Expr current = null;
Insert insert = null;
if (ctx.selectStatement() != null) {
current = visitSelectStatement(ctx.selectStatement());
} else {
Projection select = null;
if (ctx.insertClause() != null) {
insert = visitInsertClause(ctx.insertClause());
}
if (ctx.selectClause() != null) {
select = (Projection) visitSelectClause(ctx.selectClause());
if (ctx.selectClause().KW_DISTINCT() != null) {
select.setDistinct();
}
}
if (ctx.fromClause() != null) {
Expr from = visitFromClause(ctx.fromClause());
current = from;
}
if (ctx.whereClause() != null) {
Selection where = new Selection(visitWhereClause(ctx.whereClause()));
where.setChild(current);
current = where;
}
if (ctx.groupByClause() != null) {
Aggregation aggregation = visitGroupByClause(ctx.groupByClause());
aggregation.setChild(current);
current = aggregation;
if (ctx.havingClause() != null) {
Expr havingCondition = visitHavingClause(ctx.havingClause());
Having having = new Having(havingCondition);
having.setChild(current);
current = having;
}
}
if (ctx.orderByClause() != null) {
Sort sort = visitOrderByClause(ctx.orderByClause());
sort.setChild(current);
current = sort;
}
if (ctx.clusterByClause() != null) {
visitClusterByClause(ctx.clusterByClause());
}
if (ctx.distributeByClause() != null) {
visitDistributeByClause(ctx.distributeByClause());
}
if (ctx.sortByClause() != null) {
Sort sort = visitSortByClause(ctx.sortByClause());
sort.setChild(current);
current = sort;
}
if (ctx.window_clause() != null) {
Expr window = visitWindow_clause(ctx.window_clause());
}
if (ctx.limitClause() != null) {
Limit limit = visitLimitClause(ctx.limitClause());
limit.setChild(current);
current = limit;
}
Projection projection = new Projection();
projection.setNamedExprs(select.getNamedExprs());
if (current != null)
projection.setChild(current);
if (select.isDistinct())
projection.setDistinct();
if (insert != null) {
insert.setSubQuery(projection);
current = insert;
} else {
current = projection;
}
}
return current;
}
/**
* This method implemented for parsing union all clause.
*
* @param ctx
* @return
*/
@Override
public Expr visitQueryStatementExpression(HiveQLParser.QueryStatementExpressionContext ctx) {
Expr left = null, right = null, current = null;
if (ctx.queryStatement() != null) {
if (ctx.queryStatement().size() == 1)
return visitQueryStatement(ctx.queryStatement(0));
for (int i = 0; i < ctx.queryStatement().size(); i++) {
if (i == 0)
current = visitQueryStatement(ctx.queryStatement(i));
else
left = current;
if (i > 0) {
right = visitQueryStatement(ctx.queryStatement(i));
current = new SetOperation(OpType.Union, left, right, false);
}
}
}
return current;
}
@Override
public Expr visitSelectStatement(HiveQLParser.SelectStatementContext ctx) {
Expr current = null;
Projection select = (Projection) visitSelectClause(ctx.selectClause());
if (ctx.selectClause().KW_DISTINCT() != null) {
select.setDistinct();
}
Expr from = visitFromClause(ctx.fromClause());
current = from;
if (ctx.whereClause() != null) {
Selection where = new Selection(visitWhereClause(ctx.whereClause()));
where.setChild(current);
current = where;
}
if (ctx.groupByClause() != null) {
Aggregation aggregation = visitGroupByClause(ctx.groupByClause());
aggregation.setChild(current);
current = aggregation;
if (ctx.havingClause() != null) {
Expr havingCondition = visitHavingClause(ctx.havingClause());
Having having = new Having(havingCondition);
having.setChild(current);
current = having;
}
}
if (ctx.orderByClause() != null) {
Sort sort = visitOrderByClause(ctx.orderByClause());
sort.setChild(current);
current = sort;
}
if (ctx.clusterByClause() != null) {
visitClusterByClause(ctx.clusterByClause());
}
if (ctx.distributeByClause() != null) {
visitDistributeByClause(ctx.distributeByClause());
}
if (ctx.sortByClause() != null) {
Sort sort = visitSortByClause(ctx.sortByClause());
sort.setChild(current);
current = sort;
}
if (ctx.window_clause() != null) {
Expr window = visitWindow_clause(ctx.window_clause());
}
if (ctx.limitClause() != null) {
Limit limit = visitLimitClause(ctx.limitClause());
limit.setChild(current);
current = limit;
}
Projection projection = new Projection();
projection.setNamedExprs(select.getNamedExprs());
if (current != null)
projection.setChild(current);
if (select.isDistinct())
projection.setDistinct();
current = projection;
return current;
}
@Override
public Expr visitFromClause(HiveQLParser.FromClauseContext ctx) {
return visitJoinSource(ctx.joinSource());
}
@Override
public Expr visitJoinSource(HiveQLParser.JoinSourceContext ctx) {
Expr[] relations = null;
RelationList relationList = null;
if (ctx.fromSource() != null) {
int fromCount = ctx.fromSource().size();
int uniqueJoinCount = ctx.uniqueJoinSource().size();
relations = new Expr[1];
Join current = null, parent = null;
JoinType type = null;
Expr left = null, right = null, condition = null;
if (fromCount == 1) {
relations[0] = visitFromSource(ctx.fromSource(0));
} else {
left = visitFromSource((HiveQLParser.FromSourceContext) ctx.getChild(0));
for (int i = 1; i < ctx.getChildCount(); i++) {
type = null;
right = null;
condition = null;
if (ctx.getChild(i) instanceof HiveQLParser.JoinTokenContext) {
type = getJoinType((HiveQLParser.JoinTokenContext) ctx.getChild(i));
if (i > 1)
left = parent;
if (i + 1 < ctx.getChildCount() && ctx.getChild(i + 1) instanceof HiveQLParser.FromSourceContext) {
right = visitFromSource((HiveQLParser.FromSourceContext) ctx.getChild(i + 1));
}
if (i + 3 < ctx.getChildCount() && ctx.getChild(i + 3) instanceof HiveQLParser.ExpressionContext) {
condition = visitExpression((HiveQLParser.ExpressionContext) ctx.getChild(i + 3));
}
if (type != null) {
current = new Join(type);
current.setLeft(left);
current.setRight(right);
if (condition != null)
current.setQual(condition);
parent = current;
}
}
}
relations[0] = current;
}
//TODO: implement unique join.
relationList = new RelationList(relations);
}
return relationList;
}
public JoinType getJoinType(HiveQLParser.JoinTokenContext context) {
JoinType type = JoinType.INNER;
if (context.KW_INNER() != null) {
type = JoinType.INNER;
}
if (context.KW_LEFT() != null && context.KW_OUTER() != null) {
type = JoinType.LEFT_OUTER;
}
if (context.KW_RIGHT() != null && context.KW_OUTER() != null) {
type = JoinType.RIGHT_OUTER;
}
if (context.KW_CROSS() != null) {
type = JoinType.CROSS;
}
if (context.KW_FULL() != null) {
type = JoinType.FULL_OUTER;
}
if (context.KW_SEMI() != null) {
type = null;
}
return type;
}
@Override
public Expr visitFromSource(HiveQLParser.FromSourceContext ctx) {
Expr current = null;
if (ctx.Identifier() != null && ctx.LPAREN() != null) {
current = new LiteralValue(ctx.Identifier().getText(), LiteralValue.LiteralType.String);
}
if (ctx.tableSource() != null) {
current = visitTableSource(ctx.tableSource());
}
if (ctx.subQuerySource() != null) {
current = visitSubQuerySource(ctx.subQuerySource());
String tableAlias = "";
for (int i = 0; i < ctx.subQuerySource().getChildCount(); i++) {
if (ctx.subQuerySource().getChild(i) instanceof HiveQLParser.IdentifierContext) {
tableAlias = (ctx.subQuerySource().getChild(i)).getText();
}
}
TablePrimarySubQuery subQuery = new TablePrimarySubQuery(tableAlias, current);
current = subQuery;
}
// TODO: implement lateralView
return current;
}
@Override
public Expr visitSubQuerySource(HiveQLParser.SubQuerySourceContext ctx) {
Expr current = visitQueryStatementExpression(ctx.queryStatementExpression());
return current;
}
@Override
public Expr visitTableSource(HiveQLParser.TableSourceContext ctx) {
String tableName = "", alias = "";
if (ctx.tableName() != null)
tableName = ctx.tableName().getText();
if (ctx.alias != null) {
alias = ctx.alias.getText();
for (String token : HiveQLParser.tokenNames) {
if (token.replaceAll("'", "").equalsIgnoreCase(alias))
alias = "";
}
}
Relation relation = new Relation(tableName);
if (!alias.equals(""))
relation.setAlias(alias);
return relation;
}
@Override
public Expr visitSelectList(HiveQLParser.SelectListContext ctx) {
Expr current = null;
Projection projection = new Projection();
NamedExpr[] targets = new NamedExpr[ctx.selectItem().size()];
for (int i = 0; i < targets.length; i++) {
targets[i] = visitSelectItem(ctx.selectItem(i));
}
projection.setNamedExprs(targets);
current = projection;
return current;
}
@Override
public NamedExpr visitSelectItem(HiveQLParser.SelectItemContext ctx) {
NamedExpr target = null;
if (ctx.selectExpression() != null) {
target = new NamedExpr(visitSelectExpression(ctx.selectExpression()));
} else if (ctx.window_specification() != null) {
// TODO: if there is a window specification clause, we should handle it properly.
}
if (ctx.identifier().size() > 0 && target != null) {
target.setAlias(ctx.identifier(0).getText());
}
return target;
}
@Override
public Expr visitSelectExpression(HiveQLParser.SelectExpressionContext ctx) {
Expr current = null;
if (ctx.tableAllColumns() != null) {
current = visitTableAllColumns(ctx.tableAllColumns());
} else {
if (ctx.expression() != null) {
current = visitExpression(ctx.expression());
}
}
return current;
}
@Override
public Expr visitTableAllColumns(TableAllColumnsContext ctx) {
QualifiedAsteriskExpr target = new QualifiedAsteriskExpr();
if (ctx.tableName() != null) {
target.setQualifier(ctx.tableName().getText());
}
return target;
}
@Override
public Expr visitExpression(HiveQLParser.ExpressionContext ctx) {
Expr current = visitPrecedenceOrExpression(ctx.precedenceOrExpression());
return current;
}
@Override
public Expr visitPrecedenceOrExpression(HiveQLParser.PrecedenceOrExpressionContext ctx) {
Expr current = null, left = null, right = null;
for (int i = 0; i < ctx.precedenceAndExpression().size(); i++) {
if (i == 0) {
left = visitPrecedenceAndExpression(ctx.precedenceAndExpression(i));
current = left;
} else {
left = current;
right = visitPrecedenceAndExpression(ctx.precedenceAndExpression(i));
current = new BinaryOperator(OpType.Or, left, right);
}
}
return current;
}
/**
* This method parse AND expressions at WHERE clause.
* And this convert 'x BETWEEN y AND z' expression into 'x >= y AND x <= z' expression
* because Tajo doesn't provide 'BETWEEN' expression.
*
* @param ctx
* @return
*/
@Override
public Expr visitPrecedenceAndExpression(HiveQLParser.PrecedenceAndExpressionContext ctx) {
Expr current = null, left = null, right = null;
for (int i = 0; i < ctx.precedenceNotExpression().size(); i++) {
Expr min = null, max = null;
if (ctx.precedenceNotExpression(i).precedenceEqualExpression() != null) {
HiveQLParser.PrecedenceEqualExpressionContext expressionContext = ctx.precedenceNotExpression(i)
.precedenceEqualExpression();
if (expressionContext.KW_BETWEEN() != null) {
if (expressionContext.min != null) {
min = visitPrecedenceBitwiseOrExpression(expressionContext.min);
}
if (expressionContext.max != null) {
max = visitPrecedenceBitwiseOrExpression(expressionContext.max);
}
}
}
if (min != null && max != null) {
left = visitPrecedenceNotExpression(ctx.precedenceNotExpression(i));
if (left != null) {
if (i == 0) {
BinaryOperator minOperator = new BinaryOperator(OpType.GreaterThanOrEquals, left, min);
BinaryOperator maxOperator = new BinaryOperator(OpType.LessThanOrEquals, left, max);
current = new BinaryOperator(OpType.And, minOperator, maxOperator);
} else {
BinaryOperator minOperator = new BinaryOperator(OpType.GreaterThanOrEquals, left, min);
current = new BinaryOperator(OpType.And, current, minOperator);
BinaryOperator maxOperator = new BinaryOperator(OpType.LessThanOrEquals, left, max);
current = new BinaryOperator(OpType.And, current, maxOperator);
}
}
} else {
if (i == 0) {
left = visitPrecedenceNotExpression(ctx.precedenceNotExpression(i));
current = left;
} else {
left = current;
right = visitPrecedenceNotExpression(ctx.precedenceNotExpression(i));
current = new BinaryOperator(OpType.And, left, right);
}
}
}
return current;
}
@Override
public Expr visitPrecedenceNotExpression(HiveQLParser.PrecedenceNotExpressionContext ctx) {
HiveQLParser.PrecedenceEqualExpressionContext expressionContext = ctx.precedenceEqualExpression();
Expr current = visitPrecedenceEqualExpression(expressionContext);
return current;
}
/**
* This method parse operators for equals expressions as follows:
* =, <>, !=, >=, >, <=, <, IN, NOT IN, LIKE, REGEXP, RLIKE
* <p/>
* In this case, this make RuntimeException>
*
* @param ctx
* @return
*/
@Override
public Expr visitPrecedenceEqualExpression(HiveQLParser.PrecedenceEqualExpressionContext ctx) {
Expr current = null, left = null, right = null, min = null, max = null;
OpType type = null;
boolean isNot = false, isIn = false;
for (int i = 0; i < ctx.getChildCount(); i++) {
if (ctx.getChild(i) instanceof HiveQLParser.PrecedenceBitwiseOrExpressionContext) {
if (i == 0) {
left = visitPrecedenceBitwiseOrExpression((HiveQLParser.PrecedenceBitwiseOrExpressionContext) ctx.getChild(i));
} else {
right = visitPrecedenceBitwiseOrExpression((HiveQLParser.PrecedenceBitwiseOrExpressionContext) ctx.getChild(i));
}
} else if (ctx.getChild(i) instanceof HiveQLParser.ExpressionsContext) {
right = visitExpressions((HiveQLParser.ExpressionsContext) ctx.getChild(i));
} else if (ctx.getChild(i) instanceof TerminalNodeImpl) {
int symbolType = ((TerminalNodeImpl) ctx.getChild(i)).getSymbol().getType();
switch (symbolType) {
case HiveQLLexer.KW_NOT:
isNot = true;
break;
case HiveQLLexer.KW_IN:
isIn = true;
break;
default:
break;
}
} else if (ctx.getChild(i) instanceof HiveQLParser.PrecedenceEqualOperatorContext
|| ctx.getChild(i) instanceof HiveQLParser.PrecedenceEqualNegatableOperatorContext) {
String keyword = ctx.getChild(i).getText().toUpperCase();
if (keyword.equals(">")) {
type = OpType.GreaterThan;
} else if (keyword.equals("<=>")) {
throw new RuntimeException("Unexpected operator : <=>");
} else if (keyword.equals("=")) {
type = OpType.Equals;
} else if (keyword.equals("<=")) {
type = OpType.LessThanOrEquals;
} else if (keyword.equals("<")) {
type = OpType.LessThan;
} else if (keyword.equals(">=")) {
type = OpType.GreaterThanOrEquals;
} else if (keyword.equals("<>")) {
type = OpType.NotEquals;
} else if (keyword.equals("!=")) {
type = OpType.NotEquals;
} else if (keyword.equals("REGEXP")) {
type = OpType.Regexp;
} else if (keyword.equals("RLIKE")) {
type = OpType.Regexp;
} else if (keyword.equals("LIKE")) {
type = OpType.LikePredicate;
}
}
}
if (type != null && right != null) {
if (type.equals(OpType.LikePredicate)) {
PatternMatchPredicate like = new PatternMatchPredicate(OpType.LikePredicate,
isNot, left, right);
current = like;
} else if (type.equals(OpType.Regexp)) {
PatternMatchPredicate regex = new PatternMatchPredicate(OpType.Regexp, isNot, left, right);
current = regex;
} else {
BinaryOperator binaryOperator = new BinaryOperator(type, left, right);
current = binaryOperator;
}
} else if (isIn) {
InPredicate inPredicate = new InPredicate(left, right, isNot);
current = inPredicate;
} else {
current = left;
}
return current;
}
@Override
public ValueListExpr visitExpressions(HiveQLParser.ExpressionsContext ctx) {
int size = ctx.expression().size();
Expr[] exprs = new Expr[size];
for (int i = 0; i < size; i++) {
exprs[i] = visitExpression(ctx.expression(i));
}
return new ValueListExpr(exprs);
}
@Override
public Expr visitPrecedenceBitwiseOrExpression(HiveQLParser.PrecedenceBitwiseOrExpressionContext ctx) {
int expressionCount = ctx.precedenceAmpersandExpression().size();
Expr current = null, left = null, right = null, parentLeft, parentRight;
OpType type = null, parentType = null;
for (int i = 0; i < expressionCount; i += 2) {
int operatorIndex = (i == 0) ? 0 : i - 1;
if (ctx.precedenceBitwiseOrOperator(operatorIndex) != null) {
type = getPrecedenceBitwiseOrOperator(ctx.precedenceBitwiseOrOperator(operatorIndex));
}
if (i == 0) {
left = visitPrecedenceAmpersandExpression(ctx.precedenceAmpersandExpression(i));
if (ctx.precedenceAmpersandExpression(i + 1) != null)
right = visitPrecedenceAmpersandExpression(ctx.precedenceAmpersandExpression(i + 1));
} else {
parentType = getPrecedenceBitwiseOrOperator((ctx.precedenceBitwiseOrOperator(operatorIndex - 1)));
parentLeft = visitPrecedenceAmpersandExpression(ctx.precedenceAmpersandExpression(i - 2));
parentRight = visitPrecedenceAmpersandExpression(ctx.precedenceAmpersandExpression(i - 1));
left = new BinaryOperator(parentType, parentLeft, parentRight);
right = visitPrecedenceAmpersandExpression(ctx.precedenceAmpersandExpression(i));
}
if (right != null) {
current = new BinaryOperator(type, left, right);
} else {
current = left;
}
}
return current;
}
public OpType getPrecedenceBitwiseOrOperator(HiveQLParser.PrecedenceBitwiseOrOperatorContext ctx) {
OpType type = null;
// TODO: It needs to consider how to support.
return type;
}
@Override
public Expr visitPrecedenceAmpersandExpression(HiveQLParser.PrecedenceAmpersandExpressionContext ctx) {
int expressionCount = ctx.precedencePlusExpression().size();
Expr current = null, left = null, right = null, parentLeft, parentRight;
OpType type = null, parentType = null;
for (int i = 0; i < expressionCount; i += 2) {
int operatorIndex = (i == 0) ? 0 : i - 1;
if (ctx.precedenceAmpersandOperator(operatorIndex) != null) {
type = getPrecedenceAmpersandOperator(ctx.precedenceAmpersandOperator(operatorIndex));
}
if (i == 0) {
left = visitPrecedencePlusExpression(ctx.precedencePlusExpression(i));
if (ctx.precedencePlusExpression(i + 1) != null)
right = visitPrecedencePlusExpression(ctx.precedencePlusExpression(i + 1));
} else {
parentType = getPrecedenceAmpersandOperator((ctx.precedenceAmpersandOperator(operatorIndex - 1)));
parentLeft = visitPrecedencePlusExpression(ctx.precedencePlusExpression(i - 2));
parentRight = visitPrecedencePlusExpression(ctx.precedencePlusExpression(i - 1));
left = new BinaryOperator(parentType, parentLeft, parentRight);
right = visitPrecedencePlusExpression(ctx.precedencePlusExpression(i));
}
if (right != null) {
current = new BinaryOperator(type, left, right);
} else {
current = left;
}
}
return current;
}
public OpType getPrecedenceAmpersandOperator(HiveQLParser.PrecedenceAmpersandOperatorContext ctx) {
OpType type = null;
// TODO: It needs to consider how to support.
return type;
}
@Override
public Expr visitPrecedencePlusExpression(HiveQLParser.PrecedencePlusExpressionContext ctx) {
int expressionCount = ctx.precedenceStarExpression().size();
Expr current = null, left = null, right = null, parentLeft, parentRight;
OpType type = null, parentType = null;
for (int i = 0; i < expressionCount; i += 2) {
int operatorIndex = (i == 0) ? 0 : i - 1;
if (ctx.precedencePlusOperator(operatorIndex) != null) {
type = getPrecedencePlusOperator(ctx.precedencePlusOperator(operatorIndex));
}
if (i == 0) {
left = visitPrecedenceStarExpression(ctx.precedenceStarExpression(i));
if (ctx.precedenceStarExpression(i + 1) != null)
right = visitPrecedenceStarExpression(ctx.precedenceStarExpression(i + 1));
} else {
parentType = getPrecedencePlusOperator((ctx.precedencePlusOperator(operatorIndex - 1)));
parentLeft = visitPrecedenceStarExpression(ctx.precedenceStarExpression(i - 2));
parentRight = visitPrecedenceStarExpression(ctx.precedenceStarExpression(i - 1));
left = new BinaryOperator(parentType, parentLeft, parentRight);
right = visitPrecedenceStarExpression(ctx.precedenceStarExpression(i));
}
if (right != null) {
current = new BinaryOperator(type, left, right);
} else {
current = left;
}
}
return current;
}
public OpType getPrecedencePlusOperator(HiveQLParser.PrecedencePlusOperatorContext ctx) {
OpType type = null;
if (ctx.MINUS() != null) {
type = OpType.Minus;
} else if (ctx.PLUS() != null) {
type = OpType.Plus;
}
return type;
}
@Override
public Expr visitPrecedenceStarExpression(HiveQLParser.PrecedenceStarExpressionContext ctx) {
int expressionCount = ctx.precedenceBitwiseXorExpression().size();
Expr current = null, left = null, right = null, parentLeft, parentRight;
OpType type = null, parentType = null;
for (int i = 0; i < expressionCount; i += 2) {
int operatorIndex = (i == 0) ? 0 : i - 1;
if (ctx.precedenceStarOperator(operatorIndex) != null) {
type = getPrecedenceStarOperator(ctx.precedenceStarOperator(operatorIndex));
}
if (i == 0) {
left = visitPrecedenceBitwiseXorExpression(ctx.precedenceBitwiseXorExpression(i));
if (ctx.precedenceBitwiseXorExpression(i + 1) != null)
right = visitPrecedenceBitwiseXorExpression(ctx.precedenceBitwiseXorExpression(i + 1));
} else {
parentType = getPrecedenceStarOperator((ctx.precedenceStarOperator(operatorIndex - 1)));
parentLeft = visitPrecedenceBitwiseXorExpression(ctx.precedenceBitwiseXorExpression(i - 2));
parentRight = visitPrecedenceBitwiseXorExpression(ctx.precedenceBitwiseXorExpression(i - 1));
left = new BinaryOperator(parentType, parentLeft, parentRight);
right = visitPrecedenceBitwiseXorExpression(ctx.precedenceBitwiseXorExpression(i));
}
if (right != null) {
current = new BinaryOperator(type, left, right);
} else {
current = left;
}
}
return current;
}
public OpType getPrecedenceStarOperator(HiveQLParser.PrecedenceStarOperatorContext ctx) {
OpType type = null;
if (ctx.DIV() != null) {
type = OpType.Divide;
} else if (ctx.DIVIDE() != null) {
type = OpType.Divide;
} else if (ctx.MOD() != null) {
type = OpType.Modular;
} else if (ctx.STAR() != null) {
type = OpType.Multiply;
}
return type;
}
@Override
public Expr visitPrecedenceBitwiseXorExpression(HiveQLParser.PrecedenceBitwiseXorExpressionContext ctx) {
int expressionCount = ctx.precedenceUnarySuffixExpression().size();
Expr current = null, left = null, right = null, parentLeft, parentRight;
OpType type = null, parentType = null;
for (int i = 0; i < expressionCount; i += 2) {
int operatorIndex = (i == 0) ? 0 : i - 1;
if (ctx.precedenceBitwiseXorOperator(operatorIndex) != null) {
type = getPrecedenceBitwiseXorOperator(ctx.precedenceBitwiseXorOperator(operatorIndex));
}
if (i == 0) {
left = visitPrecedenceUnarySuffixExpression(ctx.precedenceUnarySuffixExpression(i));
if (ctx.precedenceUnarySuffixExpression(i + 1) != null)
right = visitPrecedenceUnarySuffixExpression(ctx.precedenceUnarySuffixExpression(i + 1));
} else {
parentType = getPrecedenceBitwiseXorOperator((ctx.precedenceBitwiseXorOperator(operatorIndex - 1)));
parentLeft = visitPrecedenceUnarySuffixExpression(ctx.precedenceUnarySuffixExpression(i - 2));
parentRight = visitPrecedenceUnarySuffixExpression(ctx.precedenceUnarySuffixExpression(i - 1));
left = new BinaryOperator(parentType, parentLeft, parentRight);
right = visitPrecedenceUnarySuffixExpression(ctx.precedenceUnarySuffixExpression(i));
}
if (right != null) {
current = new BinaryOperator(type, left, right);
} else {
current = left;
}
}
return current;
}
public OpType getPrecedenceBitwiseXorOperator(HiveQLParser.PrecedenceBitwiseXorOperatorContext ctx) {
OpType type = null;
// TODO: It needs to consider how to support.
return type;
}
@Override
public Expr visitPrecedenceUnarySuffixExpression(HiveQLParser.PrecedenceUnarySuffixExpressionContext ctx) {
Expr current = visitPrecedenceUnaryPrefixExpression(ctx.precedenceUnaryPrefixExpression());
if (ctx.nullCondition() != null) {
boolean isNot = ctx.nullCondition().KW_NOT() == null ? false : true;
IsNullPredicate isNullPredicate = new IsNullPredicate(isNot, (ColumnReferenceExpr) current);
current = isNullPredicate;
}
return current;
}
@Override
public Expr visitPrecedenceUnaryPrefixExpression(HiveQLParser.PrecedenceUnaryPrefixExpressionContext ctx) {
Expr current = visitPrecedenceFieldExpression(ctx.precedenceFieldExpression());
return current;
}
@Override
public Expr visitNullCondition(HiveQLParser.NullConditionContext ctx) {
return new NullLiteral();
}
@Override
public Expr visitPrecedenceFieldExpression(HiveQLParser.PrecedenceFieldExpressionContext ctx) {
Expr current = visitAtomExpression(ctx.atomExpression());
if (ctx.DOT().size() > 0) {
ColumnReferenceExpr column = new ColumnReferenceExpr(ctx.identifier(0).getText());
ColumnReferenceExpr table = (ColumnReferenceExpr) current;
column.setQualifier(table.getName());
current = column;
}
return current;
}
@Override
public Expr visitAtomExpression(HiveQLParser.AtomExpressionContext ctx) {
Expr current = null;
if (ctx.KW_NULL() != null) {
current = new NullLiteral();
}
if (ctx.constant() != null) {
current = visitConstant(ctx.constant());
}
if (ctx.function() != null) {
current = visitFunction(ctx.function());
}
if (ctx.castExpression() != null) {
current = visitCastExpression(ctx.castExpression());
}
if (ctx.caseExpression() != null) {
current = visitCaseExpression(ctx.caseExpression());
}
if (ctx.whenExpression() != null) {
current = visitWhenExpression(ctx.whenExpression());
}
if (ctx.tableOrColumn() != null) {
current = visitTableOrColumn(ctx.tableOrColumn());
} else {
if (ctx.LPAREN() != null && ctx.RPAREN() != null) {
current = visitExpression(ctx.expression());
}
}
return current;
}
@Override
public Expr visitTableOrColumn(HiveQLParser.TableOrColumnContext ctx) {
ColumnReferenceExpr columnReferenceExpr = new ColumnReferenceExpr(ctx.identifier().getText());
return columnReferenceExpr;
}
@Override
public Expr visitIdentifier(HiveQLParser.IdentifierContext ctx) {
Expr current = null;
if (ctx.nonReserved() != null) {
current = new LiteralValue(ctx.nonReserved().getText(), LiteralValue.LiteralType.String);
} else {
current = new LiteralValue(ctx.Identifier().getText(), LiteralValue.LiteralType.String);
}
return current;
}
@Override
public LiteralValue visitConstant(HiveQLParser.ConstantContext ctx) {
LiteralValue literalValue = null;
if (ctx.StringLiteral() != null) {
String value = ctx.StringLiteral().getText();
String strValue = "";
if ((value.startsWith("'") && value.endsWith("'")) || value.startsWith("\"") && value.endsWith("\"")) {
strValue = value.substring(1, value.length() - 1);
} else {
strValue = value;
}
literalValue = new LiteralValue(strValue, LiteralValue.LiteralType.String);
} else if (ctx.TinyintLiteral() != null) {
literalValue = new LiteralValue(ctx.TinyintLiteral().getSymbol().getText(),
LiteralValue.LiteralType.Unsigned_Integer);
} else if (ctx.BigintLiteral() != null) {
literalValue = new LiteralValue(ctx.BigintLiteral().getSymbol().getText(),
LiteralValue.LiteralType.Unsigned_Large_Integer);
} else if (ctx.DecimalLiteral() != null) {
literalValue = new LiteralValue(ctx.DecimalLiteral().getSymbol().getText(),
LiteralValue.LiteralType.Unsigned_Integer);
} else if (ctx.Number() != null) {
try {
float floatValue = NumberUtils.createFloat(ctx.getText());
literalValue = new LiteralValue(ctx.Number().getSymbol().getText(), LiteralValue.LiteralType.Unsigned_Float);
} catch (NumberFormatException nf) {
}
// TODO: double type
try {
BigInteger bigIntegerVallue = NumberUtils.createBigInteger(ctx.getText());
literalValue = new LiteralValue(ctx.Number().getSymbol().getText(),
LiteralValue.LiteralType.Unsigned_Large_Integer);
} catch (NumberFormatException nf) {
}
try {
int intValue = NumberUtils.createInteger(ctx.getText());
literalValue = new LiteralValue(ctx.Number().getSymbol().getText(), LiteralValue.LiteralType.Unsigned_Integer);
} catch (NumberFormatException nf) {
}
} else if (ctx.SmallintLiteral() != null) {
literalValue = new LiteralValue(ctx.SmallintLiteral().getSymbol().getText(),
LiteralValue.LiteralType.Unsigned_Integer);
} else if (ctx.booleanValue() != null) {
// TODO: boolean type
}
return literalValue;
}
@Override
public Expr visitFunction(HiveQLParser.FunctionContext ctx) {
Expr current = null;
String signature = ctx.functionName().getText();
boolean isDistinct = false;
if (ctx.getChild(2) != null) {
if (ctx.getChild(2) instanceof TerminalNodeImpl && ctx.getChild(2).getText().equalsIgnoreCase("DISTINCT")) {
isDistinct = true;
}
}
if (signature.equalsIgnoreCase("MIN")
|| signature.equalsIgnoreCase("MAX")
|| signature.equalsIgnoreCase("SUM")
|| signature.equalsIgnoreCase("AVG")
|| signature.equalsIgnoreCase("COUNT")
) {
if (ctx.selectExpression().size() > 1) {
throw new RuntimeException("Exactly expected one argument.");
}
if (ctx.selectExpression().size() == 0) {
CountRowsFunctionExpr countRowsFunctionExpr = new CountRowsFunctionExpr();
current = countRowsFunctionExpr;
} else {
GeneralSetFunctionExpr setFunctionExpr = new GeneralSetFunctionExpr(signature, isDistinct,
visitSelectExpression(ctx.selectExpression(0)));
current = setFunctionExpr;
}
} else {
FunctionExpr functionExpr = new FunctionExpr(signature);
Expr[] params = new Expr[ctx.selectExpression().size()];
for (int i = 0; i < ctx.selectExpression().size(); i++) {
params[i] = visitSelectExpression(ctx.selectExpression(i));
}
functionExpr.setParams(params);
current = functionExpr;
}
return current;
}
/**
* This method parse CAST expression.
* This returns only expression field without casting type
* because Tajo doesn't provide CAST expression.
*
* @param ctx
* @return
*/
@Override
public Expr visitCastExpression(HiveQLParser.CastExpressionContext ctx) {
return visitExpression(ctx.expression());
}
@Override
public Expr visitCaseExpression(HiveQLParser.CaseExpressionContext ctx) {
CaseWhenPredicate caseWhen = new CaseWhenPredicate();
Expr condition = null, result = null;
for (int i = 1; i < ctx.getChildCount(); i++) {
if (ctx.getChild(i) instanceof TerminalNodeImpl) {
if (((TerminalNodeImpl) ctx.getChild(i)).getSymbol().getType() == HiveQLLexer.KW_WHEN) {
condition = null;
result = null;
if (ctx.getChild(i + 1) instanceof HiveQLParser.ExpressionContext) {
condition = visitExpression((HiveQLParser.ExpressionContext) ctx.getChild(i + 1));
}
if (ctx.getChild(i + 3) instanceof HiveQLParser.ExpressionContext) {
result = visitExpression((HiveQLParser.ExpressionContext) ctx.getChild(i + 3));
}
if (condition != null && result != null) {
caseWhen.addWhen(condition, result);
}
} else if (((TerminalNodeImpl) ctx.getChild(i)).getSymbol().getType() == HiveQLLexer.KW_ELSE) {
result = visitExpression((HiveQLParser.ExpressionContext) ctx.getChild(i + 1));
caseWhen.setElseResult(result);
}
}
}
return caseWhen;
}
@Override
public Expr visitWhenExpression(HiveQLParser.WhenExpressionContext ctx) {
CaseWhenPredicate caseWhen = new CaseWhenPredicate();
Expr condition = null, result = null;
for (int i = 1; i < ctx.getChildCount(); i++) {
if (ctx.getChild(i) instanceof TerminalNodeImpl) {
if (((TerminalNodeImpl) ctx.getChild(i)).getSymbol().getType() == HiveQLLexer.KW_WHEN) {
condition = null;
result = null;
if (ctx.getChild(i + 1) instanceof HiveQLParser.ExpressionContext) {
condition = visitExpression((HiveQLParser.ExpressionContext) ctx.getChild(i + 1));
}
if (ctx.getChild(i + 3) instanceof HiveQLParser.ExpressionContext) {
result = visitExpression((HiveQLParser.ExpressionContext) ctx.getChild(i + 3));
}
if (condition != null && result != null) {
caseWhen.addWhen(condition, result);
}
} else if (((TerminalNodeImpl) ctx.getChild(i)).getSymbol().getType() == HiveQLLexer.KW_ELSE) {
result = visitExpression((HiveQLParser.ExpressionContext) ctx.getChild(i + 1));
caseWhen.setElseResult(result);
}
}
}
return caseWhen;
}
@Override
public Aggregation visitGroupByClause(HiveQLParser.GroupByClauseContext ctx) {
Aggregation clause = new Aggregation();
if (ctx.groupByExpression().size() > 0) {
int elementSize = ctx.groupByExpression().size();
ArrayList<Aggregation.GroupElement> groups = new ArrayList<Aggregation.GroupElement>(elementSize + 1);
ArrayList<Expr> ordinaryExprs = new ArrayList<Expr>();
int groupSize = 1;
groups.add(null);
for (int i = 0; i < ctx.groupByExpression().size(); i++) {
Expr expr = visitGroupByExpression(ctx.groupByExpression(i));
if (expr instanceof FunctionExpr) {
FunctionExpr function = (FunctionExpr) expr;
if (function.getSignature().equalsIgnoreCase("ROLLUP")) {
groupSize++;
groups.add(new Aggregation.GroupElement(Aggregation.GroupType.Rollup,
function.getParams()));
} else if (function.getSignature().equalsIgnoreCase("CUBE")) {
groupSize++;
groups.add(new Aggregation.GroupElement(Aggregation.GroupType.Cube, function.getParams()));
} else {
Collections.addAll(ordinaryExprs, function);
}
} else {
Collections.addAll(ordinaryExprs, (ColumnReferenceExpr)expr);
}
}
if (ordinaryExprs != null) {
groups.set(0, new Aggregation.GroupElement(Aggregation.GroupType.OrdinaryGroup, ordinaryExprs.toArray(new Expr[ordinaryExprs.size()])));
clause.setGroups(groups.subList(0, groupSize).toArray(new Aggregation.GroupElement[groupSize]));
} else if (groupSize > 1) {
clause.setGroups(groups.subList(1, groupSize).toArray(new Aggregation.GroupElement[groupSize - 1]));
}
}
//TODO: grouping set expression
return clause;
}
@Override
public Sort visitOrderByClause(HiveQLParser.OrderByClauseContext ctx) {
Sort clause = null;
Sort.SortSpec[] specs = null;
if (ctx.columnRefOrder().size() > 0) {
specs = new Sort.SortSpec[ctx.columnRefOrder().size()];
for (int i = 0; i < ctx.columnRefOrder().size(); i++) {
ColumnReferenceExpr column = (ColumnReferenceExpr) visitExpression(ctx.columnRefOrder().get(i).expression());
specs[i] = new Sort.SortSpec(column);
if (ctx.columnRefOrder(i).KW_DESC() != null) {
specs[i].setDescending();
}
}
clause = new Sort(specs);
}
return clause;
}
@Override
public Expr visitHavingClause(HiveQLParser.HavingClauseContext ctx) {
return visitHavingCondition(ctx.havingCondition());
}
@Override
public Expr visitClusterByClause(HiveQLParser.ClusterByClauseContext ctx) {
// TODO: It needs to consider how to support.
return null;
}
@Override
public Expr visitDistributeByClause(HiveQLParser.DistributeByClauseContext ctx) {
// TODO: It needs to consider how to support.
return null;
}
@Override
public Sort visitSortByClause(HiveQLParser.SortByClauseContext ctx) {
Sort clause = null;
Sort.SortSpec[] specs = null;
if (ctx.columnRefOrder().size() > 0) {
specs = new Sort.SortSpec[ctx.columnRefOrder().size()];
for (int i = 0; i < ctx.columnRefOrder().size(); i++) {
ColumnReferenceExpr column = (ColumnReferenceExpr) visitColumnRefOrder(ctx.columnRefOrder(i));
specs[i] = new Sort.SortSpec(column);
if (ctx.columnRefOrder(i).KW_DESC() != null) {
specs[i].setDescending();
}
}
clause = new Sort(specs);
}
return clause;
}
@Override
public Limit visitLimitClause(HiveQLParser.LimitClauseContext ctx) {
LiteralValue expr = new LiteralValue(ctx.Number().getText(), LiteralValue.LiteralType.Unsigned_Integer);
Limit limit = new Limit(expr);
return limit;
}
@Override
public Expr visitWindow_clause(HiveQLParser.Window_clauseContext ctx) {
// TODO: It needs to consider how to support.
return null;
}
@Override
public Insert visitInsertClause(HiveQLParser.InsertClauseContext ctx) {
Insert insert = new Insert();
if (ctx.KW_OVERWRITE() != null)
insert.setOverwrite();
if (ctx.tableOrPartition() != null) {
HiveQLParser.TableOrPartitionContext partitionContext = ctx.tableOrPartition();
if (partitionContext.tableName() != null) {
insert.setTableName(ctx.tableOrPartition().tableName().getText());
}
}
if (ctx.destination() != null) {
HiveQLParser.DestinationContext destination = ctx.destination();
if (destination.KW_DIRECTORY() != null) {
String location = destination.StringLiteral().getText();
location = location.replaceAll("\\'", "");
insert.setLocation(location);
} else if (destination.KW_TABLE() != null) {
if (destination.tableOrPartition() != null) {
HiveQLParser.TableOrPartitionContext partitionContext = destination.tableOrPartition();
if (partitionContext.tableName() != null) {
insert.setTableName(partitionContext.tableName().getText());
}
}
if (destination.tableFileFormat() != null) {
if (destination.tableFileFormat().KW_RCFILE() != null) {
insert.setStorageType("rcfile");
} else if (destination.tableFileFormat().KW_TEXTFILE() != null) {
insert.setStorageType("csv");
}
}
}
}
return insert;
}
@Override
public Expr visitCreateTableStatement(HiveQLParser.CreateTableStatementContext ctx) {
CreateTable createTable = null;
Map<String, String> params = new HashMap<String, String>();
if (ctx.name != null) {
createTable = new CreateTable(ctx.name.getText());
if (ctx.KW_EXTERNAL() != null) {
createTable.setExternal();
}
if (ctx.tableFileFormat() != null) {
if (ctx.tableFileFormat().KW_RCFILE() != null) {
createTable.setStorageType("rcfile");
} else if (ctx.tableFileFormat().KW_TEXTFILE() != null) {
createTable.setStorageType("csv");
}
}
if (ctx.tableRowFormat() != null) {
if (ctx.tableRowFormat().rowFormatDelimited() != null) {
String delimiter = ctx.tableRowFormat().rowFormatDelimited().tableRowFormatFieldIdentifier().getChild(3)
.getText().replaceAll("'", "");
params.put("csvfile.delimiter", SQLAnalyzer.escapeDelimiter(delimiter));
}
}
if (ctx.tableLocation() != null) {
String location = ctx.tableLocation().StringLiteral().getText();
location = location.replaceAll("'", "");
createTable.setLocation(location);
}
if (ctx.columnNameTypeList() != null) {
List<HiveQLParser.ColumnNameTypeContext> list = ctx.columnNameTypeList().columnNameType();
CreateTable.ColumnDefinition[] columns = new CreateTable.ColumnDefinition[list.size()];
for (int i = 0; i < list.size(); i++) {
HiveQLParser.ColumnNameTypeContext eachColumn = list.get(i);
String type = null;
if (eachColumn.colType().type() != null) {
if (eachColumn.colType().type().primitiveType() != null) {
HiveQLParser.PrimitiveTypeContext primitiveType = eachColumn.colType().type().primitiveType();
if (primitiveType.KW_STRING() != null) {
type = TajoDataTypes.Type.TEXT.name();
} else if (primitiveType.KW_TINYINT() != null) {
type = TajoDataTypes.Type.INT1.name();
} else if (primitiveType.KW_SMALLINT() != null) {
type = TajoDataTypes.Type.INT2.name();
} else if (primitiveType.KW_INT() != null) {
type = TajoDataTypes.Type.INT4.name();
} else if (primitiveType.KW_BIGINT() != null) {
type = TajoDataTypes.Type.INT8.name();
} else if (primitiveType.KW_FLOAT() != null) {
type = TajoDataTypes.Type.FLOAT4.name();
} else if (primitiveType.KW_DOUBLE() != null) {
type = TajoDataTypes.Type.FLOAT8.name();
} else if (primitiveType.KW_DECIMAL() != null) {
type = TajoDataTypes.Type.DECIMAL.name();
} else if (primitiveType.KW_BOOLEAN() != null) {
type = TajoDataTypes.Type.BOOLEAN.name();
} else if (primitiveType.KW_DATE() != null) {
type = TajoDataTypes.Type.DATE.name();
} else if (primitiveType.KW_DATETIME() != null) {
//TODO
} else if (primitiveType.KW_TIMESTAMP() != null) {
type = TajoDataTypes.Type.TIMESTAMP.name();
}
columns[i] = new CreateTable.ColumnDefinition(eachColumn.colName.Identifier().getText(), type);
}
}
}
if (columns != null) {
createTable.setTableElements(columns);
}
if (!params.isEmpty()) {
createTable.setParams(params);
}
}
}
return createTable;
}
@Override
public Expr visitDropTableStatement(HiveQLParser.DropTableStatementContext ctx) {
DropTable dropTable = new DropTable(ctx.tableName().getText(), false);
return dropTable;
}
/**
* This class provides and implementation for a case insensitive token checker
* for the lexical analysis part of antlr. By converting the token stream into
* upper case at the time when lexical rules are checked, this class ensures that the
* lexical rules need to just match the token with upper case letters as opposed to
* combination of upper case and lower case characteres. This is purely used for matching lexical
* rules. The actual token text is stored in the same way as the user input without
* actually converting it into an upper case. The token values are generated by the consume()
* function of the super class ANTLRStringStream. The LA() function is the lookahead funtion
* and is purely used for matching lexical rules. This also means that the grammar will only
* accept capitalized tokens in case it is run from other tools like antlrworks which
* do not have the ANTLRNoCaseStringStream implementation.
*/
public class ANTLRNoCaseStringStream extends ANTLRInputStream {
public ANTLRNoCaseStringStream(String input) {
super(input);
}
@Override
public int LA(int i) {
int returnChar = super.LA(i);
if (returnChar == CharStream.EOF) {
return returnChar;
} else if (returnChar == 0) {
return returnChar;
}
return Character.toUpperCase((char) returnChar);
}
}
} | tajo-core/tajo-core-backend/src/main/java/org/apache/tajo/engine/parser/HiveQLAnalyzer.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.tajo.engine.parser;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.TerminalNodeImpl;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tajo.algebra.*;
import org.apache.tajo.common.TajoDataTypes;
import org.apache.tajo.engine.parser.HiveQLParser.TableAllColumnsContext;
import java.math.BigInteger;
import java.util.*;
public class HiveQLAnalyzer extends HiveQLParserBaseVisitor<Expr> {
private static final Log LOG = LogFactory.getLog(HiveQLAnalyzer.class.getName());
private HiveQLParser parser;
public Expr parse(String sql) {
HiveQLLexer lexer = new HiveQLLexer(new ANTLRNoCaseStringStream(sql));
CommonTokenStream tokens = new CommonTokenStream(lexer);
parser = new HiveQLParser(tokens);
parser.setBuildParseTree(true);
HiveQLParser.StatementContext context;
try {
context = parser.statement();
} catch (SQLParseError e) {
throw new SQLSyntaxError(e);
}
return visit(context);
}
@Override
public Expr visitStatement(HiveQLParser.StatementContext ctx) {
return visitExecStatement(ctx.execStatement());
}
@Override
public Expr visitQueryStatement(HiveQLParser.QueryStatementContext ctx) {
Expr current = null;
if (ctx.body != null) {
current = visitBody(ctx.body(0));
}
if (ctx.regular_body() != null) {
current = visitRegular_body(ctx.regular_body());
}
return current;
}
@Override
public Expr visitBody(HiveQLParser.BodyContext ctx) {
Expr current = null;
Insert insert = null;
Projection select = null;
if (ctx.insertClause() != null) {
insert = visitInsertClause(ctx.insertClause());
}
if (ctx.selectClause() != null) {
select = (Projection) visitSelectClause(ctx.selectClause());
if (ctx.selectClause().KW_DISTINCT() != null) {
select.setDistinct();
}
}
for (int i = 0; i < ctx.getParent().getChildCount(); i++) {
if (ctx.getParent().getChild(i) instanceof HiveQLParser.FromClauseContext) {
HiveQLParser.FromClauseContext fromClauseContext = (HiveQLParser.FromClauseContext) ctx.getParent().getChild(i);
Expr from = visitFromClause(fromClauseContext);
current = from;
}
}
if (ctx.whereClause() != null) {
Selection where = new Selection(visitWhereClause(ctx.whereClause()));
where.setChild(current);
current = where;
}
if (ctx.groupByClause() != null) {
Aggregation aggregation = visitGroupByClause(ctx.groupByClause());
aggregation.setChild(current);
current = aggregation;
if (ctx.havingClause() != null) {
Expr havingCondition = visitHavingClause(ctx.havingClause());
Having having = new Having(havingCondition);
having.setChild(current);
current = having;
}
}
if (ctx.orderByClause() != null) {
Sort sort = visitOrderByClause(ctx.orderByClause());
sort.setChild(current);
current = sort;
}
if (ctx.clusterByClause() != null) {
visitClusterByClause(ctx.clusterByClause());
}
if (ctx.distributeByClause() != null) {
visitDistributeByClause(ctx.distributeByClause());
}
if (ctx.sortByClause() != null) {
Sort sort = visitSortByClause(ctx.sortByClause());
sort.setChild(current);
current = sort;
}
if (ctx.window_clause() != null) {
Expr window = visitWindow_clause(ctx.window_clause());
}
if (ctx.limitClause() != null) {
Limit limit = visitLimitClause(ctx.limitClause());
limit.setChild(current);
current = limit;
}
Projection projection = new Projection();
projection.setNamedExprs(select.getNamedExprs());
if (current != null)
projection.setChild(current);
if (select.isDistinct())
projection.setDistinct();
if (insert != null) {
insert.setSubQuery(projection);
current = insert;
} else {
current = projection;
}
return current;
}
@Override
public Expr visitRegular_body(HiveQLParser.Regular_bodyContext ctx) {
Expr current = null;
Insert insert = null;
if (ctx.selectStatement() != null) {
current = visitSelectStatement(ctx.selectStatement());
} else {
Projection select = null;
if (ctx.insertClause() != null) {
insert = visitInsertClause(ctx.insertClause());
}
if (ctx.selectClause() != null) {
select = (Projection) visitSelectClause(ctx.selectClause());
if (ctx.selectClause().KW_DISTINCT() != null) {
select.setDistinct();
}
}
if (ctx.fromClause() != null) {
Expr from = visitFromClause(ctx.fromClause());
current = from;
}
if (ctx.whereClause() != null) {
Selection where = new Selection(visitWhereClause(ctx.whereClause()));
where.setChild(current);
current = where;
}
if (ctx.groupByClause() != null) {
Aggregation aggregation = visitGroupByClause(ctx.groupByClause());
aggregation.setChild(current);
current = aggregation;
if (ctx.havingClause() != null) {
Expr havingCondition = visitHavingClause(ctx.havingClause());
Having having = new Having(havingCondition);
having.setChild(current);
current = having;
}
}
if (ctx.orderByClause() != null) {
Sort sort = visitOrderByClause(ctx.orderByClause());
sort.setChild(current);
current = sort;
}
if (ctx.clusterByClause() != null) {
visitClusterByClause(ctx.clusterByClause());
}
if (ctx.distributeByClause() != null) {
visitDistributeByClause(ctx.distributeByClause());
}
if (ctx.sortByClause() != null) {
Sort sort = visitSortByClause(ctx.sortByClause());
sort.setChild(current);
current = sort;
}
if (ctx.window_clause() != null) {
Expr window = visitWindow_clause(ctx.window_clause());
}
if (ctx.limitClause() != null) {
Limit limit = visitLimitClause(ctx.limitClause());
limit.setChild(current);
current = limit;
}
Projection projection = new Projection();
projection.setNamedExprs(select.getNamedExprs());
if (current != null)
projection.setChild(current);
if (select.isDistinct())
projection.setDistinct();
if (insert != null) {
insert.setSubQuery(projection);
current = insert;
} else {
current = projection;
}
}
return current;
}
/**
* This method implemented for parsing union all clause.
*
* @param ctx
* @return
*/
@Override
public Expr visitQueryStatementExpression(HiveQLParser.QueryStatementExpressionContext ctx) {
Expr left = null, right = null, current = null;
if (ctx.queryStatement() != null) {
if (ctx.queryStatement().size() == 1)
return visitQueryStatement(ctx.queryStatement(0));
for (int i = 0; i < ctx.queryStatement().size(); i++) {
if (i == 0)
current = visitQueryStatement(ctx.queryStatement(i));
else
left = current;
if (i > 0) {
right = visitQueryStatement(ctx.queryStatement(i));
current = new SetOperation(OpType.Union, left, right, false);
}
}
}
return current;
}
@Override
public Expr visitSelectStatement(HiveQLParser.SelectStatementContext ctx) {
Expr current = null;
Projection select = (Projection) visitSelectClause(ctx.selectClause());
if (ctx.selectClause().KW_DISTINCT() != null) {
select.setDistinct();
}
Expr from = visitFromClause(ctx.fromClause());
current = from;
if (ctx.whereClause() != null) {
Selection where = new Selection(visitWhereClause(ctx.whereClause()));
where.setChild(current);
current = where;
}
if (ctx.groupByClause() != null) {
Aggregation aggregation = visitGroupByClause(ctx.groupByClause());
aggregation.setChild(current);
current = aggregation;
if (ctx.havingClause() != null) {
Expr havingCondition = visitHavingClause(ctx.havingClause());
Having having = new Having(havingCondition);
having.setChild(current);
current = having;
}
}
if (ctx.orderByClause() != null) {
Sort sort = visitOrderByClause(ctx.orderByClause());
sort.setChild(current);
current = sort;
}
if (ctx.clusterByClause() != null) {
visitClusterByClause(ctx.clusterByClause());
}
if (ctx.distributeByClause() != null) {
visitDistributeByClause(ctx.distributeByClause());
}
if (ctx.sortByClause() != null) {
Sort sort = visitSortByClause(ctx.sortByClause());
sort.setChild(current);
current = sort;
}
if (ctx.window_clause() != null) {
Expr window = visitWindow_clause(ctx.window_clause());
}
if (ctx.limitClause() != null) {
Limit limit = visitLimitClause(ctx.limitClause());
limit.setChild(current);
current = limit;
}
Projection projection = new Projection();
projection.setNamedExprs(select.getNamedExprs());
if (current != null)
projection.setChild(current);
if (select.isDistinct())
projection.setDistinct();
current = projection;
return current;
}
@Override
public Expr visitFromClause(HiveQLParser.FromClauseContext ctx) {
return visitJoinSource(ctx.joinSource());
}
@Override
public Expr visitJoinSource(HiveQLParser.JoinSourceContext ctx) {
Expr[] relations = null;
RelationList relationList = null;
if (ctx.fromSource() != null) {
int fromCount = ctx.fromSource().size();
int uniqueJoinCount = ctx.uniqueJoinSource().size();
relations = new Expr[1];
Join current = null, parent = null;
JoinType type = null;
Expr left = null, right = null, condition = null;
if (fromCount == 1) {
relations[0] = visitFromSource(ctx.fromSource(0));
} else {
left = visitFromSource((HiveQLParser.FromSourceContext) ctx.getChild(0));
for (int i = 1; i < ctx.getChildCount(); i++) {
type = null;
right = null;
condition = null;
if (ctx.getChild(i) instanceof HiveQLParser.JoinTokenContext) {
type = getJoinType((HiveQLParser.JoinTokenContext) ctx.getChild(i));
if (i > 1)
left = parent;
if (i + 1 < ctx.getChildCount() && ctx.getChild(i + 1) instanceof HiveQLParser.FromSourceContext) {
right = visitFromSource((HiveQLParser.FromSourceContext) ctx.getChild(i + 1));
}
if (i + 3 < ctx.getChildCount() && ctx.getChild(i + 3) instanceof HiveQLParser.ExpressionContext) {
condition = visitExpression((HiveQLParser.ExpressionContext) ctx.getChild(i + 3));
}
if (type != null) {
current = new Join(type);
current.setLeft(left);
current.setRight(right);
if (condition != null)
current.setQual(condition);
parent = current;
}
}
}
relations[0] = current;
}
//TODO: implement unique join.
relationList = new RelationList(relations);
}
return relationList;
}
public JoinType getJoinType(HiveQLParser.JoinTokenContext context) {
JoinType type = JoinType.INNER;
if (context.KW_INNER() != null) {
type = JoinType.INNER;
}
if (context.KW_LEFT() != null && context.KW_OUTER() != null) {
type = JoinType.LEFT_OUTER;
}
if (context.KW_RIGHT() != null && context.KW_OUTER() != null) {
type = JoinType.RIGHT_OUTER;
}
if (context.KW_CROSS() != null) {
type = JoinType.CROSS;
}
if (context.KW_FULL() != null) {
type = JoinType.FULL_OUTER;
}
if (context.KW_SEMI() != null) {
type = null;
}
return type;
}
@Override
public Expr visitFromSource(HiveQLParser.FromSourceContext ctx) {
Expr current = null;
if (ctx.Identifier() != null && ctx.LPAREN() != null) {
current = new LiteralValue(ctx.Identifier().getText(), LiteralValue.LiteralType.String);
}
if (ctx.tableSource() != null) {
current = visitTableSource(ctx.tableSource());
}
if (ctx.subQuerySource() != null) {
current = visitSubQuerySource(ctx.subQuerySource());
String tableAlias = "";
for (int i = 0; i < ctx.subQuerySource().getChildCount(); i++) {
if (ctx.subQuerySource().getChild(i) instanceof HiveQLParser.IdentifierContext) {
tableAlias = (ctx.subQuerySource().getChild(i)).getText();
}
}
TablePrimarySubQuery subQuery = new TablePrimarySubQuery(tableAlias, current);
current = subQuery;
}
// TODO: implement lateralView
return current;
}
@Override
public Expr visitSubQuerySource(HiveQLParser.SubQuerySourceContext ctx) {
Expr current = visitQueryStatementExpression(ctx.queryStatementExpression());
return current;
}
@Override
public Expr visitTableSource(HiveQLParser.TableSourceContext ctx) {
String tableName = "", alias = "";
if (ctx.tableName() != null)
tableName = ctx.tableName().getText();
if (ctx.alias != null) {
alias = ctx.alias.getText();
for (String token : HiveQLParser.tokenNames) {
if (token.replaceAll("'", "").equalsIgnoreCase(alias))
alias = "";
}
}
Relation relation = new Relation(tableName);
if (!alias.equals(""))
relation.setAlias(alias);
return relation;
}
@Override
public Expr visitSelectList(HiveQLParser.SelectListContext ctx) {
Expr current = null;
Projection projection = new Projection();
NamedExpr[] targets = new NamedExpr[ctx.selectItem().size()];
for (int i = 0; i < targets.length; i++) {
targets[i] = visitSelectItem(ctx.selectItem(i));
}
projection.setNamedExprs(targets);
current = projection;
return current;
}
@Override
public NamedExpr visitSelectItem(HiveQLParser.SelectItemContext ctx) {
NamedExpr target = null;
if (ctx.selectExpression() != null) {
target = new NamedExpr(visitSelectExpression(ctx.selectExpression()));
} else if (ctx.window_specification() != null) {
// TODO: if there is a window specification clause, we should handle it properly.
}
if (ctx.identifier().size() > 0 && target != null) {
target.setAlias(ctx.identifier(0).getText());
}
return target;
}
@Override
public Expr visitSelectExpression(HiveQLParser.SelectExpressionContext ctx) {
Expr current = null;
if (ctx.tableAllColumns() != null) {
current = visitTableAllColumns(ctx.tableAllColumns());
} else {
if (ctx.expression() != null) {
current = visitExpression(ctx.expression());
}
}
return current;
}
@Override
public Expr visitTableAllColumns(TableAllColumnsContext ctx) {
QualifiedAsteriskExpr target = new QualifiedAsteriskExpr();
if (ctx.tableName() != null) {
target.setQualifier(ctx.tableName().getText());
}
return target;
}
@Override
public Expr visitExpression(HiveQLParser.ExpressionContext ctx) {
Expr current = visitPrecedenceOrExpression(ctx.precedenceOrExpression());
return current;
}
@Override
public Expr visitPrecedenceOrExpression(HiveQLParser.PrecedenceOrExpressionContext ctx) {
Expr current = null, left = null, right = null;
for (int i = 0; i < ctx.precedenceAndExpression().size(); i++) {
if (i == 0) {
left = visitPrecedenceAndExpression(ctx.precedenceAndExpression(i));
current = left;
} else {
left = current;
right = visitPrecedenceAndExpression(ctx.precedenceAndExpression(i));
current = new BinaryOperator(OpType.Or, left, right);
}
}
return current;
}
/**
* This method parse AND expressions at WHERE clause.
* And this convert 'x BETWEEN y AND z' expression into 'x >= y AND x <= z' expression
* because Tajo doesn't provide 'BETWEEN' expression.
*
* @param ctx
* @return
*/
@Override
public Expr visitPrecedenceAndExpression(HiveQLParser.PrecedenceAndExpressionContext ctx) {
Expr current = null, left = null, right = null;
for (int i = 0; i < ctx.precedenceNotExpression().size(); i++) {
Expr min = null, max = null;
if (ctx.precedenceNotExpression(i).precedenceEqualExpression() != null) {
HiveQLParser.PrecedenceEqualExpressionContext expressionContext = ctx.precedenceNotExpression(i)
.precedenceEqualExpression();
if (expressionContext.KW_BETWEEN() != null) {
if (expressionContext.min != null) {
min = visitPrecedenceBitwiseOrExpression(expressionContext.min);
}
if (expressionContext.max != null) {
max = visitPrecedenceBitwiseOrExpression(expressionContext.max);
}
}
}
if (min != null && max != null) {
left = visitPrecedenceNotExpression(ctx.precedenceNotExpression(i));
if (left != null) {
if (i == 0) {
BinaryOperator minOperator = new BinaryOperator(OpType.GreaterThanOrEquals, left, min);
BinaryOperator maxOperator = new BinaryOperator(OpType.LessThanOrEquals, left, max);
current = new BinaryOperator(OpType.And, minOperator, maxOperator);
} else {
BinaryOperator minOperator = new BinaryOperator(OpType.GreaterThanOrEquals, left, min);
current = new BinaryOperator(OpType.And, current, minOperator);
BinaryOperator maxOperator = new BinaryOperator(OpType.LessThanOrEquals, left, max);
current = new BinaryOperator(OpType.And, current, maxOperator);
}
}
} else {
if (i == 0) {
left = visitPrecedenceNotExpression(ctx.precedenceNotExpression(i));
current = left;
} else {
left = current;
right = visitPrecedenceNotExpression(ctx.precedenceNotExpression(i));
current = new BinaryOperator(OpType.And, left, right);
}
}
}
return current;
}
@Override
public Expr visitPrecedenceNotExpression(HiveQLParser.PrecedenceNotExpressionContext ctx) {
HiveQLParser.PrecedenceEqualExpressionContext expressionContext = ctx.precedenceEqualExpression();
Expr current = visitPrecedenceEqualExpression(expressionContext);
return current;
}
/**
* This method parse operators for equals expressions as follows:
* =, <>, !=, >=, >, <=, <, IN, NOT IN, LIKE, REGEXP, RLIKE
* <p/>
* In this case, this make RuntimeException>
*
* @param ctx
* @return
*/
@Override
public Expr visitPrecedenceEqualExpression(HiveQLParser.PrecedenceEqualExpressionContext ctx) {
Expr current = null, left = null, right = null, min = null, max = null;
OpType type = null;
boolean isNot = false, isIn = false;
for (int i = 0; i < ctx.getChildCount(); i++) {
if (ctx.getChild(i) instanceof HiveQLParser.PrecedenceBitwiseOrExpressionContext) {
if (i == 0) {
left = visitPrecedenceBitwiseOrExpression((HiveQLParser.PrecedenceBitwiseOrExpressionContext) ctx.getChild(i));
} else {
right = visitPrecedenceBitwiseOrExpression((HiveQLParser.PrecedenceBitwiseOrExpressionContext) ctx.getChild(i));
}
} else if (ctx.getChild(i) instanceof HiveQLParser.ExpressionsContext) {
right = visitExpressions((HiveQLParser.ExpressionsContext) ctx.getChild(i));
} else if (ctx.getChild(i) instanceof TerminalNodeImpl) {
int symbolType = ((TerminalNodeImpl) ctx.getChild(i)).getSymbol().getType();
switch (symbolType) {
case HiveQLLexer.KW_NOT:
isNot = true;
break;
case HiveQLLexer.KW_IN:
isIn = true;
break;
default:
break;
}
} else if (ctx.getChild(i) instanceof HiveQLParser.PrecedenceEqualOperatorContext
|| ctx.getChild(i) instanceof HiveQLParser.PrecedenceEqualNegatableOperatorContext) {
String keyword = ctx.getChild(i).getText().toUpperCase();
if (keyword.equals(">")) {
type = OpType.GreaterThan;
} else if (keyword.equals("<=>")) {
throw new RuntimeException("Unexpected operator : <=>");
} else if (keyword.equals("=")) {
type = OpType.Equals;
} else if (keyword.equals("<=")) {
type = OpType.LessThanOrEquals;
} else if (keyword.equals("<")) {
type = OpType.LessThan;
} else if (keyword.equals(">=")) {
type = OpType.GreaterThanOrEquals;
} else if (keyword.equals("<>")) {
type = OpType.NotEquals;
} else if (keyword.equals("!=")) {
type = OpType.NotEquals;
} else if (keyword.equals("REGEXP")) {
type = OpType.Regexp;
} else if (keyword.equals("RLIKE")) {
type = OpType.Regexp;
} else if (keyword.equals("LIKE")) {
type = OpType.LikePredicate;
}
}
}
if (type != null && right != null) {
if (type.equals(OpType.LikePredicate)) {
PatternMatchPredicate like = new PatternMatchPredicate(OpType.LikePredicate,
isNot, left, right);
current = like;
} else if (type.equals(OpType.Regexp)) {
PatternMatchPredicate regex = new PatternMatchPredicate(OpType.Regexp, isNot, left, right);
current = regex;
} else {
BinaryOperator binaryOperator = new BinaryOperator(type, left, right);
current = binaryOperator;
}
} else if (isIn) {
InPredicate inPredicate = new InPredicate(left, right, isNot);
current = inPredicate;
} else {
current = left;
}
return current;
}
@Override
public ValueListExpr visitExpressions(HiveQLParser.ExpressionsContext ctx) {
int size = ctx.expression().size();
Expr[] exprs = new Expr[size];
for (int i = 0; i < size; i++) {
exprs[i] = visitExpression(ctx.expression(i));
}
return new ValueListExpr(exprs);
}
@Override
public Expr visitPrecedenceBitwiseOrExpression(HiveQLParser.PrecedenceBitwiseOrExpressionContext ctx) {
int expressionCount = ctx.precedenceAmpersandExpression().size();
Expr current = null, left = null, right = null, parentLeft, parentRight;
OpType type = null, parentType = null;
for (int i = 0; i < expressionCount; i += 2) {
int operatorIndex = (i == 0) ? 0 : i - 1;
if (ctx.precedenceBitwiseOrOperator(operatorIndex) != null) {
type = getPrecedenceBitwiseOrOperator(ctx.precedenceBitwiseOrOperator(operatorIndex));
}
if (i == 0) {
left = visitPrecedenceAmpersandExpression(ctx.precedenceAmpersandExpression(i));
if (ctx.precedenceAmpersandExpression(i + 1) != null)
right = visitPrecedenceAmpersandExpression(ctx.precedenceAmpersandExpression(i + 1));
} else {
parentType = getPrecedenceBitwiseOrOperator((ctx.precedenceBitwiseOrOperator(operatorIndex - 1)));
parentLeft = visitPrecedenceAmpersandExpression(ctx.precedenceAmpersandExpression(i - 2));
parentRight = visitPrecedenceAmpersandExpression(ctx.precedenceAmpersandExpression(i - 1));
left = new BinaryOperator(parentType, parentLeft, parentRight);
right = visitPrecedenceAmpersandExpression(ctx.precedenceAmpersandExpression(i));
}
if (right != null) {
current = new BinaryOperator(type, left, right);
} else {
current = left;
}
}
return current;
}
public OpType getPrecedenceBitwiseOrOperator(HiveQLParser.PrecedenceBitwiseOrOperatorContext ctx) {
OpType type = null;
// TODO: It needs to consider how to support.
return type;
}
@Override
public Expr visitPrecedenceAmpersandExpression(HiveQLParser.PrecedenceAmpersandExpressionContext ctx) {
int expressionCount = ctx.precedencePlusExpression().size();
Expr current = null, left = null, right = null, parentLeft, parentRight;
OpType type = null, parentType = null;
for (int i = 0; i < expressionCount; i += 2) {
int operatorIndex = (i == 0) ? 0 : i - 1;
if (ctx.precedenceAmpersandOperator(operatorIndex) != null) {
type = getPrecedenceAmpersandOperator(ctx.precedenceAmpersandOperator(operatorIndex));
}
if (i == 0) {
left = visitPrecedencePlusExpression(ctx.precedencePlusExpression(i));
if (ctx.precedencePlusExpression(i + 1) != null)
right = visitPrecedencePlusExpression(ctx.precedencePlusExpression(i + 1));
} else {
parentType = getPrecedenceAmpersandOperator((ctx.precedenceAmpersandOperator(operatorIndex - 1)));
parentLeft = visitPrecedencePlusExpression(ctx.precedencePlusExpression(i - 2));
parentRight = visitPrecedencePlusExpression(ctx.precedencePlusExpression(i - 1));
left = new BinaryOperator(parentType, parentLeft, parentRight);
right = visitPrecedencePlusExpression(ctx.precedencePlusExpression(i));
}
if (right != null) {
current = new BinaryOperator(type, left, right);
} else {
current = left;
}
}
return current;
}
public OpType getPrecedenceAmpersandOperator(HiveQLParser.PrecedenceAmpersandOperatorContext ctx) {
OpType type = null;
// TODO: It needs to consider how to support.
return type;
}
@Override
public Expr visitPrecedencePlusExpression(HiveQLParser.PrecedencePlusExpressionContext ctx) {
int expressionCount = ctx.precedenceStarExpression().size();
Expr current = null, left = null, right = null, parentLeft, parentRight;
OpType type = null, parentType = null;
for (int i = 0; i < expressionCount; i += 2) {
int operatorIndex = (i == 0) ? 0 : i - 1;
if (ctx.precedencePlusOperator(operatorIndex) != null) {
type = getPrecedencePlusOperator(ctx.precedencePlusOperator(operatorIndex));
}
if (i == 0) {
left = visitPrecedenceStarExpression(ctx.precedenceStarExpression(i));
if (ctx.precedenceStarExpression(i + 1) != null)
right = visitPrecedenceStarExpression(ctx.precedenceStarExpression(i + 1));
} else {
parentType = getPrecedencePlusOperator((ctx.precedencePlusOperator(operatorIndex - 1)));
parentLeft = visitPrecedenceStarExpression(ctx.precedenceStarExpression(i - 2));
parentRight = visitPrecedenceStarExpression(ctx.precedenceStarExpression(i - 1));
left = new BinaryOperator(parentType, parentLeft, parentRight);
right = visitPrecedenceStarExpression(ctx.precedenceStarExpression(i));
}
if (right != null) {
current = new BinaryOperator(type, left, right);
} else {
current = left;
}
}
return current;
}
public OpType getPrecedencePlusOperator(HiveQLParser.PrecedencePlusOperatorContext ctx) {
OpType type = null;
if (ctx.MINUS() != null) {
type = OpType.Minus;
} else if (ctx.PLUS() != null) {
type = OpType.Plus;
}
return type;
}
@Override
public Expr visitPrecedenceStarExpression(HiveQLParser.PrecedenceStarExpressionContext ctx) {
int expressionCount = ctx.precedenceBitwiseXorExpression().size();
Expr current = null, left = null, right = null, parentLeft, parentRight;
OpType type = null, parentType = null;
for (int i = 0; i < expressionCount; i += 2) {
int operatorIndex = (i == 0) ? 0 : i - 1;
if (ctx.precedenceStarOperator(operatorIndex) != null) {
type = getPrecedenceStarOperator(ctx.precedenceStarOperator(operatorIndex));
}
if (i == 0) {
left = visitPrecedenceBitwiseXorExpression(ctx.precedenceBitwiseXorExpression(i));
if (ctx.precedenceBitwiseXorExpression(i + 1) != null)
right = visitPrecedenceBitwiseXorExpression(ctx.precedenceBitwiseXorExpression(i + 1));
} else {
parentType = getPrecedenceStarOperator((ctx.precedenceStarOperator(operatorIndex - 1)));
parentLeft = visitPrecedenceBitwiseXorExpression(ctx.precedenceBitwiseXorExpression(i - 2));
parentRight = visitPrecedenceBitwiseXorExpression(ctx.precedenceBitwiseXorExpression(i - 1));
left = new BinaryOperator(parentType, parentLeft, parentRight);
right = visitPrecedenceBitwiseXorExpression(ctx.precedenceBitwiseXorExpression(i));
}
if (right != null) {
current = new BinaryOperator(type, left, right);
} else {
current = left;
}
}
return current;
}
public OpType getPrecedenceStarOperator(HiveQLParser.PrecedenceStarOperatorContext ctx) {
OpType type = null;
if (ctx.DIV() != null) {
type = OpType.Divide;
} else if (ctx.DIVIDE() != null) {
type = OpType.Divide;
} else if (ctx.MOD() != null) {
type = OpType.Modular;
} else if (ctx.STAR() != null) {
type = OpType.Multiply;
}
return type;
}
@Override
public Expr visitPrecedenceBitwiseXorExpression(HiveQLParser.PrecedenceBitwiseXorExpressionContext ctx) {
int expressionCount = ctx.precedenceUnarySuffixExpression().size();
Expr current = null, left = null, right = null, parentLeft, parentRight;
OpType type = null, parentType = null;
for (int i = 0; i < expressionCount; i += 2) {
int operatorIndex = (i == 0) ? 0 : i - 1;
if (ctx.precedenceBitwiseXorOperator(operatorIndex) != null) {
type = getPrecedenceBitwiseXorOperator(ctx.precedenceBitwiseXorOperator(operatorIndex));
}
if (i == 0) {
left = visitPrecedenceUnarySuffixExpression(ctx.precedenceUnarySuffixExpression(i));
if (ctx.precedenceUnarySuffixExpression(i + 1) != null)
right = visitPrecedenceUnarySuffixExpression(ctx.precedenceUnarySuffixExpression(i + 1));
} else {
parentType = getPrecedenceBitwiseXorOperator((ctx.precedenceBitwiseXorOperator(operatorIndex - 1)));
parentLeft = visitPrecedenceUnarySuffixExpression(ctx.precedenceUnarySuffixExpression(i - 2));
parentRight = visitPrecedenceUnarySuffixExpression(ctx.precedenceUnarySuffixExpression(i - 1));
left = new BinaryOperator(parentType, parentLeft, parentRight);
right = visitPrecedenceUnarySuffixExpression(ctx.precedenceUnarySuffixExpression(i));
}
if (right != null) {
current = new BinaryOperator(type, left, right);
} else {
current = left;
}
}
return current;
}
public OpType getPrecedenceBitwiseXorOperator(HiveQLParser.PrecedenceBitwiseXorOperatorContext ctx) {
OpType type = null;
// TODO: It needs to consider how to support.
return type;
}
@Override
public Expr visitPrecedenceUnarySuffixExpression(HiveQLParser.PrecedenceUnarySuffixExpressionContext ctx) {
Expr current = visitPrecedenceUnaryPrefixExpression(ctx.precedenceUnaryPrefixExpression());
if (ctx.nullCondition() != null) {
boolean isNot = ctx.nullCondition().KW_NOT() == null ? false : true;
IsNullPredicate isNullPredicate = new IsNullPredicate(isNot, (ColumnReferenceExpr) current);
current = isNullPredicate;
}
return current;
}
@Override
public Expr visitPrecedenceUnaryPrefixExpression(HiveQLParser.PrecedenceUnaryPrefixExpressionContext ctx) {
Expr current = visitPrecedenceFieldExpression(ctx.precedenceFieldExpression());
return current;
}
@Override
public Expr visitNullCondition(HiveQLParser.NullConditionContext ctx) {
return new NullLiteral();
}
@Override
public Expr visitPrecedenceFieldExpression(HiveQLParser.PrecedenceFieldExpressionContext ctx) {
Expr current = visitAtomExpression(ctx.atomExpression());
if (ctx.DOT().size() > 0) {
ColumnReferenceExpr column = new ColumnReferenceExpr(ctx.identifier(0).getText());
ColumnReferenceExpr table = (ColumnReferenceExpr) current;
column.setQualifier(table.getName());
current = column;
}
return current;
}
@Override
public Expr visitAtomExpression(HiveQLParser.AtomExpressionContext ctx) {
Expr current = null;
if (ctx.KW_NULL() != null) {
current = new NullLiteral();
}
if (ctx.constant() != null) {
current = visitConstant(ctx.constant());
}
if (ctx.function() != null) {
current = visitFunction(ctx.function());
}
if (ctx.castExpression() != null) {
current = visitCastExpression(ctx.castExpression());
}
if (ctx.caseExpression() != null) {
current = visitCaseExpression(ctx.caseExpression());
}
if (ctx.whenExpression() != null) {
current = visitWhenExpression(ctx.whenExpression());
}
if (ctx.tableOrColumn() != null) {
current = visitTableOrColumn(ctx.tableOrColumn());
} else {
if (ctx.LPAREN() != null && ctx.RPAREN() != null) {
current = visitExpression(ctx.expression());
}
}
return current;
}
@Override
public Expr visitTableOrColumn(HiveQLParser.TableOrColumnContext ctx) {
ColumnReferenceExpr columnReferenceExpr = new ColumnReferenceExpr(ctx.identifier().getText());
return columnReferenceExpr;
}
@Override
public Expr visitIdentifier(HiveQLParser.IdentifierContext ctx) {
Expr current = null;
if (ctx.nonReserved() != null) {
current = new LiteralValue(ctx.nonReserved().getText(), LiteralValue.LiteralType.String);
} else {
current = new LiteralValue(ctx.Identifier().getText(), LiteralValue.LiteralType.String);
}
return current;
}
@Override
public LiteralValue visitConstant(HiveQLParser.ConstantContext ctx) {
LiteralValue literalValue = null;
if (ctx.StringLiteral() != null) {
String value = ctx.StringLiteral().getText();
String strValue = "";
if ((value.startsWith("'") && value.endsWith("'")) || value.startsWith("\"") && value.endsWith("\"")) {
strValue = value.substring(1, value.length() - 1);
} else {
strValue = value;
}
literalValue = new LiteralValue(strValue, LiteralValue.LiteralType.String);
} else if (ctx.TinyintLiteral() != null) {
literalValue = new LiteralValue(ctx.TinyintLiteral().getSymbol().getText(),
LiteralValue.LiteralType.Unsigned_Integer);
} else if (ctx.BigintLiteral() != null) {
literalValue = new LiteralValue(ctx.BigintLiteral().getSymbol().getText(),
LiteralValue.LiteralType.Unsigned_Large_Integer);
} else if (ctx.DecimalLiteral() != null) {
literalValue = new LiteralValue(ctx.DecimalLiteral().getSymbol().getText(),
LiteralValue.LiteralType.Unsigned_Integer);
} else if (ctx.Number() != null) {
try {
float floatValue = NumberUtils.createFloat(ctx.getText());
literalValue = new LiteralValue(ctx.Number().getSymbol().getText(), LiteralValue.LiteralType.Unsigned_Float);
} catch (NumberFormatException nf) {
}
// TODO: double type
try {
BigInteger bigIntegerVallue = NumberUtils.createBigInteger(ctx.getText());
literalValue = new LiteralValue(ctx.Number().getSymbol().getText(),
LiteralValue.LiteralType.Unsigned_Large_Integer);
} catch (NumberFormatException nf) {
}
try {
int intValue = NumberUtils.createInteger(ctx.getText());
literalValue = new LiteralValue(ctx.Number().getSymbol().getText(), LiteralValue.LiteralType.Unsigned_Integer);
} catch (NumberFormatException nf) {
}
} else if (ctx.SmallintLiteral() != null) {
literalValue = new LiteralValue(ctx.SmallintLiteral().getSymbol().getText(),
LiteralValue.LiteralType.Unsigned_Integer);
} else if (ctx.booleanValue() != null) {
// TODO: boolean type
}
return literalValue;
}
@Override
public Expr visitFunction(HiveQLParser.FunctionContext ctx) {
Expr current = null;
String signature = ctx.functionName().getText();
boolean isDistinct = false;
if (ctx.getChild(2) != null) {
if (ctx.getChild(2) instanceof TerminalNodeImpl && ctx.getChild(2).getText().equalsIgnoreCase("DISTINCT")) {
isDistinct = true;
}
}
if (signature.equalsIgnoreCase("MIN")
|| signature.equalsIgnoreCase("MAX")
|| signature.equalsIgnoreCase("SUM")
|| signature.equalsIgnoreCase("AVG")
|| signature.equalsIgnoreCase("COUNT")
) {
if (ctx.selectExpression().size() > 1) {
throw new RuntimeException("Exactly expected one argument.");
}
if (ctx.selectExpression().size() == 0) {
CountRowsFunctionExpr countRowsFunctionExpr = new CountRowsFunctionExpr();
current = countRowsFunctionExpr;
} else {
GeneralSetFunctionExpr setFunctionExpr = new GeneralSetFunctionExpr(signature, isDistinct,
visitSelectExpression(ctx.selectExpression(0)));
current = setFunctionExpr;
}
} else {
FunctionExpr functionExpr = new FunctionExpr(signature);
Expr[] params = new Expr[ctx.selectExpression().size()];
for (int i = 0; i < ctx.selectExpression().size(); i++) {
params[i] = visitSelectExpression(ctx.selectExpression(i));
}
functionExpr.setParams(params);
current = functionExpr;
}
return current;
}
/**
* This method parse CAST expression.
* This returns only expression field without casting type
* because Tajo doesn't provide CAST expression.
*
* @param ctx
* @return
*/
@Override
public Expr visitCastExpression(HiveQLParser.CastExpressionContext ctx) {
LOG.info("### 100 - expr:" + ctx.getText());
LOG.info("### 110 - primitiveType:" + ctx.primitiveType().getText());
// current = new CastExpr(current, visitData_type(ctx.cast_target(i).data_type()));
Expr expr = visitExpression(ctx.expression());
LOG.info("### 200 - expr:" + expr.toJson());
return visitExpression(ctx.expression());
}
@Override
public Expr visitCaseExpression(HiveQLParser.CaseExpressionContext ctx) {
CaseWhenPredicate caseWhen = new CaseWhenPredicate();
Expr condition = null, result = null;
for (int i = 1; i < ctx.getChildCount(); i++) {
if (ctx.getChild(i) instanceof TerminalNodeImpl) {
if (((TerminalNodeImpl) ctx.getChild(i)).getSymbol().getType() == HiveQLLexer.KW_WHEN) {
condition = null;
result = null;
if (ctx.getChild(i + 1) instanceof HiveQLParser.ExpressionContext) {
condition = visitExpression((HiveQLParser.ExpressionContext) ctx.getChild(i + 1));
}
if (ctx.getChild(i + 3) instanceof HiveQLParser.ExpressionContext) {
result = visitExpression((HiveQLParser.ExpressionContext) ctx.getChild(i + 3));
}
if (condition != null && result != null) {
caseWhen.addWhen(condition, result);
}
} else if (((TerminalNodeImpl) ctx.getChild(i)).getSymbol().getType() == HiveQLLexer.KW_ELSE) {
result = visitExpression((HiveQLParser.ExpressionContext) ctx.getChild(i + 1));
caseWhen.setElseResult(result);
}
}
}
return caseWhen;
}
@Override
public Expr visitWhenExpression(HiveQLParser.WhenExpressionContext ctx) {
CaseWhenPredicate caseWhen = new CaseWhenPredicate();
Expr condition = null, result = null;
for (int i = 1; i < ctx.getChildCount(); i++) {
if (ctx.getChild(i) instanceof TerminalNodeImpl) {
if (((TerminalNodeImpl) ctx.getChild(i)).getSymbol().getType() == HiveQLLexer.KW_WHEN) {
condition = null;
result = null;
if (ctx.getChild(i + 1) instanceof HiveQLParser.ExpressionContext) {
condition = visitExpression((HiveQLParser.ExpressionContext) ctx.getChild(i + 1));
}
if (ctx.getChild(i + 3) instanceof HiveQLParser.ExpressionContext) {
result = visitExpression((HiveQLParser.ExpressionContext) ctx.getChild(i + 3));
}
if (condition != null && result != null) {
caseWhen.addWhen(condition, result);
}
} else if (((TerminalNodeImpl) ctx.getChild(i)).getSymbol().getType() == HiveQLLexer.KW_ELSE) {
result = visitExpression((HiveQLParser.ExpressionContext) ctx.getChild(i + 1));
caseWhen.setElseResult(result);
}
}
}
return caseWhen;
}
@Override
public Aggregation visitGroupByClause(HiveQLParser.GroupByClauseContext ctx) {
Aggregation clause = new Aggregation();
if (ctx.groupByExpression().size() > 0) {
int elementSize = ctx.groupByExpression().size();
ArrayList<Aggregation.GroupElement> groups = new ArrayList<Aggregation.GroupElement>(elementSize + 1);
ArrayList<Expr> ordinaryExprs = new ArrayList<Expr>();
int groupSize = 1;
groups.add(null);
for (int i = 0; i < ctx.groupByExpression().size(); i++) {
Expr expr = visitGroupByExpression(ctx.groupByExpression(i));
if (expr instanceof FunctionExpr) {
FunctionExpr function = (FunctionExpr) expr;
if (function.getSignature().equalsIgnoreCase("ROLLUP")) {
groupSize++;
groups.add(new Aggregation.GroupElement(Aggregation.GroupType.Rollup,
function.getParams()));
} else if (function.getSignature().equalsIgnoreCase("CUBE")) {
groupSize++;
groups.add(new Aggregation.GroupElement(Aggregation.GroupType.Cube, function.getParams()));
} else {
Collections.addAll(ordinaryExprs, function);
}
} else {
Collections.addAll(ordinaryExprs, (ColumnReferenceExpr)expr);
}
}
if (ordinaryExprs != null) {
groups.set(0, new Aggregation.GroupElement(Aggregation.GroupType.OrdinaryGroup, ordinaryExprs.toArray(new Expr[ordinaryExprs.size()])));
clause.setGroups(groups.subList(0, groupSize).toArray(new Aggregation.GroupElement[groupSize]));
} else if (groupSize > 1) {
clause.setGroups(groups.subList(1, groupSize).toArray(new Aggregation.GroupElement[groupSize - 1]));
}
}
//TODO: grouping set expression
return clause;
}
@Override
public Sort visitOrderByClause(HiveQLParser.OrderByClauseContext ctx) {
Sort clause = null;
Sort.SortSpec[] specs = null;
if (ctx.columnRefOrder().size() > 0) {
specs = new Sort.SortSpec[ctx.columnRefOrder().size()];
for (int i = 0; i < ctx.columnRefOrder().size(); i++) {
ColumnReferenceExpr column = (ColumnReferenceExpr) visitExpression(ctx.columnRefOrder().get(i).expression());
specs[i] = new Sort.SortSpec(column);
if (ctx.columnRefOrder(i).KW_DESC() != null) {
specs[i].setDescending();
}
}
clause = new Sort(specs);
}
return clause;
}
@Override
public Expr visitHavingClause(HiveQLParser.HavingClauseContext ctx) {
return visitHavingCondition(ctx.havingCondition());
}
@Override
public Expr visitClusterByClause(HiveQLParser.ClusterByClauseContext ctx) {
// TODO: It needs to consider how to support.
return null;
}
@Override
public Expr visitDistributeByClause(HiveQLParser.DistributeByClauseContext ctx) {
// TODO: It needs to consider how to support.
return null;
}
@Override
public Sort visitSortByClause(HiveQLParser.SortByClauseContext ctx) {
Sort clause = null;
Sort.SortSpec[] specs = null;
if (ctx.columnRefOrder().size() > 0) {
specs = new Sort.SortSpec[ctx.columnRefOrder().size()];
for (int i = 0; i < ctx.columnRefOrder().size(); i++) {
ColumnReferenceExpr column = (ColumnReferenceExpr) visitColumnRefOrder(ctx.columnRefOrder(i));
specs[i] = new Sort.SortSpec(column);
if (ctx.columnRefOrder(i).KW_DESC() != null) {
specs[i].setDescending();
}
}
clause = new Sort(specs);
}
return clause;
}
@Override
public Limit visitLimitClause(HiveQLParser.LimitClauseContext ctx) {
LiteralValue expr = new LiteralValue(ctx.Number().getText(), LiteralValue.LiteralType.Unsigned_Integer);
Limit limit = new Limit(expr);
return limit;
}
@Override
public Expr visitWindow_clause(HiveQLParser.Window_clauseContext ctx) {
// TODO: It needs to consider how to support.
return null;
}
@Override
public Insert visitInsertClause(HiveQLParser.InsertClauseContext ctx) {
Insert insert = new Insert();
if (ctx.KW_OVERWRITE() != null)
insert.setOverwrite();
if (ctx.tableOrPartition() != null) {
HiveQLParser.TableOrPartitionContext partitionContext = ctx.tableOrPartition();
if (partitionContext.tableName() != null) {
insert.setTableName(ctx.tableOrPartition().tableName().getText());
}
}
if (ctx.destination() != null) {
HiveQLParser.DestinationContext destination = ctx.destination();
if (destination.KW_DIRECTORY() != null) {
String location = destination.StringLiteral().getText();
location = location.replaceAll("\\'", "");
insert.setLocation(location);
} else if (destination.KW_TABLE() != null) {
if (destination.tableOrPartition() != null) {
HiveQLParser.TableOrPartitionContext partitionContext = destination.tableOrPartition();
if (partitionContext.tableName() != null) {
insert.setTableName(partitionContext.tableName().getText());
}
}
if (destination.tableFileFormat() != null) {
if (destination.tableFileFormat().KW_RCFILE() != null) {
insert.setStorageType("rcfile");
} else if (destination.tableFileFormat().KW_TEXTFILE() != null) {
insert.setStorageType("csv");
}
}
}
}
return insert;
}
@Override
public Expr visitCreateTableStatement(HiveQLParser.CreateTableStatementContext ctx) {
CreateTable createTable = null;
Map<String, String> params = new HashMap<String, String>();
if (ctx.name != null) {
createTable = new CreateTable(ctx.name.getText());
if (ctx.KW_EXTERNAL() != null) {
createTable.setExternal();
}
if (ctx.tableFileFormat() != null) {
if (ctx.tableFileFormat().KW_RCFILE() != null) {
createTable.setStorageType("rcfile");
} else if (ctx.tableFileFormat().KW_TEXTFILE() != null) {
createTable.setStorageType("csv");
}
}
if (ctx.tableRowFormat() != null) {
if (ctx.tableRowFormat().rowFormatDelimited() != null) {
String delimiter = ctx.tableRowFormat().rowFormatDelimited().tableRowFormatFieldIdentifier().getChild(3)
.getText().replaceAll("'", "");
params.put("csvfile.delimiter", SQLAnalyzer.escapeDelimiter(delimiter));
}
}
if (ctx.tableLocation() != null) {
String location = ctx.tableLocation().StringLiteral().getText();
location = location.replaceAll("'", "");
createTable.setLocation(location);
}
if (ctx.columnNameTypeList() != null) {
List<HiveQLParser.ColumnNameTypeContext> list = ctx.columnNameTypeList().columnNameType();
CreateTable.ColumnDefinition[] columns = new CreateTable.ColumnDefinition[list.size()];
for (int i = 0; i < list.size(); i++) {
HiveQLParser.ColumnNameTypeContext eachColumn = list.get(i);
String type = null;
if (eachColumn.colType().type() != null) {
if (eachColumn.colType().type().primitiveType() != null) {
HiveQLParser.PrimitiveTypeContext primitiveType = eachColumn.colType().type().primitiveType();
if (primitiveType.KW_STRING() != null) {
type = TajoDataTypes.Type.TEXT.name();
} else if (primitiveType.KW_TINYINT() != null) {
type = TajoDataTypes.Type.INT1.name();
} else if (primitiveType.KW_SMALLINT() != null) {
type = TajoDataTypes.Type.INT2.name();
} else if (primitiveType.KW_INT() != null) {
type = TajoDataTypes.Type.INT4.name();
} else if (primitiveType.KW_BIGINT() != null) {
type = TajoDataTypes.Type.INT8.name();
} else if (primitiveType.KW_FLOAT() != null) {
type = TajoDataTypes.Type.FLOAT4.name();
} else if (primitiveType.KW_DOUBLE() != null) {
type = TajoDataTypes.Type.FLOAT8.name();
} else if (primitiveType.KW_DECIMAL() != null) {
type = TajoDataTypes.Type.DECIMAL.name();
} else if (primitiveType.KW_BOOLEAN() != null) {
type = TajoDataTypes.Type.BOOLEAN.name();
} else if (primitiveType.KW_DATE() != null) {
type = TajoDataTypes.Type.DATE.name();
} else if (primitiveType.KW_DATETIME() != null) {
//TODO
} else if (primitiveType.KW_TIMESTAMP() != null) {
type = TajoDataTypes.Type.TIMESTAMP.name();
}
columns[i] = new CreateTable.ColumnDefinition(eachColumn.colName.Identifier().getText(), type);
}
}
}
if (columns != null) {
createTable.setTableElements(columns);
}
if (!params.isEmpty()) {
createTable.setParams(params);
}
}
}
return createTable;
}
@Override
public Expr visitDropTableStatement(HiveQLParser.DropTableStatementContext ctx) {
DropTable dropTable = new DropTable(ctx.tableName().getText(), false);
return dropTable;
}
/**
* This class provides and implementation for a case insensitive token checker
* for the lexical analysis part of antlr. By converting the token stream into
* upper case at the time when lexical rules are checked, this class ensures that the
* lexical rules need to just match the token with upper case letters as opposed to
* combination of upper case and lower case characteres. This is purely used for matching lexical
* rules. The actual token text is stored in the same way as the user input without
* actually converting it into an upper case. The token values are generated by the consume()
* function of the super class ANTLRStringStream. The LA() function is the lookahead funtion
* and is purely used for matching lexical rules. This also means that the grammar will only
* accept capitalized tokens in case it is run from other tools like antlrworks which
* do not have the ANTLRNoCaseStringStream implementation.
*/
public class ANTLRNoCaseStringStream extends ANTLRInputStream {
public ANTLRNoCaseStringStream(String input) {
super(input);
}
@Override
public int LA(int i) {
int returnChar = super.LA(i);
if (returnChar == CharStream.EOF) {
return returnChar;
} else if (returnChar == 0) {
return returnChar;
}
return Character.toUpperCase((char) returnChar);
}
}
} | TAJO-403: HiveQLAnalyzer should supports standard function in the GROUP BY Clause. (Removing unnecessary codes)
| tajo-core/tajo-core-backend/src/main/java/org/apache/tajo/engine/parser/HiveQLAnalyzer.java | TAJO-403: HiveQLAnalyzer should supports standard function in the GROUP BY Clause. (Removing unnecessary codes) |
|
Java | apache-2.0 | 578bab17754f8c811f77eb569438aba1f855cd8d | 0 | renchaorevee/gerrit,evanchueng/gerrit,supriyantomaftuh/gerrit,bpollack/gerrit,MerritCR/merrit,MerritCR/merrit,TonyChai24/test,WANdisco/gerrit,netroby/gerrit,jackminicloud/test,basilgor/gerrit,dwhipstock/gerrit,netroby/gerrit,catrope/gerrit,teamblueridge/gerrit,keerath/gerrit_newssh,zommarin/gerrit,Seinlin/gerrit,atdt/gerrit,austinchic/Gerrit,supriyantomaftuh/gerrit,anminhsu/gerrit,pkdevbox/gerrit,teamblueridge/gerrit,makholm/gerrit-ceremony,catrope/gerrit,gracefullife/gerrit,gerrit-review/gerrit,atdt/gerrit,Overruler/gerrit,midnightradio/gerrit,bootstraponline-archive/gerrit-mirror,supriyantomaftuh/gerrit,thesamet/gerrit,gracefullife/gerrit,cjh1/gerrit,thesamet/gerrit,duboisf/gerrit,gerrit-review/gerrit,m1kah/gerrit-contributions,Seinlin/gerrit,hdost/gerrit,CandyShop/gerrit,WANdisco/gerrit,WANdisco/gerrit,gcoders/gerrit,WANdisco/gerrit,ckamm/gerrit,Team-OctOS/host_gerrit,dwhipstock/gerrit,Overruler/gerrit,netroby/gerrit,anminhsu/gerrit,bootstraponline-archive/gerrit-mirror,bpollack/gerrit,renchaorevee/gerrit,austinchic/Gerrit,bpollack/gerrit,keerath/gerrit_newssh,Team-OctOS/host_gerrit,skurfuerst/gerrit,pkdevbox/gerrit,skurfuerst/gerrit,Team-OctOS/host_gerrit,Saulis/gerrit,GerritCodeReview/gerrit,thinkernel/gerrit,qtproject/qtqa-gerrit,renchaorevee/gerrit,GerritCodeReview/gerrit,TonyChai24/test,quyixia/gerrit,ashang/aaron-gerrit,gcoders/gerrit,m1kah/gerrit-contributions,GerritCodeReview/gerrit,TonyChai24/test,atdt/gerrit,sudosurootdev/gerrit,rtyley/mini-git-server,teamblueridge/gerrit,GerritCodeReview/gerrit,austinchic/Gerrit,anminhsu/gerrit,bpollack/gerrit,Distrotech/gerrit,gerrit-review/gerrit,m1kah/gerrit-contributions,pkdevbox/gerrit,MerritCR/merrit,quyixia/gerrit,Team-OctOS/host_gerrit,sudosurootdev/gerrit,Distrotech/gerrit,netroby/gerrit,ashang/aaron-gerrit,Overruler/gerrit,qtproject/qtqa-gerrit,bpollack/gerrit,CandyShop/gerrit,Distrotech/gerrit,sudosurootdev/gerrit,Saulis/gerrit,joshuawilson/merrit,thinkernel/gerrit,gcoders/gerrit,Distrotech/gerrit,austinchic/Gerrit,quyixia/gerrit,Saulis/gerrit,zommarin/gerrit,skurfuerst/gerrit,GerritCodeReview/gerrit,MerritCR/merrit,bootstraponline-archive/gerrit-mirror,Seinlin/gerrit,joshuawilson/merrit,thesamet/gerrit,jackminicloud/test,basilgor/gerrit,gracefullife/gerrit,hdost/gerrit,qtproject/qtqa-gerrit,Distrotech/gerrit,makholm/gerrit-ceremony,zommarin/gerrit,thesamet/gerrit,hdost/gerrit,ckamm/gerrit,dwhipstock/gerrit,skurfuerst/gerrit,hdost/gerrit,WANdisco/gerrit,MerritCR/merrit,basilgor/gerrit,qtproject/qtqa-gerrit,jeblair/gerrit,jackminicloud/test,CandyShop/gerrit,sudosurootdev/gerrit,netroby/gerrit,gerrit-review/gerrit,MerritCR/merrit,MerritCR/merrit,rtyley/mini-git-server,gcoders/gerrit,gerrit-review/gerrit,Distrotech/gerrit,Distrotech/gerrit,supriyantomaftuh/gerrit,evanchueng/gerrit,netroby/gerrit,anminhsu/gerrit,catrope/gerrit,anminhsu/gerrit,renchaorevee/gerrit,Overruler/gerrit,m1kah/gerrit-contributions,thesamet/gerrit,supriyantomaftuh/gerrit,WANdisco/gerrit,ckamm/gerrit,Seinlin/gerrit,thesamet/gerrit,midnightradio/gerrit,sudosurootdev/gerrit,renchaorevee/gerrit,keerath/gerrit_newssh,TonyChai24/test,Saulis/gerrit,dwhipstock/gerrit,pkdevbox/gerrit,catrope/gerrit,joshuawilson/merrit,joshuawilson/merrit,WANdisco/gerrit,ashang/aaron-gerrit,hdost/gerrit,atdt/gerrit,evanchueng/gerrit,Seinlin/gerrit,ckamm/gerrit,dwhipstock/gerrit,ckamm/gerrit,quyixia/gerrit,TonyChai24/test,thinkernel/gerrit,jackminicloud/test,hdost/gerrit,TonyChai24/test,bpollack/gerrit,1yvT0s/gerrit,cjh1/gerrit,zommarin/gerrit,thinkernel/gerrit,qtproject/qtqa-gerrit,Seinlin/gerrit,midnightradio/gerrit,cjh1/gerrit,qtproject/qtqa-gerrit,joshuawilson/merrit,Overruler/gerrit,1yvT0s/gerrit,bootstraponline-archive/gerrit-mirror,supriyantomaftuh/gerrit,teamblueridge/gerrit,jackminicloud/test,GerritCodeReview/gerrit,CandyShop/gerrit,gcoders/gerrit,ashang/aaron-gerrit,joshuawilson/merrit,GerritCodeReview/gerrit,dwhipstock/gerrit,jeblair/gerrit,duboisf/gerrit,dwhipstock/gerrit,bootstraponline-archive/gerrit-mirror,jeblair/gerrit,midnightradio/gerrit,pkdevbox/gerrit,makholm/gerrit-ceremony,hdost/gerrit,1yvT0s/gerrit,anminhsu/gerrit,Team-OctOS/host_gerrit,pkdevbox/gerrit,quyixia/gerrit,thinkernel/gerrit,jackminicloud/test,joshuawilson/merrit,qtproject/qtqa-gerrit,Team-OctOS/host_gerrit,jackminicloud/test,thinkernel/gerrit,TonyChai24/test,quyixia/gerrit,renchaorevee/gerrit,Team-OctOS/host_gerrit,thinkernel/gerrit,CandyShop/gerrit,jeblair/gerrit,gerrit-review/gerrit,bootstraponline-archive/gerrit-mirror,anminhsu/gerrit,gracefullife/gerrit,basilgor/gerrit,thesamet/gerrit,duboisf/gerrit,netroby/gerrit,GerritCodeReview/gerrit,pkdevbox/gerrit,Seinlin/gerrit,ashang/aaron-gerrit,zommarin/gerrit,evanchueng/gerrit,Overruler/gerrit,Saulis/gerrit,atdt/gerrit,cjh1/gerrit,supriyantomaftuh/gerrit,Saulis/gerrit,midnightradio/gerrit,1yvT0s/gerrit,evanchueng/gerrit,gerrit-review/gerrit,1yvT0s/gerrit,quyixia/gerrit,gcoders/gerrit,renchaorevee/gerrit,gcoders/gerrit,makholm/gerrit-ceremony,basilgor/gerrit,joshuawilson/merrit,midnightradio/gerrit,MerritCR/merrit,keerath/gerrit_newssh,gracefullife/gerrit,keerath/gerrit_newssh,teamblueridge/gerrit,duboisf/gerrit | // Copyright (C) 2008 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.client.changes;
import com.google.gerrit.client.ErrorDialog;
import com.google.gerrit.client.Gerrit;
import com.google.gerrit.client.patches.PatchUtil;
import com.google.gerrit.client.rpc.GerritCallback;
import com.google.gerrit.client.ui.AccountDashboardLink;
import com.google.gerrit.client.ui.AddMemberBox;
import com.google.gerrit.common.data.AccountInfoCache;
import com.google.gerrit.common.data.ApprovalDetail;
import com.google.gerrit.common.data.ApprovalType;
import com.google.gerrit.common.data.ChangeDetail;
import com.google.gerrit.common.data.ReviewerResult;
import com.google.gerrit.reviewdb.Account;
import com.google.gerrit.reviewdb.ApprovalCategory;
import com.google.gerrit.reviewdb.ApprovalCategoryValue;
import com.google.gerrit.reviewdb.Change;
import com.google.gerrit.reviewdb.PatchSetApproval;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;
import com.google.gwtexpui.safehtml.client.SafeHtmlBuilder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** Displays a table of {@link ApprovalDetail} objects for a change record. */
public class ApprovalTable extends Composite {
private final List<ApprovalType> types;
private final Grid table;
private final Widget missing;
private final Panel addReviewer;
private final AddMemberBox addMemberBox;
private Change.Id changeId;
private boolean changeIsOpen;
private AccountInfoCache accountCache = AccountInfoCache.empty();
public ApprovalTable() {
types = Gerrit.getConfig().getApprovalTypes().getApprovalTypes();
table = new Grid(1, 4 + types.size());
table.addStyleName(Gerrit.RESOURCES.css().infoTable());
displayHeader();
missing = new Widget() {
{
setElement(DOM.createElement("ul"));
}
};
missing.setStyleName(Gerrit.RESOURCES.css().missingApprovalList());
addReviewer = new FlowPanel();
addReviewer.setStyleName(Gerrit.RESOURCES.css().addReviewer());
addMemberBox = new AddMemberBox();
addMemberBox.setAddButtonText(Util.C.approvalTableAddReviewer());
addMemberBox.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
doAddReviewer();
}
});
addReviewer.add(addMemberBox);
addReviewer.setVisible(false);
final FlowPanel fp = new FlowPanel();
fp.add(table);
fp.add(missing);
fp.add(addReviewer);
initWidget(fp);
setStyleName(Gerrit.RESOURCES.css().approvalTable());
}
private void displayHeader() {
int col = 0;
header(col++, Util.C.approvalTableReviewer());
header(col++, "");
for (final ApprovalType t : types) {
header(col++, t.getCategory().getName());
}
header(col++, Util.C.removeReviewer());
applyEdgeStyles(0);
}
private void header(final int col, final String title) {
table.setText(0, col, title);
table.getCellFormatter().addStyleName(0, col, Gerrit.RESOURCES.css().header());
}
private void applyEdgeStyles(final int row) {
final CellFormatter fmt = table.getCellFormatter();
fmt.addStyleName(row, 1, Gerrit.RESOURCES.css().approvalrole());
fmt.addStyleName(row, 1 + types.size(), Gerrit.RESOURCES.css().rightmost());
fmt.addStyleName(row, 2 + types.size(), Gerrit.RESOURCES.css().rightmost());
fmt.addStyleName(row, 3 + types.size(), Gerrit.RESOURCES.css().approvalhint());
}
private void applyScoreStyles(final int row) {
final CellFormatter fmt = table.getCellFormatter();
for (int col = 0; col < types.size(); col++) {
fmt.addStyleName(row, 2 + col, Gerrit.RESOURCES.css().approvalscore());
}
}
public void setAccountInfoCache(final AccountInfoCache aic) {
assert aic != null;
accountCache = aic;
}
private AccountDashboardLink link(final Account.Id id) {
return AccountDashboardLink.link(accountCache, id);
}
public void display(final Change change, final Set<ApprovalCategory.Id> need,
final List<ApprovalDetail> rows) {
changeId = change.getId();
final int oldcnt = table.getRowCount();
table.resizeRows(1 + rows.size());
if (oldcnt < 1 + rows.size()) {
for (int row = oldcnt; row < 1 + rows.size(); row++) {
applyEdgeStyles(row);
applyScoreStyles(row);
}
}
if (rows.isEmpty()) {
table.setVisible(false);
} else {
table.setVisible(true);
for (int i = 0; i < rows.size(); i++) {
displayRow(i + 1, rows.get(i), change);
}
}
final Element missingList = missing.getElement();
while (DOM.getChildCount(missingList) > 0) {
DOM.removeChild(missingList, DOM.getChild(missingList, 0));
}
missing.setVisible(false);
if (need != null) {
for (final ApprovalType at : types) {
if (need.contains(at.getCategory().getId())) {
final Element li = DOM.createElement("li");
li.setClassName(Gerrit.RESOURCES.css().missingApproval());
DOM.setInnerText(li, Util.M.needApproval(at.getCategory().getName(),
at.getMax().formatValue(), at.getMax().getName()));
DOM.appendChild(missingList, li);
missing.setVisible(true);
}
}
}
changeIsOpen = change.getStatus().isOpen();
addReviewer.setVisible(Gerrit.isSignedIn() && changeIsOpen);
}
private void doAddReviewer() {
final String nameEmail = addMemberBox.getText();
if (nameEmail.length() == 0) {
return;
}
addMemberBox.setEnabled(false);
final List<String> reviewers = new ArrayList<String>();
reviewers.add(nameEmail);
PatchUtil.DETAIL_SVC.addReviewers(changeId, reviewers,
new GerritCallback<ReviewerResult>() {
public void onSuccess(final ReviewerResult result) {
addMemberBox.setEnabled(true);
addMemberBox.setText("");
if (!result.getErrors().isEmpty()) {
final SafeHtmlBuilder r = new SafeHtmlBuilder();
for (final ReviewerResult.Error e : result.getErrors()) {
switch (e.getType()) {
case ACCOUNT_NOT_FOUND:
r.append(Util.M.accountNotFound(e.getName()));
break;
case CHANGE_NOT_VISIBLE:
r.append(Util.M.changeNotVisibleTo(e.getName()));
break;
default:
r.append(e.getName());
r.append(" - ");
r.append(e.getType());
r.br();
break;
}
}
new ErrorDialog(r).center();
}
final ChangeDetail r = result.getChange();
if (r != null) {
setAccountInfoCache(r.getAccounts());
display(r.getChange(), r.getMissingApprovals(), r.getApprovals());
}
}
@Override
public void onFailure(final Throwable caught) {
addMemberBox.setEnabled(true);
super.onFailure(caught);
}
});
}
private void displayRow(final int row, final ApprovalDetail ad,
final Change change) {
final CellFormatter fmt = table.getCellFormatter();
final Map<ApprovalCategory.Id, PatchSetApproval> am = ad.getApprovalMap();
final StringBuilder hint = new StringBuilder();
int col = 0;
table.setWidget(row, col++, link(ad.getAccount()));
table.clearCell(row, col++); // TODO populate the account role
for (final ApprovalType type : types) {
final PatchSetApproval ca = am.get(type.getCategory().getId());
if (ca == null || ca.getValue() == 0) {
table.clearCell(row, col);
col++;
continue;
}
final ApprovalCategoryValue acv = type.getValue(ca);
if (acv != null) {
if (hint.length() > 0) {
hint.append("; ");
}
hint.append(acv.getName());
}
if (type.isMaxNegative(ca)) {
table.setWidget(row, col, new Image(Gerrit.RESOURCES.redNot()));
} else if (type.isMaxPositive(ca)) {
table.setWidget(row, col, new Image(Gerrit.RESOURCES.greenCheck()));
} else {
String vstr = String.valueOf(ca.getValue());
if (ca.getValue() > 0) {
vstr = "+" + vstr;
fmt.removeStyleName(row, col, Gerrit.RESOURCES.css().negscore());
fmt.addStyleName(row, col, Gerrit.RESOURCES.css().posscore());
} else {
fmt.addStyleName(row, col, Gerrit.RESOURCES.css().negscore());
fmt.removeStyleName(row, col, Gerrit.RESOURCES.css().posscore());
}
table.setText(row, col, vstr);
}
col++;
}
//
// Remove button
//
if (change.getStatus().isOpen() && Gerrit.isSignedIn()) {
Button removeButton = new Button("X");
removeButton.setStyleName(Gerrit.RESOURCES.css().removeReviewer());
removeButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
PatchUtil.DETAIL_SVC.removeReviewer(changeId, ad.getAccount(),
new GerritCallback<ReviewerResult>() {
@Override
public void onSuccess(ReviewerResult result) {
if (result.getErrors().isEmpty()) {
final ChangeDetail r = result.getChange();
display(r.getChange(), r.getMissingApprovals(), r.getApprovals());
} else {
new ErrorDialog(result.getErrors().get(0).toString()).center();
}
}
});
}
});
table.setWidget(row, col++, removeButton);
}
table.setText(row, col++, hint.toString());
}
}
| gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/ApprovalTable.java | // Copyright (C) 2008 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.client.changes;
import com.google.gerrit.client.ErrorDialog;
import com.google.gerrit.client.Gerrit;
import com.google.gerrit.client.patches.PatchUtil;
import com.google.gerrit.client.rpc.GerritCallback;
import com.google.gerrit.client.ui.AccountDashboardLink;
import com.google.gerrit.client.ui.AddMemberBox;
import com.google.gerrit.common.data.AccountInfoCache;
import com.google.gerrit.common.data.ApprovalDetail;
import com.google.gerrit.common.data.ApprovalType;
import com.google.gerrit.common.data.ChangeDetail;
import com.google.gerrit.common.data.ReviewerResult;
import com.google.gerrit.reviewdb.Account;
import com.google.gerrit.reviewdb.ApprovalCategory;
import com.google.gerrit.reviewdb.ApprovalCategoryValue;
import com.google.gerrit.reviewdb.Change;
import com.google.gerrit.reviewdb.PatchSetApproval;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;
import com.google.gwtexpui.safehtml.client.SafeHtmlBuilder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** Displays a table of {@link ApprovalDetail} objects for a change record. */
public class ApprovalTable extends Composite {
private final List<ApprovalType> types;
private final Grid table;
private final Widget missing;
private final Panel addReviewer;
private final AddMemberBox addMemberBox;
private Change.Id changeId;
private boolean changeIsOpen;
private AccountInfoCache accountCache = AccountInfoCache.empty();
public ApprovalTable() {
types = Gerrit.getConfig().getApprovalTypes().getApprovalTypes();
table = new Grid(1, 4 + types.size());
table.addStyleName(Gerrit.RESOURCES.css().infoTable());
displayHeader();
missing = new Widget() {
{
setElement(DOM.createElement("ul"));
}
};
missing.setStyleName(Gerrit.RESOURCES.css().missingApprovalList());
addReviewer = new FlowPanel();
addReviewer.setStyleName(Gerrit.RESOURCES.css().addReviewer());
addMemberBox = new AddMemberBox();
addMemberBox.setAddButtonText(Util.C.approvalTableAddReviewer());
addMemberBox.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
doAddReviewer();
}
});
addReviewer.add(addMemberBox);
addReviewer.setVisible(false);
final FlowPanel fp = new FlowPanel();
fp.add(table);
fp.add(missing);
fp.add(addReviewer);
initWidget(fp);
setStyleName(Gerrit.RESOURCES.css().approvalTable());
}
private void displayHeader() {
int col = 0;
header(col++, Util.C.approvalTableReviewer());
header(col++, "");
for (final ApprovalType t : types) {
header(col++, t.getCategory().getName());
}
header(col++, Util.C.removeReviewer());
applyEdgeStyles(0);
}
private void header(final int col, final String title) {
table.setText(0, col, title);
table.getCellFormatter().addStyleName(0, col, Gerrit.RESOURCES.css().header());
}
private void applyEdgeStyles(final int row) {
final CellFormatter fmt = table.getCellFormatter();
fmt.addStyleName(row, 1, Gerrit.RESOURCES.css().approvalrole());
fmt.addStyleName(row, 1 + types.size(), Gerrit.RESOURCES.css().rightmost());
fmt.addStyleName(row, 2 + types.size(), Gerrit.RESOURCES.css().rightmost());
fmt.addStyleName(row, 3 + types.size(), Gerrit.RESOURCES.css().approvalhint());
}
private void applyScoreStyles(final int row) {
final CellFormatter fmt = table.getCellFormatter();
for (int col = 0; col < types.size(); col++) {
fmt.addStyleName(row, 2 + col, Gerrit.RESOURCES.css().approvalscore());
}
}
public void setAccountInfoCache(final AccountInfoCache aic) {
assert aic != null;
accountCache = aic;
}
private AccountDashboardLink link(final Account.Id id) {
return AccountDashboardLink.link(accountCache, id);
}
public void display(final Change change, final Set<ApprovalCategory.Id> need,
final List<ApprovalDetail> rows) {
changeId = change.getId();
final int oldcnt = table.getRowCount();
table.resizeRows(1 + rows.size());
if (oldcnt < 1 + rows.size()) {
for (int row = oldcnt; row < 1 + rows.size(); row++) {
applyEdgeStyles(row);
applyScoreStyles(row);
}
}
if (rows.isEmpty()) {
table.setVisible(false);
} else {
table.setVisible(true);
for (int i = 0; i < rows.size(); i++) {
displayRow(i + 1, rows.get(i));
}
}
final Element missingList = missing.getElement();
while (DOM.getChildCount(missingList) > 0) {
DOM.removeChild(missingList, DOM.getChild(missingList, 0));
}
missing.setVisible(false);
if (need != null) {
for (final ApprovalType at : types) {
if (need.contains(at.getCategory().getId())) {
final Element li = DOM.createElement("li");
li.setClassName(Gerrit.RESOURCES.css().missingApproval());
DOM.setInnerText(li, Util.M.needApproval(at.getCategory().getName(),
at.getMax().formatValue(), at.getMax().getName()));
DOM.appendChild(missingList, li);
missing.setVisible(true);
}
}
}
changeIsOpen = change.getStatus().isOpen();
addReviewer.setVisible(Gerrit.isSignedIn() && changeIsOpen);
}
private void doAddReviewer() {
final String nameEmail = addMemberBox.getText();
if (nameEmail.length() == 0) {
return;
}
addMemberBox.setEnabled(false);
final List<String> reviewers = new ArrayList<String>();
reviewers.add(nameEmail);
PatchUtil.DETAIL_SVC.addReviewers(changeId, reviewers,
new GerritCallback<ReviewerResult>() {
public void onSuccess(final ReviewerResult result) {
addMemberBox.setEnabled(true);
addMemberBox.setText("");
if (!result.getErrors().isEmpty()) {
final SafeHtmlBuilder r = new SafeHtmlBuilder();
for (final ReviewerResult.Error e : result.getErrors()) {
switch (e.getType()) {
case ACCOUNT_NOT_FOUND:
r.append(Util.M.accountNotFound(e.getName()));
break;
case CHANGE_NOT_VISIBLE:
r.append(Util.M.changeNotVisibleTo(e.getName()));
break;
default:
r.append(e.getName());
r.append(" - ");
r.append(e.getType());
r.br();
break;
}
}
new ErrorDialog(r).center();
}
final ChangeDetail r = result.getChange();
if (r != null) {
setAccountInfoCache(r.getAccounts());
display(r.getChange(), r.getMissingApprovals(), r.getApprovals());
}
}
@Override
public void onFailure(final Throwable caught) {
addMemberBox.setEnabled(true);
super.onFailure(caught);
}
});
}
private void displayRow(final int row, final ApprovalDetail ad) {
final CellFormatter fmt = table.getCellFormatter();
final Map<ApprovalCategory.Id, PatchSetApproval> am = ad.getApprovalMap();
final StringBuilder hint = new StringBuilder();
int col = 0;
table.setWidget(row, col++, link(ad.getAccount()));
table.clearCell(row, col++); // TODO populate the account role
for (final ApprovalType type : types) {
final PatchSetApproval ca = am.get(type.getCategory().getId());
if (ca == null || ca.getValue() == 0) {
table.clearCell(row, col);
col++;
continue;
}
final ApprovalCategoryValue acv = type.getValue(ca);
if (acv != null) {
if (hint.length() > 0) {
hint.append("; ");
}
hint.append(acv.getName());
}
if (type.isMaxNegative(ca)) {
table.setWidget(row, col, new Image(Gerrit.RESOURCES.redNot()));
} else if (type.isMaxPositive(ca)) {
table.setWidget(row, col, new Image(Gerrit.RESOURCES.greenCheck()));
} else {
String vstr = String.valueOf(ca.getValue());
if (ca.getValue() > 0) {
vstr = "+" + vstr;
fmt.removeStyleName(row, col, Gerrit.RESOURCES.css().negscore());
fmt.addStyleName(row, col, Gerrit.RESOURCES.css().posscore());
} else {
fmt.addStyleName(row, col, Gerrit.RESOURCES.css().negscore());
fmt.removeStyleName(row, col, Gerrit.RESOURCES.css().posscore());
}
table.setText(row, col, vstr);
}
col++;
}
//
// Remove button
//
if (Gerrit.isSignedIn()) {
Button removeButton = new Button("X");
removeButton.setStyleName(Gerrit.RESOURCES.css().removeReviewer());
removeButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
PatchUtil.DETAIL_SVC.removeReviewer(changeId, ad.getAccount(),
new GerritCallback<ReviewerResult>() {
@Override
public void onSuccess(ReviewerResult result) {
if (result.getErrors().isEmpty()) {
final ChangeDetail r = result.getChange();
display(r.getChange(), r.getMissingApprovals(), r.getApprovals());
} else {
new ErrorDialog(result.getErrors().get(0).toString()).center();
}
}
});
}
});
table.setWidget(row, col++, removeButton);
}
table.setText(row, col++, hint.toString());
}
}
| Don't show remove reviewer button on closed changes
If the change is closed, we shouldn't be able to delete a reviewer
from the reviewer table. So don't display the button to the user.
Change-Id: I1b4c7e3f2f764a7109fba3bbd93cef9ce4d2622e
Signed-off-by: Shawn O. Pearce <[email protected]>
| gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/ApprovalTable.java | Don't show remove reviewer button on closed changes |
|
Java | apache-2.0 | e74c5a3732b6006ffdc8d9155a73bde36525796c | 0 | gathreya/rice-kc,gathreya/rice-kc,bsmith83/rice-1,jwillia/kc-rice1,smith750/rice,ewestfal/rice-svn2git-test,shahess/rice,ewestfal/rice-svn2git-test,gathreya/rice-kc,ewestfal/rice,jwillia/kc-rice1,sonamuthu/rice-1,jwillia/kc-rice1,rojlarge/rice-kc,cniesen/rice,cniesen/rice,ewestfal/rice,bhutchinson/rice,shahess/rice,sonamuthu/rice-1,rojlarge/rice-kc,bhutchinson/rice,UniversityOfHawaiiORS/rice,geothomasp/kualico-rice-kc,bsmith83/rice-1,bhutchinson/rice,kuali/kc-rice,geothomasp/kualico-rice-kc,shahess/rice,geothomasp/kualico-rice-kc,geothomasp/kualico-rice-kc,gathreya/rice-kc,geothomasp/kualico-rice-kc,rojlarge/rice-kc,jwillia/kc-rice1,ewestfal/rice,shahess/rice,cniesen/rice,jwillia/kc-rice1,kuali/kc-rice,UniversityOfHawaiiORS/rice,UniversityOfHawaiiORS/rice,rojlarge/rice-kc,smith750/rice,bsmith83/rice-1,kuali/kc-rice,kuali/kc-rice,sonamuthu/rice-1,ewestfal/rice,smith750/rice,rojlarge/rice-kc,smith750/rice,bhutchinson/rice,sonamuthu/rice-1,kuali/kc-rice,cniesen/rice,bsmith83/rice-1,cniesen/rice,ewestfal/rice,gathreya/rice-kc,shahess/rice,bhutchinson/rice,smith750/rice,UniversityOfHawaiiORS/rice,ewestfal/rice-svn2git-test,ewestfal/rice-svn2git-test,UniversityOfHawaiiORS/rice | /*
* Copyright 2005-2007 The Kuali Foundation
*
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.kew.postprocessor;
import org.apache.commons.lang.StringUtils;
import org.custommonkey.xmlunit.XMLAssert;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.Test;
import org.kuali.rice.kew.doctype.bo.DocumentType;
import org.kuali.rice.kew.routeheader.DocumentRouteHeaderValue;
import org.kuali.rice.kew.service.KEWServiceLocator;
import org.kuali.rice.kew.service.WorkflowDocument;
import org.kuali.rice.kew.test.KEWTestCase;
import org.kuali.rice.kew.util.KEWConstants;
import org.kuali.rice.test.BaselineTestCase;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
@BaselineTestCase.BaselineMode(BaselineTestCase.Mode.NONE)
public class PostProcessorTest extends KEWTestCase {
private static final String APPLICATION_CONTENT = "<some><application>content</application></some>";
private static final String DOC_TITLE = "The Doc Title";
protected void loadTestData() throws Exception {
loadXmlFile("PostProcessorConfig.xml");
}
/**
* Tests that modifying a document in the post processor works. This test will do a few things:
*
* 1) Change the document content in the post processor
* 2) Send an app specific FYI request to the initiator of the document
* 3) Modify the document title.
*
* This test is meant to expose the bug KULWF-668 where it appears an OptimisticLockException is
* being thrown after returning from the EPIC post processor.
*/
@Test public void testModifyDocumentInPostProcessor() throws Exception {
XMLUnit.setIgnoreWhitespace(true);
WorkflowDocument document = new WorkflowDocument(getPrincipalIdForName("ewestfal"), "testModifyDocumentInPostProcessor");
document.saveDocument("");
assertEquals("application content should be empty initially", "", document.getApplicationContent());
assertNull("Doc title should be empty initially", document.getTitle());
// now route the document, it should through a 2 nodes, then go PROCESSED then FINAL
document.routeDocument("");
assertEquals("Should have transitioned nodes twice", 2, DocumentModifyingPostProcessor.levelChanges);
assertTrue("SHould have called the processed status change", DocumentModifyingPostProcessor.processedChange);
assertTrue("Document should be final.", document.stateIsFinal());
XMLAssert.assertXMLEqual("Application content should have been sucessfully modified.", APPLICATION_CONTENT, document.getApplicationContent());
// check that the title was modified successfully
assertEquals("Wrong doc title", DOC_TITLE, document.getTitle());
// check that the document we routed from the post processor exists
assertNotNull("SHould have routed a document from the post processor.", DocumentModifyingPostProcessor.routedDocumentId);
document = new WorkflowDocument(getPrincipalIdForName("ewestfal"), DocumentModifyingPostProcessor.routedDocumentId);
assertTrue("document should be enroute", document.stateIsEnroute());
assertEquals("Document should have 1 pending request.", 1, KEWServiceLocator.getActionRequestService().findPendingByDoc(document.getRouteHeaderId()).size());
assertTrue("ewestfal should have an approve request.", document.isApprovalRequested());
document.approve("");
assertTrue("Document should be final.", document.stateIsFinal());
}
/**
* Tests that modifying a document in the post processor works. This test will do a few things:
*
* 1) Change the document content in the post processor
* 2) Send an app specific FYI request to the initiator of the document
* 3) Modify the document title.
*
* This test is meant to test that an empty post processor works. The empty post processor should be handled as a DefaultPostProcessor.
*/
@Test public void testEmptyPostProcessor() throws Exception {
WorkflowDocument document = new WorkflowDocument(getPrincipalIdForName("ewestfal"), "testEmptyPostProcessor");
document.saveDocument("");
assertEquals("application content should be empty initially", "", document.getApplicationContent());
assertNull("Doc title should be empty initially", document.getTitle());
assertTrue("Document should be final.", document.stateIsFinal());
DocumentType testEmptyDocType = KEWServiceLocator.getDocumentTypeService().findByName("testEmptyPostProcessor");
assertTrue("Post Processor should be set to 'none'", StringUtils.equals("none", testEmptyDocType.getPostProcessorName()));
assertTrue("Post Processor should be of type DefaultPostProcessor", testEmptyDocType.getPostProcessor() instanceof org.kuali.rice.kew.postprocessor.DefaultPostProcessor);
}
private static boolean shouldReturnDocumentIdsToLock = false;
private static Long documentAId = null;
private static Long documentBId = null;
private static UpdateDocumentThread updateDocumentThread = null;
protected String getPrincipalIdForName(String principalName) {
return KEWServiceLocator.getIdentityHelperService()
.getIdForPrincipalName(principalName);
}
/**
* Tests the locking of additional documents from the Post Processor.
*
* @author Kuali Rice Team ([email protected])
*/
@Test public void testGetDocumentIdsToLock() throws Exception {
/**
* Let's recreate the original optimistic lock scenario that caused this issue to crop up, essentially:
*
* 1) Thread one locks and processes document A in the workflow engine
* 2) Thread one loads document B
* 3) Thread two locks and processes document B from document A's post processor, doing an update which increments the version number of document B
* 4) Thread A attempts to update document B and gets an optimistic lock exception
*/
WorkflowDocument documentB = new WorkflowDocument(getPrincipalIdForName("ewestfal"), "TestDocumentType");
documentB.saveDocument("");
documentBId = documentB.getRouteHeaderId();
updateDocumentThread = new UpdateDocumentThread(documentBId);
// this is the document with the post processor
WorkflowDocument documentA = new WorkflowDocument(getPrincipalIdForName("ewestfal"), "testGetDocumentIdsToLock");
documentA.adHocRouteDocumentToPrincipal(KEWConstants.ACTION_REQUEST_APPROVE_REQ, "", getPrincipalIdForName("rkirkend"), "", true);
try {
documentA.routeDocument(""); // this should trigger our post processor and our optimistic lock exception
fail("An exception should have been thrown as the result of an optimistic lock!");
} catch (Exception e) {
e.printStackTrace();
}
/**
* Now let's try the same thing again, this time returning document B's id as a document to lock, the error should not happen this time
*/
shouldReturnDocumentIdsToLock = true;
documentB = new WorkflowDocument(getPrincipalIdForName("ewestfal"), "TestDocumentType");
documentB.saveDocument("");
documentBId = documentB.getRouteHeaderId();
updateDocumentThread = new UpdateDocumentThread(documentBId);
// this is the document with the post processor
documentA = new WorkflowDocument(getPrincipalIdForName("ewestfal"), "testGetDocumentIdsToLock");
documentA.adHocRouteDocumentToPrincipal(KEWConstants.ACTION_REQUEST_APPROVE_REQ, "", getPrincipalIdForName("rkirkend"), "", true);
documentA.routeDocument(""); // this should trigger our post processor and our optimistic lock exception
documentA = new WorkflowDocument(getPrincipalIdForName("rkirkend"), documentA.getRouteHeaderId());
assertTrue("rkirkend should have approve request", documentA.isApprovalRequested());
}
public static class DocumentModifyingPostProcessor extends DefaultPostProcessor {
public static boolean processedChange = false;
public static int levelChanges = 0;
public static Long routedDocumentId;
protected String getPrincipalIdForName(String principalName) {
return KEWServiceLocator.getIdentityHelperService()
.getIdForPrincipalName(principalName);
}
public ProcessDocReport doRouteStatusChange(DocumentRouteStatusChange statusChangeEvent) throws Exception {
if (KEWConstants.ROUTE_HEADER_PROCESSED_CD.equals(statusChangeEvent.getNewRouteStatus())) {
WorkflowDocument document = new WorkflowDocument(getPrincipalIdForName("ewestfal"), statusChangeEvent.getRouteHeaderId());
document.setApplicationContent(APPLICATION_CONTENT);
document.setTitle(DOC_TITLE);
document.saveRoutingData();
// now route another document from the post processor, sending it an adhoc request
WorkflowDocument ppDocument = new WorkflowDocument(getPrincipalIdForName("user1"), "testModifyDocumentInPostProcessor");
routedDocumentId = ppDocument.getRouteHeaderId();
// principal id 1 = ewestfal
ppDocument.adHocRouteDocumentToPrincipal(KEWConstants.ACTION_REQUEST_APPROVE_REQ, "AdHoc", "", "2001", "", true);
ppDocument.routeDocument("");
processedChange = true;
}
return new ProcessDocReport(true);
}
public ProcessDocReport doRouteLevelChange(DocumentRouteLevelChange levelChangeEvent) throws Exception {
levelChanges++;
WorkflowDocument document = new WorkflowDocument(getPrincipalIdForName("ewestfal"), levelChangeEvent.getRouteHeaderId());
document.setTitle("Current level change: " + levelChanges);
document.saveRoutingData();
return new ProcessDocReport(true);
}
}
public static class GetDocumentIdsToLockPostProcessor extends DefaultPostProcessor {
protected String getPrincipalIdForName(String principalName) {
return KEWServiceLocator.getIdentityHelperService()
.getIdForPrincipalName(principalName);
}
@Override
public List<Long> getDocumentIdsToLock(DocumentLockingEvent lockingEvent) throws Exception {
WorkflowDocument document = new WorkflowDocument(getPrincipalIdForName("ewestfal"), lockingEvent.getRouteHeaderId());
if (shouldReturnDocumentIdsToLock) {
List<Long> docIds = new ArrayList<Long>();
docIds.add(documentBId);
return docIds;
}
return null;
}
@Override
public ProcessDocReport afterProcess(AfterProcessEvent event) throws Exception {
WorkflowDocument wfDocument = new WorkflowDocument(getPrincipalIdForName("ewestfal"), event.getRouteHeaderId());
if (wfDocument.stateIsEnroute()) {
// first, let's load document B in this thread
DocumentRouteHeaderValue document = KEWServiceLocator.getRouteHeaderService().getRouteHeader(documentBId);
// now let's execute the thread
new Thread(updateDocumentThread).start();
// let's wait for a few seconds to either let the thread process or let it aquire the lock
Thread.sleep(5000);
// now update document B
KEWServiceLocator.getRouteHeaderService().saveRouteHeader(document);
}
return super.afterProcess(event);
}
}
/**
* A Thread which simply locks and updates the document
*
* @author Kuali Rice Team ([email protected])
*/
private class UpdateDocumentThread implements Runnable {
private Long documentId;
public UpdateDocumentThread(Long documentId) {
this.documentId = documentId;
}
public void run() {
TransactionTemplate template = new TransactionTemplate(KEWServiceLocator.getPlatformTransactionManager());
template.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
KEWServiceLocator.getRouteHeaderService().lockRouteHeader(documentId, true);
DocumentRouteHeaderValue document = KEWServiceLocator.getRouteHeaderService().getRouteHeader(documentId);
KEWServiceLocator.getRouteHeaderService().saveRouteHeader(document);
return null;
}
});
}
}
}
| test/kew/src/test/java/org/kuali/rice/kew/postprocessor/PostProcessorTest.java | /*
* Copyright 2005-2007 The Kuali Foundation
*
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.kew.postprocessor;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.kuali.rice.kew.doctype.bo.DocumentType;
import org.kuali.rice.kew.routeheader.DocumentRouteHeaderValue;
import org.kuali.rice.kew.service.KEWServiceLocator;
import org.kuali.rice.kew.service.WorkflowDocument;
import org.kuali.rice.kew.test.KEWTestCase;
import org.kuali.rice.kew.util.KEWConstants;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
public class PostProcessorTest extends KEWTestCase {
private static final String APPLICATION_CONTENT = "<some><application>content</application></some>";
private static final String DOC_TITLE = "The Doc Title";
protected void loadTestData() throws Exception {
loadXmlFile("PostProcessorConfig.xml");
}
/**
* Tests that modifying a document in the post processor works. This test will do a few things:
*
* 1) Change the document content in the post processor
* 2) Send an app specific FYI request to the initiator of the document
* 3) Modify the document title.
*
* This test is meant to expose the bug KULWF-668 where it appears an OptimisticLockException is
* being thrown after returning from the EPIC post processor.
*/
@Test public void testModifyDocumentInPostProcessor() throws Exception {
WorkflowDocument document = new WorkflowDocument(getPrincipalIdForName("ewestfal"), "testModifyDocumentInPostProcessor");
document.saveDocument("");
assertEquals("application content should be empty initially", "", document.getApplicationContent());
assertNull("Doc title should be empty initially", document.getTitle());
// now route the document, it should through a 2 nodes, then go PROCESSED then FINAL
document.routeDocument("");
assertEquals("Should have transitioned nodes twice", 2, DocumentModifyingPostProcessor.levelChanges);
assertTrue("SHould have called the processed status change", DocumentModifyingPostProcessor.processedChange);
assertTrue("Document should be final.", document.stateIsFinal());
assertEquals("Application content should have been sucessfully modified.", APPLICATION_CONTENT, document.getApplicationContent());
// check that the title was modified successfully
assertEquals("Wrong doc title", DOC_TITLE, document.getTitle());
// check that the document we routed from the post processor exists
assertNotNull("SHould have routed a document from the post processor.", DocumentModifyingPostProcessor.routedDocumentId);
document = new WorkflowDocument(getPrincipalIdForName("ewestfal"), DocumentModifyingPostProcessor.routedDocumentId);
assertTrue("document should be enroute", document.stateIsEnroute());
assertEquals("Document should have 1 pending request.", 1, KEWServiceLocator.getActionRequestService().findPendingByDoc(document.getRouteHeaderId()).size());
assertTrue("ewestfal should have an approve request.", document.isApprovalRequested());
document.approve("");
assertTrue("Document should be final.", document.stateIsFinal());
}
/**
* Tests that modifying a document in the post processor works. This test will do a few things:
*
* 1) Change the document content in the post processor
* 2) Send an app specific FYI request to the initiator of the document
* 3) Modify the document title.
*
* This test is meant to test that an empty post processor works. The empty post processor should be handled as a DefaultPostProcessor.
*/
@Test public void testEmptyPostProcessor() throws Exception {
WorkflowDocument document = new WorkflowDocument(getPrincipalIdForName("ewestfal"), "testEmptyPostProcessor");
document.saveDocument("");
assertEquals("application content should be empty initially", "", document.getApplicationContent());
assertNull("Doc title should be empty initially", document.getTitle());
assertTrue("Document should be final.", document.stateIsFinal());
DocumentType testEmptyDocType = KEWServiceLocator.getDocumentTypeService().findByName("testEmptyPostProcessor");
assertTrue("Post Processor should be set to 'none'", StringUtils.equals("none", testEmptyDocType.getPostProcessorName()));
assertTrue("Post Processor should be of type DefaultPostProcessor", testEmptyDocType.getPostProcessor() instanceof org.kuali.rice.kew.postprocessor.DefaultPostProcessor);
}
private static boolean shouldReturnDocumentIdsToLock = false;
private static Long documentAId = null;
private static Long documentBId = null;
private static UpdateDocumentThread updateDocumentThread = null;
protected String getPrincipalIdForName(String principalName) {
return KEWServiceLocator.getIdentityHelperService()
.getIdForPrincipalName(principalName);
}
/**
* Tests the locking of additional documents from the Post Processor.
*
* @author Kuali Rice Team ([email protected])
*/
@Test public void testGetDocumentIdsToLock() throws Exception {
/**
* Let's recreate the original optimistic lock scenario that caused this issue to crop up, essentially:
*
* 1) Thread one locks and processes document A in the workflow engine
* 2) Thread one loads document B
* 3) Thread two locks and processes document B from document A's post processor, doing an update which increments the version number of document B
* 4) Thread A attempts to update document B and gets an optimistic lock exception
*/
WorkflowDocument documentB = new WorkflowDocument(getPrincipalIdForName("ewestfal"), "TestDocumentType");
documentB.saveDocument("");
documentBId = documentB.getRouteHeaderId();
updateDocumentThread = new UpdateDocumentThread(documentBId);
// this is the document with the post processor
WorkflowDocument documentA = new WorkflowDocument(getPrincipalIdForName("ewestfal"), "testGetDocumentIdsToLock");
documentA.adHocRouteDocumentToPrincipal(KEWConstants.ACTION_REQUEST_APPROVE_REQ, "", getPrincipalIdForName("rkirkend"), "", true);
try {
documentA.routeDocument(""); // this should trigger our post processor and our optimistic lock exception
fail("An exception should have been thrown as the result of an optimistic lock!");
} catch (Exception e) {
e.printStackTrace();
}
/**
* Now let's try the same thing again, this time returning document B's id as a document to lock, the error should not happen this time
*/
shouldReturnDocumentIdsToLock = true;
documentB = new WorkflowDocument(getPrincipalIdForName("ewestfal"), "TestDocumentType");
documentB.saveDocument("");
documentBId = documentB.getRouteHeaderId();
updateDocumentThread = new UpdateDocumentThread(documentBId);
// this is the document with the post processor
documentA = new WorkflowDocument(getPrincipalIdForName("ewestfal"), "testGetDocumentIdsToLock");
documentA.adHocRouteDocumentToPrincipal(KEWConstants.ACTION_REQUEST_APPROVE_REQ, "", getPrincipalIdForName("rkirkend"), "", true);
documentA.routeDocument(""); // this should trigger our post processor and our optimistic lock exception
documentA = new WorkflowDocument(getPrincipalIdForName("rkirkend"), documentA.getRouteHeaderId());
assertTrue("rkirkend should have approve request", documentA.isApprovalRequested());
}
public static class DocumentModifyingPostProcessor extends DefaultPostProcessor {
public static boolean processedChange = false;
public static int levelChanges = 0;
public static Long routedDocumentId;
protected String getPrincipalIdForName(String principalName) {
return KEWServiceLocator.getIdentityHelperService()
.getIdForPrincipalName(principalName);
}
public ProcessDocReport doRouteStatusChange(DocumentRouteStatusChange statusChangeEvent) throws Exception {
if (KEWConstants.ROUTE_HEADER_PROCESSED_CD.equals(statusChangeEvent.getNewRouteStatus())) {
WorkflowDocument document = new WorkflowDocument(getPrincipalIdForName("ewestfal"), statusChangeEvent.getRouteHeaderId());
document.setApplicationContent(APPLICATION_CONTENT);
document.setTitle(DOC_TITLE);
document.saveRoutingData();
// now route another document from the post processor, sending it an adhoc request
WorkflowDocument ppDocument = new WorkflowDocument(getPrincipalIdForName("user1"), "testModifyDocumentInPostProcessor");
routedDocumentId = ppDocument.getRouteHeaderId();
// principal id 1 = ewestfal
ppDocument.adHocRouteDocumentToPrincipal(KEWConstants.ACTION_REQUEST_APPROVE_REQ, "AdHoc", "", "2001", "", true);
ppDocument.routeDocument("");
processedChange = true;
}
return new ProcessDocReport(true);
}
public ProcessDocReport doRouteLevelChange(DocumentRouteLevelChange levelChangeEvent) throws Exception {
levelChanges++;
WorkflowDocument document = new WorkflowDocument(getPrincipalIdForName("ewestfal"), levelChangeEvent.getRouteHeaderId());
document.setTitle("Current level change: " + levelChanges);
document.saveRoutingData();
return new ProcessDocReport(true);
}
}
public static class GetDocumentIdsToLockPostProcessor extends DefaultPostProcessor {
protected String getPrincipalIdForName(String principalName) {
return KEWServiceLocator.getIdentityHelperService()
.getIdForPrincipalName(principalName);
}
@Override
public List<Long> getDocumentIdsToLock(DocumentLockingEvent lockingEvent) throws Exception {
WorkflowDocument document = new WorkflowDocument(getPrincipalIdForName("ewestfal"), lockingEvent.getRouteHeaderId());
if (shouldReturnDocumentIdsToLock) {
List<Long> docIds = new ArrayList<Long>();
docIds.add(documentBId);
return docIds;
}
return null;
}
@Override
public ProcessDocReport afterProcess(AfterProcessEvent event) throws Exception {
WorkflowDocument wfDocument = new WorkflowDocument(getPrincipalIdForName("ewestfal"), event.getRouteHeaderId());
if (wfDocument.stateIsEnroute()) {
// first, let's load document B in this thread
DocumentRouteHeaderValue document = KEWServiceLocator.getRouteHeaderService().getRouteHeader(documentBId);
// now let's execute the thread
new Thread(updateDocumentThread).start();
// let's wait for a few seconds to either let the thread process or let it aquire the lock
Thread.sleep(5000);
// now update document B
KEWServiceLocator.getRouteHeaderService().saveRouteHeader(document);
}
return super.afterProcess(event);
}
}
/**
* A Thread which simply locks and updates the document
*
* @author Kuali Rice Team ([email protected])
*/
private class UpdateDocumentThread implements Runnable {
private Long documentId;
public UpdateDocumentThread(Long documentId) {
this.documentId = documentId;
}
public void run() {
TransactionTemplate template = new TransactionTemplate(KEWServiceLocator.getPlatformTransactionManager());
template.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
KEWServiceLocator.getRouteHeaderService().lockRouteHeader(documentId, true);
DocumentRouteHeaderValue document = KEWServiceLocator.getRouteHeaderService().getRouteHeader(documentId);
KEWServiceLocator.getRouteHeaderService().saveRouteHeader(document);
return null;
}
});
}
}
}
| KULRICE-4900 - fix for PostProcessorTest
| test/kew/src/test/java/org/kuali/rice/kew/postprocessor/PostProcessorTest.java | KULRICE-4900 - fix for PostProcessorTest |
|
Java | apache-2.0 | 4ff167981a98bffebe7c0f9918313c18d607d926 | 0 | bpark/companion-nlp-micro | /*
* Copyright 2017 Kurt Sparber
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.bpark.companion;
import com.github.bpark.companion.model.AnalyzedText;
import com.github.bpark.companion.model.PersonName;
import com.github.bpark.companion.model.Sentence;
import io.vertx.core.json.Json;
import io.vertx.rxjava.core.AbstractVerticle;
import io.vertx.rxjava.core.eventbus.EventBus;
import io.vertx.rxjava.core.eventbus.Message;
import io.vertx.rxjava.core.eventbus.MessageConsumer;
import opennlp.tools.namefind.NameFinderME;
import opennlp.tools.namefind.TokenNameFinderModel;
import opennlp.tools.postag.POSModel;
import opennlp.tools.postag.POSTaggerME;
import opennlp.tools.sentdetect.SentenceDetectorME;
import opennlp.tools.sentdetect.SentenceModel;
import opennlp.tools.tokenize.Tokenizer;
import opennlp.tools.tokenize.TokenizerME;
import opennlp.tools.tokenize.TokenizerModel;
import opennlp.tools.util.Span;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Verticle to perform a full nlp analysis.
*
* The verticle initializes the openlnp trained models and listens on the eventbus for text to analyze.
* The result contains a list of analyzed sentences.
*
* @author ksr
*/
public class NlpVerticle extends AbstractVerticle {
private static final Logger logger = LoggerFactory.getLogger(NlpVerticle.class);
private static final String MESSAGE_KEY = "message";
private static final String NLP_KEY = "nlp";
private static final String ADDRESS = "nlp.analyze";
private static final String TOKEN_BINARY = "/nlp/en-token.bin";
private static final String NER_PERSON_BINARY = "/nlp/en-ner-person.bin";
private static final String POS_MAXENT_BINARY = "/nlp/en-pos-maxent.bin";
private static final String SENT_BINARY = "/nlp/en-sent.bin";
private Tokenizer tokenizer;
private NameFinderME nameFinder;
private POSTaggerME posTagger;
private SentenceDetectorME sentenceDetectorME;
@Override
public void start() throws Exception {
initTokenizer();
initNameFinder();
initPosTagger();
initSentenceDetector();
registerAnalyzer();
}
private void initTokenizer() {
try (InputStream modelInToken = NlpVerticle.class.getResourceAsStream(TOKEN_BINARY)) {
TokenizerModel modelToken = new TokenizerModel(modelInToken);
tokenizer = new TokenizerME(modelToken);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void initNameFinder() {
try (InputStream modelIn = NlpVerticle.class.getResourceAsStream(NER_PERSON_BINARY)) {
TokenNameFinderModel model = new TokenNameFinderModel(modelIn);
nameFinder = new NameFinderME(model);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void initPosTagger() {
try (InputStream modelIn = NlpVerticle.class.getResourceAsStream(POS_MAXENT_BINARY)) {
POSModel model = new POSModel(modelIn);
posTagger = new POSTaggerME(model);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void initSentenceDetector() {
try (InputStream modelIn = NlpVerticle.class.getResourceAsStream(SENT_BINARY)) {
SentenceModel model = new SentenceModel(modelIn);
sentenceDetectorME = new SentenceDetectorME(model);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void registerAnalyzer() {
EventBus eventBus = vertx.eventBus();
MessageConsumer<String> consumer = eventBus.consumer(ADDRESS);
Observable<Message<String>> observable = consumer.toObservable();
observable.subscribe(message -> {
String id = message.body();
readMessage(id).flatMap(content -> {
logger.info("text to analyze for sentences: {}", content);
String[] sentences = sentenceDetectorME.sentDetect(content);
List<Sentence> analyzedSentences = Stream.of(sentences).map(s -> {
String[] tokens = tokenizer.tokenize(s);
String[] posTags = posTagger.tag(tokens);
List<PersonName> names = findNames(tokens);
return new Sentence(s, tokens, posTags, names);
}).collect(Collectors.toList());
logger.info("evaluated sentences: {}", Arrays.asList(sentences));
return Observable.just(new AnalyzedText(analyzedSentences));
}).flatMap(analyzedText -> saveMessage(id, analyzedText)).subscribe(a -> message.reply(id));
});
}
private List<PersonName> findNames(String[] tokens) {
List<PersonName> names = new ArrayList<>();
Span nameSpans[] = nameFinder.find(tokens);
double[] spanProbs = nameFinder.probs(nameSpans);
for (int i = 0; i < nameSpans.length; i++) {
Span nameSpan = nameSpans[i];
int start = nameSpan.getStart();
int end = nameSpan.getEnd() - 1;
String name;
if (start == end) {
name = tokens[start];
} else {
name = tokens[start] + " " + tokens[end];
}
double probability = spanProbs[i];
String[] nameTokens = Arrays.copyOfRange(tokens, start, end + 1);
names.add(new PersonName(name, nameTokens, probability));
}
return names;
}
private Observable<String> readMessage(String id) {
return vertx.sharedData().<String, String>rxGetClusterWideMap(id)
.flatMap(map -> map.rxGet(MESSAGE_KEY))
.toObservable();
}
private Observable<Void> saveMessage(String id, AnalyzedText analyzedText) {
return vertx.sharedData().<String, String>rxGetClusterWideMap(id)
.flatMap(map -> map.rxPut(NLP_KEY, Json.encode(analyzedText)))
.toObservable();
}
}
| src/main/java/com/github/bpark/companion/NlpVerticle.java | /*
* Copyright 2017 Kurt Sparber
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.bpark.companion;
import com.github.bpark.companion.model.AnalyzedText;
import com.github.bpark.companion.model.PersonName;
import com.github.bpark.companion.model.Sentence;
import io.vertx.core.json.Json;
import io.vertx.rxjava.core.AbstractVerticle;
import io.vertx.rxjava.core.eventbus.EventBus;
import io.vertx.rxjava.core.eventbus.Message;
import io.vertx.rxjava.core.eventbus.MessageConsumer;
import opennlp.tools.namefind.NameFinderME;
import opennlp.tools.namefind.TokenNameFinderModel;
import opennlp.tools.postag.POSModel;
import opennlp.tools.postag.POSTaggerME;
import opennlp.tools.sentdetect.SentenceDetectorME;
import opennlp.tools.sentdetect.SentenceModel;
import opennlp.tools.tokenize.Tokenizer;
import opennlp.tools.tokenize.TokenizerME;
import opennlp.tools.tokenize.TokenizerModel;
import opennlp.tools.util.Span;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Verticle to perform a full nlp analysis.
*
* The verticle initializes the openlnp trained models and listens on the eventbus for text to analyze.
* The result contains a list of analyzed sentences.
*
* @author ksr
*/
public class NlpVerticle extends AbstractVerticle {
private static final Logger logger = LoggerFactory.getLogger(NlpVerticle.class);
private static final String ADDRESS = "nlp.analyze";
private static final String TOKEN_BINARY = "/nlp/en-token.bin";
private static final String NER_PERSON_BINARY = "/nlp/en-ner-person.bin";
private static final String POS_MAXENT_BINARY = "/nlp/en-pos-maxent.bin";
private static final String SENT_BINARY = "/nlp/en-sent.bin";
private Tokenizer tokenizer;
private NameFinderME nameFinder;
private POSTaggerME posTagger;
private SentenceDetectorME sentenceDetectorME;
@Override
public void start() throws Exception {
initTokenizer();
initNameFinder();
initPosTagger();
initSentenceDetector();
registerAnalyzer();
}
private void initTokenizer() {
try (InputStream modelInToken = NlpVerticle.class.getResourceAsStream(TOKEN_BINARY)) {
TokenizerModel modelToken = new TokenizerModel(modelInToken);
tokenizer = new TokenizerME(modelToken);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void initNameFinder() {
try (InputStream modelIn = NlpVerticle.class.getResourceAsStream(NER_PERSON_BINARY)) {
TokenNameFinderModel model = new TokenNameFinderModel(modelIn);
nameFinder = new NameFinderME(model);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void initPosTagger() {
try (InputStream modelIn = NlpVerticle.class.getResourceAsStream(POS_MAXENT_BINARY)) {
POSModel model = new POSModel(modelIn);
posTagger = new POSTaggerME(model);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void initSentenceDetector() {
try (InputStream modelIn = NlpVerticle.class.getResourceAsStream(SENT_BINARY)) {
SentenceModel model = new SentenceModel(modelIn);
sentenceDetectorME = new SentenceDetectorME(model);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void registerAnalyzer() {
EventBus eventBus = vertx.eventBus();
MessageConsumer<String> consumer = eventBus.consumer(ADDRESS);
Observable<Message<String>> observable = consumer.toObservable();
observable.subscribe(message -> {
String messageBody = message.body();
logger.info("text to analyze for sentences: {}", messageBody);
String[] sentences = sentenceDetectorME.sentDetect(messageBody);
List<Sentence> analyzedSentences = Stream.of(sentences).map(s -> {
String[] tokens = tokenizer.tokenize(s);
String[] posTags = posTagger.tag(tokens);
List<PersonName> names = findNames(tokens);
return new Sentence(s, tokens, posTags, names);
}).collect(Collectors.toList());
logger.info("evaluated sentences: {}", Arrays.asList(sentences));
message.reply(Json.encode(new AnalyzedText(analyzedSentences)));
});
}
private List<PersonName> findNames(String[] tokens) {
List<PersonName> names = new ArrayList<>();
Span nameSpans[] = nameFinder.find(tokens);
double[] spanProbs = nameFinder.probs(nameSpans);
for (int i = 0; i < nameSpans.length; i++) {
Span nameSpan = nameSpans[i];
int start = nameSpan.getStart();
int end = nameSpan.getEnd() - 1;
String name;
if (start == end) {
name = tokens[start];
} else {
name = tokens[start] + " " + tokens[end];
}
double probability = spanProbs[i];
String[] nameTokens = Arrays.copyOfRange(tokens, start, end + 1);
names.add(new PersonName(name, nameTokens, probability));
}
return names;
}
}
| moved messages to cluster map
| src/main/java/com/github/bpark/companion/NlpVerticle.java | moved messages to cluster map |
|
Java | apache-2.0 | 474519961faf9aa860cd5df03914526aebe04429 | 0 | vipshop/Saturn,vipshop/Saturn,vipshop/Saturn,vipshop/Saturn,vipshop/Saturn | package com.vip.saturn.job.console.controller.gui;
import com.google.common.collect.Lists;
import com.vip.saturn.job.console.aop.annotation.Audit;
import com.vip.saturn.job.console.aop.annotation.AuditParam;
import com.vip.saturn.job.console.controller.SuccessResponseEntity;
import com.vip.saturn.job.console.domain.RequestResult;
import com.vip.saturn.job.console.domain.ServerBriefInfo;
import com.vip.saturn.job.console.domain.ServerStatus;
import com.vip.saturn.job.console.exception.SaturnJobConsoleException;
import com.vip.saturn.job.console.exception.SaturnJobConsoleGUIException;
import com.vip.saturn.job.console.service.ExecutorService;
import com.vip.saturn.job.console.utils.Permissions;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* Executor overview related operations.
*
* @author kfchu
*/
@RequestMapping("/console/namespaces/{namespace:.+}/executors")
public class ExecutorOverviewController extends AbstractGUIController {
private static final Logger log = LoggerFactory.getLogger(ExecutorOverviewController.class);
private static final String TRAFFIC_OPERATION_EXTRACT = "extract";
private static final String TRAFFIC_OPERATION_RECOVER = "recover";
@Resource
private ExecutorService executorService;
/**
* 获取域下所有executor基本信息
*/
@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
@GetMapping
public SuccessResponseEntity getExecutors(final HttpServletRequest request, @PathVariable String namespace,
@RequestParam(required = false) String status) throws SaturnJobConsoleException {
if ("online".equalsIgnoreCase(status)) {
return new SuccessResponseEntity(executorService.getExecutors(namespace, ServerStatus.ONLINE));
}
return new SuccessResponseEntity(executorService.getExecutors(namespace));
}
/**
* 获取executor被分配的作业分片信息
*/
@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
@GetMapping(value = "/{executorName}/allocation")
public SuccessResponseEntity getExecutorAllocation(final HttpServletRequest request, @PathVariable String namespace,
@PathVariable String executorName) throws SaturnJobConsoleException {
return new SuccessResponseEntity(executorService.getExecutorAllocation(namespace, executorName));
}
/**
* 一键重排
*/
@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
@Audit
@RequiresPermissions(Permissions.executorShardAllAtOnce)
@PostMapping(value = "/shardAll")
public SuccessResponseEntity shardAll(final HttpServletRequest request,
@AuditParam("namespace") @PathVariable String namespace) throws SaturnJobConsoleException {
executorService.shardAll(namespace);
return new SuccessResponseEntity();
}
/*
* 摘流量与流量恢复
*/
@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
@Audit
@RequiresPermissions(Permissions.executorExtractOrRecoverTraffic)
@PostMapping(value = "/{executorName}/traffic")
public SuccessResponseEntity extractOrRecoverTraffic(final HttpServletRequest request,
@AuditParam("namespace") @PathVariable String namespace,
@AuditParam("executorName") @PathVariable String executorName,
@AuditParam("operation") @RequestParam String operation) throws SaturnJobConsoleException {
extractOrRecoverTraffic(namespace, executorName, operation);
return new SuccessResponseEntity();
}
/*
* 批量摘流量与流量恢复
*/
@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
@Audit
@RequiresPermissions(Permissions.executorBatchExtractOrRecoverTraffic)
@PostMapping(value = "/traffic")
public SuccessResponseEntity batchExtractOrRecoverTraffic(final HttpServletRequest request,
@AuditParam("namespace") @PathVariable String namespace,
@AuditParam("executorNames") @RequestParam List<String> executorNames,
@AuditParam("operation") @RequestParam String operation) throws SaturnJobConsoleException {
List<String> success2ExtractOrRecoverTrafficExecutors = Lists.newArrayList();
List<String> fail2ExtractOrRecoverTrafficExecutors = Lists.newArrayList();
for (String executorName : executorNames) {
try {
extractOrRecoverTraffic(namespace, executorName, operation);
success2ExtractOrRecoverTrafficExecutors.add(executorName);
} catch (Exception e) {
log.warn("exception happens during extract or recover traffic of executor:" + executorName, e);
fail2ExtractOrRecoverTrafficExecutors.add(executorName);
}
}
if (!fail2ExtractOrRecoverTrafficExecutors.isEmpty()) {
StringBuilder message = new StringBuilder();
message.append("操作成功的executor:").append(success2ExtractOrRecoverTrafficExecutors).append(",")
.append("操作失败的executor:").append(fail2ExtractOrRecoverTrafficExecutors);
throw new SaturnJobConsoleGUIException(message.toString());
}
return new SuccessResponseEntity();
}
private void extractOrRecoverTraffic(String namespace, String executorName, String operation)
throws SaturnJobConsoleException {
if (TRAFFIC_OPERATION_EXTRACT.equals(operation)) {
executorService.extractTraffic(namespace, executorName);
} else if (TRAFFIC_OPERATION_RECOVER.equals(operation)) {
executorService.recoverTraffic(namespace, executorName);
} else {
throw new SaturnJobConsoleGUIException("operation " + operation + "不支持");
}
}
/**
* 移除executor
*/
@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
@Audit
@RequiresPermissions(Permissions.executorRemove)
@DeleteMapping(value = "/{executorName}")
public SuccessResponseEntity removeExecutor(final HttpServletRequest request,
@AuditParam("namespace") @PathVariable String namespace,
@AuditParam("executorName") @PathVariable String executorName) throws SaturnJobConsoleException {
// check executor is existed and online.
checkExecutorStatus(namespace, executorName, ServerStatus.OFFLINE, "Executor在线,不能移除");
executorService.removeExecutor(namespace, executorName);
return new SuccessResponseEntity();
}
/**
* 批量移除executor
*/
@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
@Audit
@RequiresPermissions(Permissions.executorBatchRemove)
@DeleteMapping
public SuccessResponseEntity batchRemoveExecutors(final HttpServletRequest request,
@AuditParam("namespace") @PathVariable String namespace,
@AuditParam("executorNames") @RequestParam List<String> executorNames) throws SaturnJobConsoleException {
// check executor is existed and online.
List<String> success2RemoveExecutors = Lists.newArrayList();
List<String> fail2RemoveExecutors = Lists.newArrayList();
for (String executorName : executorNames) {
try {
checkExecutorStatus(namespace, executorName, ServerStatus.OFFLINE, "Executor在线,不能移除");
executorService.removeExecutor(namespace, executorName);
success2RemoveExecutors.add(executorName);
} catch (Exception e) {
log.warn("exception happens during remove executor:" + executorName, e);
fail2RemoveExecutors.add(executorName);
}
}
if (!fail2RemoveExecutors.isEmpty()) {
StringBuilder message = new StringBuilder();
message.append("删除成功的executor:").append(success2RemoveExecutors).append(",").append("删除失败的executor:")
.append(fail2RemoveExecutors);
throw new SaturnJobConsoleGUIException(message.toString());
}
return new SuccessResponseEntity();
}
private void checkExecutorStatus(String namespace, String executorName, ServerStatus status, String errMsg)
throws SaturnJobConsoleException {
ServerBriefInfo executorInfo = executorService.getExecutor(namespace, executorName);
if (executorInfo == null) {
throw new SaturnJobConsoleGUIException("Executor不存在");
}
if (status != executorInfo.getStatus()) {
throw new SaturnJobConsoleGUIException(errMsg);
}
}
/**
* 一键Dump,包括threadump和gc.log。
*/
@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
@Audit
@RequiresPermissions(Permissions.executorDump)
@PostMapping(value = "/{executorName}/dump")
public SuccessResponseEntity dump(final HttpServletRequest request,
@AuditParam("namespace") @PathVariable String namespace,
@AuditParam("executorName") @PathVariable String executorName) throws SaturnJobConsoleException {
// check executor is existed and online.
checkExecutorStatus(namespace, executorName, ServerStatus.ONLINE, "Executor必须在线才可以dump");
executorService.dump(namespace, executorName);
return new SuccessResponseEntity();
}
/**
* 一键重启。
*/
@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
@Audit
@RequiresPermissions(Permissions.executorRestart)
@PostMapping(value = "/{executorName}/restart")
public SuccessResponseEntity restart(final HttpServletRequest request,
@AuditParam("namespace") @PathVariable String namespace,
@AuditParam("executorName") @PathVariable String executorName) throws SaturnJobConsoleException {
// check executor is existed and online.
checkExecutorStatus(namespace, executorName, ServerStatus.ONLINE, "Executor必须在线才可以重启");
executorService.restart(namespace, executorName);
return new SuccessResponseEntity();
}
}
| saturn-console-api/src/main/java/com/vip/saturn/job/console/controller/gui/ExecutorOverviewController.java | package com.vip.saturn.job.console.controller.gui;
import com.google.common.collect.Lists;
import com.vip.saturn.job.console.aop.annotation.Audit;
import com.vip.saturn.job.console.aop.annotation.AuditParam;
import com.vip.saturn.job.console.controller.SuccessResponseEntity;
import com.vip.saturn.job.console.domain.RequestResult;
import com.vip.saturn.job.console.domain.ServerBriefInfo;
import com.vip.saturn.job.console.domain.ServerStatus;
import com.vip.saturn.job.console.exception.SaturnJobConsoleException;
import com.vip.saturn.job.console.exception.SaturnJobConsoleGUIException;
import com.vip.saturn.job.console.service.ExecutorService;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* Executor overview related operations.
*
* @author kfchu
*/
@RequestMapping("/console/namespaces/{namespace:.+}/executors")
public class ExecutorOverviewController extends AbstractGUIController {
private static final Logger log = LoggerFactory.getLogger(ExecutorOverviewController.class);
private static final String TRAFFIC_OPERATION_EXTRACT = "extract";
private static final String TRAFFIC_OPERATION_RECOVER = "recover";
@Resource
private ExecutorService executorService;
/**
* 获取域下所有executor基本信息
*/
@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
@GetMapping
public SuccessResponseEntity getExecutors(final HttpServletRequest request, @PathVariable String namespace,
@RequestParam(required = false) String status) throws SaturnJobConsoleException {
if ("online".equalsIgnoreCase(status)) {
return new SuccessResponseEntity(executorService.getExecutors(namespace, ServerStatus.ONLINE));
}
return new SuccessResponseEntity(executorService.getExecutors(namespace));
}
/**
* 获取executor被分配的作业分片信息
*/
@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
@GetMapping(value = "/{executorName}/allocation")
public SuccessResponseEntity getExecutorAllocation(final HttpServletRequest request, @PathVariable String namespace,
@PathVariable String executorName) throws SaturnJobConsoleException {
return new SuccessResponseEntity(executorService.getExecutorAllocation(namespace, executorName));
}
/**
* 一键重排
*/
@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
@Audit
@RequiresPermissions(Permissions.executorShardAllAtOnce)
@PostMapping(value = "/shardAll")
public SuccessResponseEntity shardAll(final HttpServletRequest request,
@AuditParam("namespace") @PathVariable String namespace) throws SaturnJobConsoleException {
executorService.shardAll(namespace);
return new SuccessResponseEntity();
}
/*
* 摘流量与流量恢复
*/
@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
@Audit
@RequiresPermissions(Permissions.executorExtractOrRecoverTraffic)
@PostMapping(value = "/{executorName}/traffic")
public SuccessResponseEntity extractOrRecoverTraffic(final HttpServletRequest request,
@AuditParam("namespace") @PathVariable String namespace,
@AuditParam("executorName") @PathVariable String executorName,
@AuditParam("operation") @RequestParam String operation) throws SaturnJobConsoleException {
extractOrRecoverTraffic(namespace, executorName, operation);
return new SuccessResponseEntity();
}
/*
* 批量摘流量与流量恢复
*/
@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
@Audit
@RequiresPermissions(Permissions.executorBatchExtractOrRecoverTraffic)
@PostMapping(value = "/traffic")
public SuccessResponseEntity batchExtractOrRecoverTraffic(final HttpServletRequest request,
@AuditParam("namespace") @PathVariable String namespace,
@AuditParam("executorNames") @RequestParam List<String> executorNames,
@AuditParam("operation") @RequestParam String operation) throws SaturnJobConsoleException {
List<String> success2ExtractOrRecoverTrafficExecutors = Lists.newArrayList();
List<String> fail2ExtractOrRecoverTrafficExecutors = Lists.newArrayList();
for (String executorName : executorNames) {
try {
extractOrRecoverTraffic(namespace, executorName, operation);
success2ExtractOrRecoverTrafficExecutors.add(executorName);
} catch (Exception e) {
log.warn("exception happens during extract or recover traffic of executor:" + executorName, e);
fail2ExtractOrRecoverTrafficExecutors.add(executorName);
}
}
if (!fail2ExtractOrRecoverTrafficExecutors.isEmpty()) {
StringBuilder message = new StringBuilder();
message.append("操作成功的executor:").append(success2ExtractOrRecoverTrafficExecutors).append(",")
.append("操作失败的executor:")
.append(fail2ExtractOrRecoverTrafficExecutors);
throw new SaturnJobConsoleGUIException(message.toString());
}
return new SuccessResponseEntity();
}
private void extractOrRecoverTraffic(String namespace, String executorName, String operation)
throws SaturnJobConsoleException {
if (TRAFFIC_OPERATION_EXTRACT.equals(operation)) {
executorService.extractTraffic(namespace, executorName);
} else if (TRAFFIC_OPERATION_RECOVER.equals(operation)) {
executorService.recoverTraffic(namespace, executorName);
} else {
throw new SaturnJobConsoleGUIException("operation " + operation + "不支持");
}
}
/**
* 移除executor
*/
@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
@Audit
@RequiresPermissions(Permissions.executorRemove)
@DeleteMapping(value = "/{executorName}")
public SuccessResponseEntity removeExecutor(final HttpServletRequest request,
@AuditParam("namespace") @PathVariable String namespace,
@AuditParam("executorName") @PathVariable String executorName) throws SaturnJobConsoleException {
// check executor is existed and online.
checkExecutorStatus(namespace, executorName, ServerStatus.OFFLINE, "Executor在线,不能移除");
executorService.removeExecutor(namespace, executorName);
return new SuccessResponseEntity();
}
/**
* 批量移除executor
*/
@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
@Audit
@RequiresPermissions(Permissions.executorBatchRemove)
@DeleteMapping
public SuccessResponseEntity batchRemoveExecutors(final HttpServletRequest request,
@AuditParam("namespace") @PathVariable String namespace,
@AuditParam("executorNames") @RequestParam List<String> executorNames) throws SaturnJobConsoleException {
// check executor is existed and online.
List<String> success2RemoveExecutors = Lists.newArrayList();
List<String> fail2RemoveExecutors = Lists.newArrayList();
for (String executorName : executorNames) {
try {
checkExecutorStatus(namespace, executorName, ServerStatus.OFFLINE, "Executor在线,不能移除");
executorService.removeExecutor(namespace, executorName);
success2RemoveExecutors.add(executorName);
} catch (Exception e) {
log.warn("exception happens during remove executor:" + executorName, e);
fail2RemoveExecutors.add(executorName);
}
}
if (!fail2RemoveExecutors.isEmpty()) {
StringBuilder message = new StringBuilder();
message.append("删除成功的executor:").append(success2RemoveExecutors).append(",").append("删除失败的executor:")
.append(fail2RemoveExecutors);
throw new SaturnJobConsoleGUIException(message.toString());
}
return new SuccessResponseEntity();
}
private void checkExecutorStatus(String namespace, String executorName, ServerStatus status, String errMsg)
throws SaturnJobConsoleException {
ServerBriefInfo executorInfo = executorService.getExecutor(namespace, executorName);
if (executorInfo == null) {
throw new SaturnJobConsoleGUIException("Executor不存在");
}
if (status != executorInfo.getStatus()) {
throw new SaturnJobConsoleGUIException(errMsg);
}
}
/**
* 一键Dump,包括threadump和gc.log。
*/
@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
@Audit
@RequiresPermissions(Permissions.executorDump)
@PostMapping(value = "/{executorName}/dump")
public SuccessResponseEntity dump(final HttpServletRequest request,
@AuditParam("namespace") @PathVariable String namespace,
@AuditParam("executorName") @PathVariable String executorName) throws SaturnJobConsoleException {
// check executor is existed and online.
checkExecutorStatus(namespace, executorName, ServerStatus.ONLINE, "Executor必须在线才可以dump");
executorService.dump(namespace, executorName);
return new SuccessResponseEntity();
}
/**
* 一键重启。
*/
@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
@Audit
@RequiresPermissions(Permissions.executorRestart)
@PostMapping(value = "/{executorName}/restart")
public SuccessResponseEntity restart(final HttpServletRequest request,
@AuditParam("namespace") @PathVariable String namespace,
@AuditParam("executorName") @PathVariable String executorName) throws SaturnJobConsoleException {
// check executor is existed and online.
checkExecutorStatus(namespace, executorName, ServerStatus.ONLINE, "Executor必须在线才可以重启");
executorService.restart(namespace, executorName);
return new SuccessResponseEntity();
}
}
| #359 #357 merge, import and format
| saturn-console-api/src/main/java/com/vip/saturn/job/console/controller/gui/ExecutorOverviewController.java | #359 #357 merge, import and format |
|
Java | apache-2.0 | c5ca3126bba031fe20976f6c26be42756c7ee2a7 | 0 | eayun/ovirt-engine,yapengsong/ovirt-engine,eayun/ovirt-engine,halober/ovirt-engine,walteryang47/ovirt-engine,yapengsong/ovirt-engine,halober/ovirt-engine,yingyun001/ovirt-engine,yingyun001/ovirt-engine,OpenUniversity/ovirt-engine,walteryang47/ovirt-engine,zerodengxinchao/ovirt-engine,eayun/ovirt-engine,yingyun001/ovirt-engine,OpenUniversity/ovirt-engine,halober/ovirt-engine,eayun/ovirt-engine,OpenUniversity/ovirt-engine,yingyun001/ovirt-engine,walteryang47/ovirt-engine,OpenUniversity/ovirt-engine,walteryang47/ovirt-engine,yapengsong/ovirt-engine,zerodengxinchao/ovirt-engine,OpenUniversity/ovirt-engine,yingyun001/ovirt-engine,zerodengxinchao/ovirt-engine,walteryang47/ovirt-engine,zerodengxinchao/ovirt-engine,zerodengxinchao/ovirt-engine,halober/ovirt-engine,yapengsong/ovirt-engine,eayun/ovirt-engine,yapengsong/ovirt-engine | package org.ovirt.engine.core.vdsbroker;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.FeatureSupported;
import org.ovirt.engine.core.common.businessentities.NonOperationalReason;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSDomainsData;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.VdsDynamic;
import org.ovirt.engine.core.common.businessentities.VdsStatistics;
import org.ovirt.engine.core.common.businessentities.VmDynamic;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.locks.LockingGroup;
import org.ovirt.engine.core.common.utils.Pair;
import org.ovirt.engine.core.common.vdscommands.SetVdsStatusVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.common.vdscommands.VDSReturnValue;
import org.ovirt.engine.core.common.vdscommands.VdsIdAndVdsVDSCommandParametersBase;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogDirector;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogableBase;
import org.ovirt.engine.core.utils.FileUtil;
import org.ovirt.engine.core.utils.lock.EngineLock;
import org.ovirt.engine.core.utils.lock.LockManagerFactory;
import org.ovirt.engine.core.utils.log.Log;
import org.ovirt.engine.core.utils.log.LogFactory;
import org.ovirt.engine.core.utils.timer.OnTimerMethodAnnotation;
import org.ovirt.engine.core.utils.timer.SchedulerUtil;
import org.ovirt.engine.core.utils.timer.SchedulerUtilQuartzImpl;
import org.ovirt.engine.core.vdsbroker.irsbroker.IRSErrorException;
import org.ovirt.engine.core.vdsbroker.irsbroker.IrsBrokerCommand;
import org.ovirt.engine.core.vdsbroker.vdsbroker.CollectVdsNetworkDataVDSCommand;
import org.ovirt.engine.core.vdsbroker.vdsbroker.GetCapabilitiesVDSCommand;
import org.ovirt.engine.core.vdsbroker.vdsbroker.IVdsServer;
import org.ovirt.engine.core.vdsbroker.vdsbroker.VDSNetworkException;
import org.ovirt.engine.core.vdsbroker.vdsbroker.VDSRecoveringException;
import org.ovirt.engine.core.vdsbroker.vdsbroker.VdsServerConnector;
import org.ovirt.engine.core.vdsbroker.vdsbroker.VdsServerWrapper;
import org.ovirt.engine.core.vdsbroker.xmlrpc.XmlRpcUtils;
public class VdsManager {
private VDS _vds;
private long lastUpdate;
private long updateStartTime;
private static Log log = LogFactory.getLog(VdsManager.class);
public boolean getRefreshStatistics() {
return (_refreshIteration == _numberRefreshesBeforeSave);
}
private static final int VDS_REFRESH_RATE = Config.<Integer> GetValue(ConfigValues.VdsRefreshRate) * 1000;
private String onTimerJobId;
private final int _numberRefreshesBeforeSave = Config.<Integer> GetValue(ConfigValues.NumberVmRefreshesBeforeSave);
private int _refreshIteration = 1;
private final Object _lockObj = new Object();
private static Map<Guid, String> recoveringJobIdMap = new ConcurrentHashMap<Guid, String>();
private boolean isSetNonOperationalExecuted;
private MonitoringStrategy monitoringStrategy;
private EngineLock monitoringLock;
public Object getLockObj() {
return _lockObj;
}
public static void cancelRecoveryJob(Guid vdsId) {
String jobId = recoveringJobIdMap.remove(vdsId);
if (jobId != null) {
log.infoFormat("Cancelling the recovery from crash timer for VDS {0} because vds started initializing", vdsId);
try {
SchedulerUtilQuartzImpl.getInstance().deleteJob(jobId);
} catch (Exception e) {
log.warnFormat("Failed deleting job {0} at cancelRecoveryJob", jobId);
}
}
}
private final AtomicInteger mFailedToRunVmAttempts;
private final AtomicInteger mUnrespondedAttempts;
private static final int VDS_DURING_FAILURE_TIMEOUT_IN_MINUTES = Config
.<Integer> GetValue(ConfigValues.TimeToReduceFailedRunOnVdsInMinutes);
private String duringFailureJobId;
private boolean privateInitialized;
public boolean getInitialized() {
return privateInitialized;
}
public void setInitialized(boolean value) {
privateInitialized = value;
}
private IVdsServer _vdsProxy;
public IVdsServer getVdsProxy() {
return _vdsProxy;
}
public Guid getVdsId() {
return _vdsId;
}
private boolean mBeforeFirstRefresh = true;
public boolean getbeforeFirstRefresh() {
return mBeforeFirstRefresh;
}
public void setbeforeFirstRefresh(boolean value) {
mBeforeFirstRefresh = value;
}
private final Guid _vdsId;
private VdsManager(VDS vds) {
log.info("Entered VdsManager constructor");
_vds = vds;
_vdsId = vds.getId();
monitoringStrategy = MonitoringStrategyFactory.getMonitoringStrategyForVds(vds);
mUnrespondedAttempts = new AtomicInteger();
mFailedToRunVmAttempts = new AtomicInteger();
monitoringLock = new EngineLock(Collections.singletonMap(_vdsId.toString(),
new Pair<String, String>(LockingGroup.VDS_INIT.name(), "")), null);
if (_vds.getStatus() == VDSStatus.PreparingForMaintenance) {
_vds.setPreviousStatus(_vds.getStatus());
} else {
_vds.setPreviousStatus(VDSStatus.Up);
}
// if ssl is on and no certificate file
if (Config.<Boolean> GetValue(ConfigValues.UseSecureConnectionWithServers)
&& !FileUtil.fileExists(Config.resolveCertificatePath())) {
if (_vds.getStatus() != VDSStatus.Maintenance && _vds.getStatus() != VDSStatus.InstallFailed) {
setStatus(VDSStatus.NonResponsive, _vds);
UpdateDynamicData(_vds.getDynamicData());
}
log.error("Could not find VDC Certificate file.");
AuditLogableBase logable = new AuditLogableBase(_vdsId);
AuditLogDirector.log(logable, AuditLogType.CERTIFICATE_FILE_NOT_FOUND);
}
InitVdsBroker();
_vds = null;
}
public static VdsManager buildVdsManager(VDS vds) {
VdsManager vdsManager = new VdsManager(vds);
return vdsManager;
}
public void schedulJobs() {
SchedulerUtil sched = SchedulerUtilQuartzImpl.getInstance();
duringFailureJobId = sched.scheduleAFixedDelayJob(this, "OnVdsDuringFailureTimer", new Class[0],
new Object[0], VDS_DURING_FAILURE_TIMEOUT_IN_MINUTES, VDS_DURING_FAILURE_TIMEOUT_IN_MINUTES,
TimeUnit.MINUTES);
sched.pauseJob(duringFailureJobId);
// start with refresh statistics
_refreshIteration = _numberRefreshesBeforeSave - 1;
onTimerJobId = sched.scheduleAFixedDelayJob(this, "OnTimer", new Class[0], new Object[0], VDS_REFRESH_RATE,
VDS_REFRESH_RATE, TimeUnit.MILLISECONDS);
}
private void InitVdsBroker() {
log.infoFormat("Initialize vdsBroker ({0},{1})", _vds.getHostName(), _vds.getPort());
// Get the values of the timeouts:
int clientTimeOut = Config.<Integer> GetValue(ConfigValues.vdsTimeout) * 1000;
int connectionTimeOut = Config.<Integer>GetValue(ConfigValues.vdsConnectionTimeout) * 1000;
int clientRetries = Config.<Integer>GetValue(ConfigValues.vdsRetries);
Pair<VdsServerConnector, HttpClient> returnValue =
XmlRpcUtils.getConnection(_vds.getHostName(),
_vds.getPort(),
clientTimeOut,
connectionTimeOut,
clientRetries,
VdsServerConnector.class,
Config.<Boolean> GetValue(ConfigValues.UseSecureConnectionWithServers));
_vdsProxy = new VdsServerWrapper(returnValue.getFirst(), returnValue.getSecond());
}
public void UpdateVmDynamic(VmDynamic vmDynamic) {
DbFacade.getInstance().getVmDynamicDao().update(vmDynamic);
}
private VdsUpdateRunTimeInfo _vdsUpdater;
private final VdsMonitor vdsMonitor = new VdsMonitor();
@OnTimerMethodAnnotation("OnTimer")
public void OnTimer() {
if (LockManagerFactory.getLockManager().acquireLock(monitoringLock).getFirst()) {
try {
setIsSetNonOperationalExecuted(false);
Guid vdsId = null;
Guid storagePoolId = null;
String vdsName = null;
ArrayList<VDSDomainsData> domainsList = null;
synchronized (getLockObj()) {
_vds = DbFacade.getInstance().getVdsDao().get(getVdsId());
if (_vds == null) {
log.errorFormat("VdsManager::refreshVdsRunTimeInfo - OnTimer is NULL for {0}",
getVdsId());
return;
}
try {
if (_refreshIteration == _numberRefreshesBeforeSave) {
_refreshIteration = 1;
} else {
_refreshIteration++;
}
if (isMonitoringNeeded()) {
setStartTime();
_vdsUpdater = new VdsUpdateRunTimeInfo(VdsManager.this, _vds, monitoringStrategy);
_vdsUpdater.Refresh();
mUnrespondedAttempts.set(0);
setLastUpdate();
}
if (!getInitialized() && _vds.getStatus() != VDSStatus.NonResponsive
&& _vds.getStatus() != VDSStatus.PendingApproval) {
log.infoFormat("Initializing Host: {0}", _vds.getName());
ResourceManager.getInstance().HandleVdsFinishedInit(_vds.getId());
setInitialized(true);
}
} catch (VDSNetworkException e) {
logNetworkException(e);
} catch (VDSRecoveringException ex) {
HandleVdsRecoveringException(ex);
} catch (IRSErrorException ex) {
logFailureMessage(ex);
} catch (RuntimeException ex) {
logFailureMessage(ex);
}
try {
if (_vdsUpdater != null) {
_vdsUpdater.AfterRefreshTreatment();
// Get vds data for updating domains list, ignoring vds which is down, since it's not
// connected
// to
// the storage anymore (so there is no sense in updating the domains list in that case).
if (_vds != null && _vds.getStatus() != VDSStatus.Maintenance) {
vdsId = _vds.getId();
vdsName = _vds.getName();
storagePoolId = _vds.getStoragePoolId();
domainsList = _vds.getDomains();
}
}
_vds = null;
_vdsUpdater = null;
} catch (IRSErrorException ex) {
logAfterRefreshFailureMessage(ex);
if (log.isDebugEnabled()) {
logException(ex);
}
} catch (RuntimeException ex) {
logAfterRefreshFailureMessage(ex);
logException(ex);
}
}
// Now update the status of domains, this code should not be in
// synchronized part of code
if (domainsList != null) {
IrsBrokerCommand.UpdateVdsDomainsData(vdsId, vdsName, storagePoolId, domainsList);
}
} catch (Exception e) {
log.error("Timer update runtimeinfo failed. Exception:", e);
} finally {
LockManagerFactory.getLockManager().releaseLock(monitoringLock);
}
}
}
private void logFailureMessage(RuntimeException ex) {
log.warnFormat(
"Failed to refresh VDS , vds = {0} : {1}, error = '{2}', continuing.",
_vds.getId(),
_vds.getName(),
ex);
}
private static void logException(final RuntimeException ex) {
log.error("ResourceManager::refreshVdsRunTimeInfo", ex);
}
private void logAfterRefreshFailureMessage(RuntimeException ex) {
log.warnFormat(
"Failed to AfterRefreshTreatment VDS error = '{0}', continuing.",
ExceptionUtils.getMessage(ex));
}
public boolean isMonitoringNeeded() {
return (monitoringStrategy.isMonitoringNeeded(_vds) &&
_vds.getStatus() != VDSStatus.Installing &&
_vds.getStatus() != VDSStatus.InstallFailed &&
_vds.getStatus() != VDSStatus.Reboot &&
_vds.getStatus() != VDSStatus.Maintenance &&
_vds.getStatus() != VDSStatus.PendingApproval && _vds.getStatus() != VDSStatus.Down);
}
private void HandleVdsRecoveringException(VDSRecoveringException ex) {
if (_vds.getStatus() != VDSStatus.Initializing && _vds.getStatus() != VDSStatus.NonOperational) {
setStatus(VDSStatus.Initializing, _vds);
UpdateDynamicData(_vds.getDynamicData());
AuditLogableBase logable = new AuditLogableBase(_vds.getId());
logable.addCustomValue("ErrorMessage", ex.getMessage());
AuditLogDirector.log(logable, AuditLogType.VDS_INITIALIZING);
log.warnFormat(
"Failed to refresh VDS , vds = {0} : {1}, error = {2}, continuing.",
_vds.getId(),
_vds.getName(),
ex.getMessage());
final int VDS_RECOVERY_TIMEOUT_IN_MINUTES = Config.<Integer> GetValue(ConfigValues.VdsRecoveryTimeoutInMintues);
String jobId = SchedulerUtilQuartzImpl.getInstance().scheduleAOneTimeJob(this, "onTimerHandleVdsRecovering", new Class[0],
new Object[0], VDS_RECOVERY_TIMEOUT_IN_MINUTES, TimeUnit.MINUTES);
recoveringJobIdMap.put(_vds.getId(), jobId);
}
}
@OnTimerMethodAnnotation("onTimerHandleVdsRecovering")
public void onTimerHandleVdsRecovering() {
recoveringJobIdMap.remove(getVdsId());
VDS vds = DbFacade.getInstance().getVdsDao().get(getVdsId());
if (vds.getStatus() == VDSStatus.Initializing) {
try {
ResourceManager
.getInstance()
.getEventListener()
.vdsNonOperational(vds.getId(),
NonOperationalReason.TIMEOUT_RECOVERING_FROM_CRASH,
true,
true,
Guid.Empty);
setIsSetNonOperationalExecuted(true);
} catch (RuntimeException exp) {
log.errorFormat(
"HandleVdsRecoveringException::Error in recovery timer treatment, vds = {0} : {1}, error = {2}.",
vds.getId(),
vds.getName(),
exp.getMessage());
}
}
}
/**
* Save dynamic data to cache and DB.
*
* @param dynamicData
*/
public void UpdateDynamicData(VdsDynamic dynamicData) {
DbFacade.getInstance().getVdsDynamicDao().update(dynamicData);
}
/**
* Save statistics data to cache and DB.
*
* @param statisticsData
*/
public void UpdateStatisticsData(VdsStatistics statisticsData) {
DbFacade.getInstance().getVdsStatisticsDao().update(statisticsData);
}
public void activate() {
VDS vds = null;
try {
// refresh vds from db in case changed while was down
log.debugFormat(
"Trying to activate host {0} , meanwhile setting status to Unassigned.",
getVdsId());
vds = DbFacade.getInstance().getVdsDao().get(getVdsId());
/**
* refresh capabilities
*/
VDSStatus newStatus = refreshCapabilities(new AtomicBoolean(), vds);
if (log.isDebugEnabled()) {
log.debugFormat(
"Succeeded to refreshCapabilities for host {0} , new status will be {1} ",
getVdsId(),
newStatus);
}
} catch (java.lang.Exception e) {
log.infoFormat("Failed to activate VDS = {0} with error: {1}.",
getVdsId(), e.getMessage());
} finally {
if (vds != null) {
UpdateDynamicData(vds.getDynamicData());
// Update VDS after testing special hardware capabilities
monitoringStrategy.processHardwareCapabilities(vds);
// Always check VdsVersion
ResourceManager.getInstance().getEventListener().handleVdsVersion(vds.getId());
}
}
}
public void setStatus(VDSStatus status, VDS vds) {
synchronized (getLockObj()) {
if (vds == null) {
vds = DbFacade.getInstance().getVdsDao().get(getVdsId());
}
if (vds.getPreviousStatus() != vds.getStatus()) {
vds.setPreviousStatus(vds.getStatus());
if (_vds != null) {
_vds.setPreviousStatus(vds.getStatus());
}
}
// update to new status
vds.setStatus(status);
if (_vds != null) {
_vds.setStatus(status);
}
switch (status) {
case NonOperational:
if (_vds != null) {
_vds.setNonOperationalReason(vds.getNonOperationalReason());
}
if(vds.getVmCount() > 0) {
break;
}
case NonResponsive:
case Down:
case Maintenance:
vds.setCpuSys(Double.valueOf(0));
vds.setCpuUser(Double.valueOf(0));
vds.setCpuIdle(Double.valueOf(0));
vds.setCpuLoad(Double.valueOf(0));
vds.setUsageCpuPercent(0);
vds.setUsageMemPercent(0);
vds.setUsageNetworkPercent(0);
if (_vds != null) {
_vds.setCpuSys(Double.valueOf(0));
_vds.setCpuUser(Double.valueOf(0));
_vds.setCpuIdle(Double.valueOf(0));
_vds.setCpuLoad(Double.valueOf(0));
_vds.setUsageCpuPercent(0);
_vds.setUsageMemPercent(0);
_vds.setUsageNetworkPercent(0);
}
default:
break;
}
}
}
/**
* This function called when vds have failed vm attempts one in predefined time. Its increments failure attemts to
* one
*
* @param obj
* @param arg
*/
@OnTimerMethodAnnotation("OnVdsDuringFailureTimer")
public void OnVdsDuringFailureTimer() {
synchronized (getLockObj()) {
VDS vds = DbFacade.getInstance().getVdsDao().get(getVdsId());
/**
* Disable timer if vds returns from suspitious mode
*/
if (mFailedToRunVmAttempts.decrementAndGet() == 0) {
SchedulerUtilQuartzImpl.getInstance().pauseJob(duringFailureJobId);
}
/**
* Move vds to Up status from error
*/
if (mFailedToRunVmAttempts.get() < Config.<Integer> GetValue(ConfigValues.NumberOfFailedRunsOnVds)
&& vds.getStatus() == VDSStatus.Error) {
setStatus(VDSStatus.Up, vds);
UpdateDynamicData(vds.getDynamicData());
}
log.infoFormat("OnVdsDuringFailureTimer of vds {0} entered. Time:{1}. Attempts after {2}", vds.getName(),
new java.util.Date(), mFailedToRunVmAttempts);
}
}
public void failedToRunVm(VDS vds) {
if (mFailedToRunVmAttempts.get() < Config.<Integer> GetValue(ConfigValues.NumberOfFailedRunsOnVds)
&& mFailedToRunVmAttempts.incrementAndGet() >= Config
.<Integer> GetValue(ConfigValues.NumberOfFailedRunsOnVds)) {
ResourceManager.getInstance().runVdsCommand(VDSCommandType.SetVdsStatus,
new SetVdsStatusVDSCommandParameters(vds.getId(), VDSStatus.Error));
SchedulerUtilQuartzImpl.getInstance().resumeJob(duringFailureJobId);
AuditLogableBase logable = new AuditLogableBase(vds.getId());
logable.addCustomValue("Time", Config.<Integer> GetValue(ConfigValues.TimeToReduceFailedRunOnVdsInMinutes)
.toString());
AuditLogDirector.log(logable, AuditLogType.VDS_FAILED_TO_RUN_VMS);
log.infoFormat("Vds {0} moved to Error mode after {1} attempts. Time: {2}", vds.getName(),
mFailedToRunVmAttempts, new java.util.Date());
}
}
/**
*/
public void SuccededToRunVm(Guid vmId) {
mUnrespondedAttempts.set(0);
ResourceManager.getInstance().SuccededToRunVm(vmId, _vds.getId());
}
public VDSStatus refreshCapabilities(AtomicBoolean processHardwareCapsNeeded, VDS vds) {
log.debug("GetCapabilitiesVDSCommand started method");
VDS oldVDS = vds.clone();
GetCapabilitiesVDSCommand<VdsIdAndVdsVDSCommandParametersBase> vdsBrokerCommand =
new GetCapabilitiesVDSCommand<VdsIdAndVdsVDSCommandParametersBase>(new VdsIdAndVdsVDSCommandParametersBase(vds));
vdsBrokerCommand.execute();
if (vdsBrokerCommand.getVDSReturnValue().getSucceeded()) {
// Verify version capabilities
HashSet<Version> hostVersions = null;
Version clusterCompatibility = vds.getVdsGroupCompatibilityVersion();
if (FeatureSupported.hardwareInfo(clusterCompatibility) &&
// If the feature is enabled in cluster level, we continue by verifying that this VDS also
// supports the specific cluster level. Otherwise getHardwareInfo API won't exist for the
// host and an exception will be raised by vdsm.
(hostVersions = vds.getSupportedClusterVersionsSet()) != null &&
hostVersions.contains(clusterCompatibility)) {
VDSReturnValue ret = ResourceManager.getInstance().runVdsCommand(VDSCommandType.GetHardwareInfo,
new VdsIdAndVdsVDSCommandParametersBase(vds));
if (!ret.getSucceeded()) {
AuditLogableBase logable = new AuditLogableBase(vds.getId());
AuditLogDirector.log(logable, AuditLogType.VDS_FAILED_TO_GET_HOST_HARDWARE_INFO);
}
}
VDSStatus returnStatus = vds.getStatus();
boolean isSetNonOperational = CollectVdsNetworkDataVDSCommand.persistAndEnforceNetworkCompliance(vds);
if (isSetNonOperational) {
setIsSetNonOperationalExecuted(true);
}
if (isSetNonOperational && returnStatus != VDSStatus.NonOperational) {
if (log.isDebugEnabled()) {
log.debugFormat(
"refreshCapabilities:GetCapabilitiesVDSCommand vds {0} networks do not match its cluster networks, vds will be moved to NonOperational",
vds.getStaticData().getId());
}
vds.setStatus(VDSStatus.NonOperational);
vds.setNonOperationalReason(NonOperationalReason.NETWORK_UNREACHABLE);
returnStatus = vds.getStatus();
}
// We process the software capabilities.
VDSStatus oldStatus = vds.getStatus();
monitoringStrategy.processSoftwareCapabilities(vds);
returnStatus = vds.getStatus();
if (returnStatus != oldStatus && returnStatus == VDSStatus.NonOperational) {
setIsSetNonOperationalExecuted(true);
}
processHardwareCapsNeeded.set(monitoringStrategy.processHardwareCapabilitiesNeeded(oldVDS, vds));
return returnStatus;
} else if (vdsBrokerCommand.getVDSReturnValue().getExceptionObject() != null) {
// if exception is VDSNetworkException then call to
// handleNetworkException
if (vdsBrokerCommand.getVDSReturnValue().getExceptionObject() instanceof VDSNetworkException
&& handleNetworkException((VDSNetworkException) vdsBrokerCommand.getVDSReturnValue()
.getExceptionObject(), vds)) {
UpdateDynamicData(vds.getDynamicData());
UpdateStatisticsData(vds.getStatisticsData());
}
throw vdsBrokerCommand.getVDSReturnValue().getExceptionObject();
} else {
log.errorFormat("refreshCapabilities:GetCapabilitiesVDSCommand failed with no exception!");
throw new RuntimeException(vdsBrokerCommand.getVDSReturnValue().getExceptionString());
}
}
/**
* Handle network exception, return true if save vdsDynamic to DB is needed.
*
* @param ex
* @return
*/
public boolean handleNetworkException(VDSNetworkException ex, VDS vds) {
if (vds.getStatus() != VDSStatus.Down) {
if (mUnrespondedAttempts.get() < Config.<Integer> GetValue(ConfigValues.VDSAttemptsToResetCount)
|| lastUpdate
+ (TimeUnit.SECONDS.toMillis(Config.<Integer> GetValue(ConfigValues.TimeoutToResetVdsInSeconds))) > System.currentTimeMillis()) {
boolean result = false;
if (vds.getStatus() != VDSStatus.Connecting && vds.getStatus() != VDSStatus.PreparingForMaintenance
&& vds.getStatus() != VDSStatus.NonResponsive) {
setStatus(VDSStatus.Connecting, vds);
result = true;
}
mUnrespondedAttempts.incrementAndGet();
return result;
}
if (vds.getStatus() == VDSStatus.NonResponsive || vds.getStatus() == VDSStatus.Maintenance) {
setStatus(VDSStatus.NonResponsive, vds);
return true;
}
setStatus(VDSStatus.NonResponsive, vds);
log.errorFormat(
"Server failed to respond, vds_id = {0}, vds_name = {1}, error = {2}",
vds.getId(), vds.getName(), ex.getMessage());
AuditLogableBase logable = new AuditLogableBase(vds.getId());
AuditLogDirector.log(logable, AuditLogType.VDS_FAILURE);
ResourceManager.getInstance().getEventListener().vdsNotResponding(vds);
}
return true;
}
public void dispose() {
log.info("vdsManager::disposing");
SchedulerUtilQuartzImpl.getInstance().deleteJob(onTimerJobId);
XmlRpcUtils.shutDownConnection(((VdsServerWrapper) _vdsProxy).getHttpClient());
}
/**
* Log the network exception depending on the VDS status.
*
* @param e
* The exception to log.
*/
private void logNetworkException(VDSNetworkException e) {
switch (_vds.getStatus()) {
case Down:
break;
case NonResponsive:
log.debugFormat(
"Failed to refresh VDS , vds = {0} : {1}, VDS Network Error, continuing.\n{2}",
_vds.getId(),
_vds.getName(),
e.getMessage());
break;
default:
log.warnFormat(
"Failed to refresh VDS , vds = {0} : {1}, VDS Network Error, continuing.\n{2}",
_vds.getId(),
_vds.getName(),
e.getMessage());
}
}
public void setIsSetNonOperationalExecuted(boolean isExecuted) {
this.isSetNonOperationalExecuted = isExecuted;
}
public boolean isSetNonOperationalExecuted() {
return isSetNonOperationalExecuted;
}
private void setStartTime() {
updateStartTime = System.currentTimeMillis();
}
private void setLastUpdate() {
lastUpdate = System.currentTimeMillis();
}
/**
* @return elapsed time in milliseconds it took to update the Host run-time info. 0 means the updater never ran.
*/
public long getLastUpdateElapsed() {
return lastUpdate - updateStartTime;
}
/**
* @return VdsMonitor a class with means for lock and conditions for signaling
*/
public VdsMonitor getVdsMonitor() {
return vdsMonitor;
}
}
| backend/manager/modules/vdsbroker/src/main/java/org/ovirt/engine/core/vdsbroker/VdsManager.java | package org.ovirt.engine.core.vdsbroker;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.FeatureSupported;
import org.ovirt.engine.core.common.businessentities.NonOperationalReason;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSDomainsData;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.VdsDynamic;
import org.ovirt.engine.core.common.businessentities.VdsStatistics;
import org.ovirt.engine.core.common.businessentities.VmDynamic;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.locks.LockingGroup;
import org.ovirt.engine.core.common.utils.Pair;
import org.ovirt.engine.core.common.vdscommands.SetVdsStatusVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.common.vdscommands.VDSReturnValue;
import org.ovirt.engine.core.common.vdscommands.VdsIdAndVdsVDSCommandParametersBase;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogDirector;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogableBase;
import org.ovirt.engine.core.utils.FileUtil;
import org.ovirt.engine.core.utils.lock.EngineLock;
import org.ovirt.engine.core.utils.lock.LockManagerFactory;
import org.ovirt.engine.core.utils.log.Log;
import org.ovirt.engine.core.utils.log.LogFactory;
import org.ovirt.engine.core.utils.timer.OnTimerMethodAnnotation;
import org.ovirt.engine.core.utils.timer.SchedulerUtil;
import org.ovirt.engine.core.utils.timer.SchedulerUtilQuartzImpl;
import org.ovirt.engine.core.vdsbroker.irsbroker.IRSErrorException;
import org.ovirt.engine.core.vdsbroker.irsbroker.IrsBrokerCommand;
import org.ovirt.engine.core.vdsbroker.vdsbroker.CollectVdsNetworkDataVDSCommand;
import org.ovirt.engine.core.vdsbroker.vdsbroker.GetCapabilitiesVDSCommand;
import org.ovirt.engine.core.vdsbroker.vdsbroker.IVdsServer;
import org.ovirt.engine.core.vdsbroker.vdsbroker.VDSNetworkException;
import org.ovirt.engine.core.vdsbroker.vdsbroker.VDSRecoveringException;
import org.ovirt.engine.core.vdsbroker.vdsbroker.VdsServerConnector;
import org.ovirt.engine.core.vdsbroker.vdsbroker.VdsServerWrapper;
import org.ovirt.engine.core.vdsbroker.xmlrpc.XmlRpcUtils;
public class VdsManager {
private VDS _vds;
private long lastUpdate;
private long updateStartTime;
private static Log log = LogFactory.getLog(VdsManager.class);
public boolean getRefreshStatistics() {
return (_refreshIteration == _numberRefreshesBeforeSave);
}
private static final int VDS_REFRESH_RATE = Config.<Integer> GetValue(ConfigValues.VdsRefreshRate) * 1000;
private String onTimerJobId;
private final int _numberRefreshesBeforeSave = Config.<Integer> GetValue(ConfigValues.NumberVmRefreshesBeforeSave);
private int _refreshIteration = 1;
private final Object _lockObj = new Object();
private static Map<Guid, String> recoveringJobIdMap = new ConcurrentHashMap<Guid, String>();
private boolean isSetNonOperationalExecuted;
private MonitoringStrategy monitoringStrategy;
private EngineLock monitoringLock;
public Object getLockObj() {
return _lockObj;
}
public static void cancelRecoveryJob(Guid vdsId) {
String jobId = recoveringJobIdMap.remove(vdsId);
if (jobId != null) {
log.infoFormat("Cancelling the recovery from crash timer for VDS {0} because vds started initializing", vdsId);
try {
SchedulerUtilQuartzImpl.getInstance().deleteJob(jobId);
} catch (Exception e) {
log.warnFormat("Failed deleting job {0} at cancelRecoveryJob", jobId);
}
}
}
private final AtomicInteger mFailedToRunVmAttempts;
private final AtomicInteger mUnrespondedAttempts;
private static final int VDS_DURING_FAILURE_TIMEOUT_IN_MINUTES = Config
.<Integer> GetValue(ConfigValues.TimeToReduceFailedRunOnVdsInMinutes);
private String duringFailureJobId;
private boolean privateInitialized;
public boolean getInitialized() {
return privateInitialized;
}
public void setInitialized(boolean value) {
privateInitialized = value;
}
private IVdsServer _vdsProxy;
public IVdsServer getVdsProxy() {
return _vdsProxy;
}
public Guid getVdsId() {
return _vdsId;
}
private boolean mBeforeFirstRefresh = true;
public boolean getbeforeFirstRefresh() {
return mBeforeFirstRefresh;
}
public void setbeforeFirstRefresh(boolean value) {
mBeforeFirstRefresh = value;
}
private final Guid _vdsId;
private VdsManager(VDS vds) {
log.info("Entered VdsManager constructor");
_vds = vds;
_vdsId = vds.getId();
monitoringStrategy = MonitoringStrategyFactory.getMonitoringStrategyForVds(vds);
mUnrespondedAttempts = new AtomicInteger();
mFailedToRunVmAttempts = new AtomicInteger();
monitoringLock = new EngineLock(Collections.singletonMap(_vdsId.toString(),
new Pair<String, String>(LockingGroup.VDS_INIT.name(), "")), null);
if (_vds.getStatus() == VDSStatus.PreparingForMaintenance) {
_vds.setPreviousStatus(_vds.getStatus());
} else {
_vds.setPreviousStatus(VDSStatus.Up);
}
// if ssl is on and no certificate file
if (Config.<Boolean> GetValue(ConfigValues.UseSecureConnectionWithServers)
&& !FileUtil.fileExists(Config.resolveCertificatePath())) {
if (_vds.getStatus() != VDSStatus.Maintenance && _vds.getStatus() != VDSStatus.InstallFailed) {
setStatus(VDSStatus.NonResponsive, _vds);
UpdateDynamicData(_vds.getDynamicData());
}
log.error("Could not find VDC Certificate file.");
AuditLogableBase logable = new AuditLogableBase(_vdsId);
AuditLogDirector.log(logable, AuditLogType.CERTIFICATE_FILE_NOT_FOUND);
}
InitVdsBroker();
_vds = null;
}
public static VdsManager buildVdsManager(VDS vds) {
VdsManager vdsManager = new VdsManager(vds);
return vdsManager;
}
public void schedulJobs() {
SchedulerUtil sched = SchedulerUtilQuartzImpl.getInstance();
duringFailureJobId = sched.scheduleAFixedDelayJob(this, "OnVdsDuringFailureTimer", new Class[0],
new Object[0], VDS_DURING_FAILURE_TIMEOUT_IN_MINUTES, VDS_DURING_FAILURE_TIMEOUT_IN_MINUTES,
TimeUnit.MINUTES);
sched.pauseJob(duringFailureJobId);
// start with refresh statistics
_refreshIteration = _numberRefreshesBeforeSave - 1;
onTimerJobId = sched.scheduleAFixedDelayJob(this, "OnTimer", new Class[0], new Object[0], VDS_REFRESH_RATE,
VDS_REFRESH_RATE, TimeUnit.MILLISECONDS);
}
private void InitVdsBroker() {
log.infoFormat("Initialize vdsBroker ({0},{1})", _vds.getHostName(), _vds.getPort());
// Get the values of the timeouts:
int clientTimeOut = Config.<Integer> GetValue(ConfigValues.vdsTimeout) * 1000;
int connectionTimeOut = Config.<Integer>GetValue(ConfigValues.vdsConnectionTimeout) * 1000;
int clientRetries = Config.<Integer>GetValue(ConfigValues.vdsRetries);
Pair<VdsServerConnector, HttpClient> returnValue =
XmlRpcUtils.getConnection(_vds.getHostName(),
_vds.getPort(),
clientTimeOut,
connectionTimeOut,
clientRetries,
VdsServerConnector.class,
Config.<Boolean> GetValue(ConfigValues.UseSecureConnectionWithServers));
_vdsProxy = new VdsServerWrapper(returnValue.getFirst(), returnValue.getSecond());
}
public void UpdateVmDynamic(VmDynamic vmDynamic) {
DbFacade.getInstance().getVmDynamicDao().update(vmDynamic);
}
private VdsUpdateRunTimeInfo _vdsUpdater;
private final VdsMonitor vdsMonitor = new VdsMonitor();
@OnTimerMethodAnnotation("OnTimer")
public void OnTimer() {
if (LockManagerFactory.getLockManager().acquireLock(monitoringLock).getFirst()) {
try {
setIsSetNonOperationalExecuted(false);
Guid vdsId = null;
Guid storagePoolId = null;
String vdsName = null;
ArrayList<VDSDomainsData> domainsList = null;
synchronized (getLockObj()) {
_vds = DbFacade.getInstance().getVdsDao().get(getVdsId());
if (_vds == null) {
log.errorFormat("VdsManager::refreshVdsRunTimeInfo - OnTimer is NULL for {0}",
getVdsId());
return;
}
try {
if (_refreshIteration == _numberRefreshesBeforeSave) {
_refreshIteration = 1;
} else {
_refreshIteration++;
}
if (isMonitoringNeeded()) {
setStartTime();
_vdsUpdater = new VdsUpdateRunTimeInfo(VdsManager.this, _vds, monitoringStrategy);
_vdsUpdater.Refresh();
mUnrespondedAttempts.set(0);
setLastUpdate();
}
if (!getInitialized() && _vds.getStatus() != VDSStatus.NonResponsive
&& _vds.getStatus() != VDSStatus.PendingApproval) {
log.infoFormat("Initializing Host: {0}", _vds.getName());
ResourceManager.getInstance().HandleVdsFinishedInit(_vds.getId());
setInitialized(true);
}
} catch (VDSNetworkException e) {
logNetworkException(e);
} catch (VDSRecoveringException ex) {
HandleVdsRecoveringException(ex);
} catch (IRSErrorException ex) {
logFailureMessage(ex);
} catch (RuntimeException ex) {
logFailureMessage(ex);
}
try {
if (_vdsUpdater != null) {
_vdsUpdater.AfterRefreshTreatment();
// Get vds data for updating domains list, ignoring vds which is down, since it's not
// connected
// to
// the storage anymore (so there is no sense in updating the domains list in that case).
if (_vds != null && _vds.getStatus() != VDSStatus.Maintenance) {
vdsId = _vds.getId();
vdsName = _vds.getName();
storagePoolId = _vds.getStoragePoolId();
domainsList = _vds.getDomains();
}
}
_vds = null;
_vdsUpdater = null;
} catch (IRSErrorException ex) {
logAfterRefreshFailureMessage(ex);
if (log.isDebugEnabled()) {
logException(ex);
}
} catch (RuntimeException ex) {
logAfterRefreshFailureMessage(ex);
logException(ex);
}
}
// Now update the status of domains, this code should not be in
// synchronized part of code
if (domainsList != null) {
IrsBrokerCommand.UpdateVdsDomainsData(vdsId, vdsName, storagePoolId, domainsList);
}
} catch (Exception e) {
log.error("Timer update runtimeinfo failed. Exception:", e);
} finally {
LockManagerFactory.getLockManager().releaseLock(monitoringLock);
}
}
}
private void logFailureMessage(RuntimeException ex) {
log.warnFormat(
"Failed to refresh VDS , vds = {0} : {1}, error = '{2}', continuing.",
_vds.getId(),
_vds.getName(),
ex);
}
private static void logException(final RuntimeException ex) {
log.error("ResourceManager::refreshVdsRunTimeInfo", ex);
}
private void logAfterRefreshFailureMessage(RuntimeException ex) {
log.warnFormat(
"Failed to AfterRefreshTreatment VDS error = '{0}', continuing.",
ExceptionUtils.getMessage(ex));
}
public boolean isMonitoringNeeded() {
return (monitoringStrategy.isMonitoringNeeded(_vds) &&
_vds.getStatus() != VDSStatus.Installing &&
_vds.getStatus() != VDSStatus.InstallFailed &&
_vds.getStatus() != VDSStatus.Reboot &&
_vds.getStatus() != VDSStatus.Maintenance &&
_vds.getStatus() != VDSStatus.PendingApproval && _vds.getStatus() != VDSStatus.Down);
}
private void HandleVdsRecoveringException(VDSRecoveringException ex) {
if (_vds.getStatus() != VDSStatus.Initializing && _vds.getStatus() != VDSStatus.NonOperational) {
setStatus(VDSStatus.Initializing, _vds);
UpdateDynamicData(_vds.getDynamicData());
AuditLogableBase logable = new AuditLogableBase(_vds.getId());
logable.addCustomValue("ErrorMessage", ex.getMessage());
AuditLogDirector.log(logable, AuditLogType.VDS_INITIALIZING);
log.warnFormat(
"Failed to refresh VDS , vds = {0} : {1}, error = {2}, continuing.",
_vds.getId(),
_vds.getName(),
ex.getMessage());
final int VDS_RECOVERY_TIMEOUT_IN_MINUTES = Config.<Integer> GetValue(ConfigValues.VdsRecoveryTimeoutInMintues);
String jobId = SchedulerUtilQuartzImpl.getInstance().scheduleAOneTimeJob(this, "onTimerHandleVdsRecovering", new Class[0],
new Object[0], VDS_RECOVERY_TIMEOUT_IN_MINUTES, TimeUnit.MINUTES);
recoveringJobIdMap.put(_vds.getId(), jobId);
}
}
@OnTimerMethodAnnotation("onTimerHandleVdsRecovering")
public void onTimerHandleVdsRecovering() {
recoveringJobIdMap.remove(getVdsId());
VDS vds = DbFacade.getInstance().getVdsDao().get(getVdsId());
if (vds.getStatus() == VDSStatus.Initializing) {
try {
ResourceManager
.getInstance()
.getEventListener()
.vdsNonOperational(vds.getId(),
NonOperationalReason.TIMEOUT_RECOVERING_FROM_CRASH,
true,
true,
Guid.Empty);
setIsSetNonOperationalExecuted(true);
} catch (RuntimeException exp) {
log.errorFormat(
"HandleVdsRecoveringException::Error in recovery timer treatment, vds = {0} : {1}, error = {2}.",
vds.getId(),
vds.getName(),
exp.getMessage());
}
}
}
/**
* Save dynamic data to cache and DB.
*
* @param dynamicData
*/
public void UpdateDynamicData(VdsDynamic dynamicData) {
DbFacade.getInstance().getVdsDynamicDao().update(dynamicData);
}
/**
* Save statistics data to cache and DB.
*
* @param statisticsData
*/
public void UpdateStatisticsData(VdsStatistics statisticsData) {
DbFacade.getInstance().getVdsStatisticsDao().update(statisticsData);
}
public void activate() {
VDS vds = null;
try {
// refresh vds from db in case changed while was down
log.debugFormat(
"Trying to activate host {0} , meanwhile setting status to Unassigned.",
getVdsId());
vds = DbFacade.getInstance().getVdsDao().get(getVdsId());
/**
* refresh capabilities
*/
VDSStatus newStatus = refreshCapabilities(new AtomicBoolean(), vds);
if (log.isDebugEnabled()) {
log.debugFormat(
"Succeeded to refreshCapabilities for host {0} , new status will be {1} ",
getVdsId(),
newStatus);
}
} catch (java.lang.Exception e) {
log.infoFormat("Failed to activate VDS = {0} with error: {1}.",
getVdsId(), e.getMessage());
} finally {
if (vds != null) {
UpdateDynamicData(vds.getDynamicData());
// Update VDS after testing special hardware capabilities
monitoringStrategy.processHardwareCapabilities(vds);
// Always check VdsVersion
ResourceManager.getInstance().getEventListener().handleVdsVersion(vds.getId());
}
}
}
public void setStatus(VDSStatus status, VDS vds) {
synchronized (getLockObj()) {
if (vds == null) {
vds = DbFacade.getInstance().getVdsDao().get(getVdsId());
}
if (vds.getPreviousStatus() != vds.getStatus()) {
vds.setPreviousStatus(vds.getStatus());
if (_vds != null) {
_vds.setPreviousStatus(vds.getStatus());
}
}
// update to new status
vds.setStatus(status);
if (_vds != null) {
_vds.setStatus(status);
}
switch (status) {
case NonOperational:
if (_vds != null) {
_vds.setNonOperationalReason(vds.getNonOperationalReason());
}
if(vds.getVmCount() > 0) {
break;
}
case NonResponsive:
case Down:
case Maintenance:
vds.setCpuSys(Double.valueOf(0));
vds.setCpuUser(Double.valueOf(0));
vds.setCpuIdle(Double.valueOf(0));
vds.setCpuLoad(Double.valueOf(0));
vds.setUsageCpuPercent(0);
vds.setUsageMemPercent(0);
vds.setUsageNetworkPercent(0);
if (_vds != null) {
_vds.setCpuSys(Double.valueOf(0));
_vds.setCpuUser(Double.valueOf(0));
_vds.setCpuIdle(Double.valueOf(0));
_vds.setCpuLoad(Double.valueOf(0));
_vds.setUsageCpuPercent(0);
_vds.setUsageMemPercent(0);
_vds.setUsageNetworkPercent(0);
}
}
}
}
/**
* This function called when vds have failed vm attempts one in predefined time. Its increments failure attemts to
* one
*
* @param obj
* @param arg
*/
@OnTimerMethodAnnotation("OnVdsDuringFailureTimer")
public void OnVdsDuringFailureTimer() {
synchronized (getLockObj()) {
VDS vds = DbFacade.getInstance().getVdsDao().get(getVdsId());
/**
* Disable timer if vds returns from suspitious mode
*/
if (mFailedToRunVmAttempts.decrementAndGet() == 0) {
SchedulerUtilQuartzImpl.getInstance().pauseJob(duringFailureJobId);
}
/**
* Move vds to Up status from error
*/
if (mFailedToRunVmAttempts.get() < Config.<Integer> GetValue(ConfigValues.NumberOfFailedRunsOnVds)
&& vds.getStatus() == VDSStatus.Error) {
setStatus(VDSStatus.Up, vds);
UpdateDynamicData(vds.getDynamicData());
}
log.infoFormat("OnVdsDuringFailureTimer of vds {0} entered. Time:{1}. Attempts after {2}", vds.getName(),
new java.util.Date(), mFailedToRunVmAttempts);
}
}
public void failedToRunVm(VDS vds) {
if (mFailedToRunVmAttempts.get() < Config.<Integer> GetValue(ConfigValues.NumberOfFailedRunsOnVds)
&& mFailedToRunVmAttempts.incrementAndGet() >= Config
.<Integer> GetValue(ConfigValues.NumberOfFailedRunsOnVds)) {
ResourceManager.getInstance().runVdsCommand(VDSCommandType.SetVdsStatus,
new SetVdsStatusVDSCommandParameters(vds.getId(), VDSStatus.Error));
SchedulerUtilQuartzImpl.getInstance().resumeJob(duringFailureJobId);
AuditLogableBase logable = new AuditLogableBase(vds.getId());
logable.addCustomValue("Time", Config.<Integer> GetValue(ConfigValues.TimeToReduceFailedRunOnVdsInMinutes)
.toString());
AuditLogDirector.log(logable, AuditLogType.VDS_FAILED_TO_RUN_VMS);
log.infoFormat("Vds {0} moved to Error mode after {1} attempts. Time: {2}", vds.getName(),
mFailedToRunVmAttempts, new java.util.Date());
}
}
/**
*/
public void SuccededToRunVm(Guid vmId) {
mUnrespondedAttempts.set(0);
ResourceManager.getInstance().SuccededToRunVm(vmId, _vds.getId());
}
public VDSStatus refreshCapabilities(AtomicBoolean processHardwareCapsNeeded, VDS vds) {
log.debug("GetCapabilitiesVDSCommand started method");
VDS oldVDS = vds.clone();
GetCapabilitiesVDSCommand vdsBrokerCommand = new GetCapabilitiesVDSCommand(
new VdsIdAndVdsVDSCommandParametersBase(vds));
vdsBrokerCommand.execute();
if (vdsBrokerCommand.getVDSReturnValue().getSucceeded()) {
// Verify version capabilities
HashSet<Version> hostVersions = null;
Version clusterCompatibility = vds.getVdsGroupCompatibilityVersion();
if (FeatureSupported.hardwareInfo(clusterCompatibility) &&
// If the feature is enabled in cluster level, we continue by verifying that this VDS also
// supports the specific cluster level. Otherwise getHardwareInfo API won't exist for the
// host and an exception will be raised by vdsm.
(hostVersions = vds.getSupportedClusterVersionsSet()) != null &&
hostVersions.contains(clusterCompatibility)) {
VDSReturnValue ret = ResourceManager.getInstance().runVdsCommand(VDSCommandType.GetHardwareInfo,
new VdsIdAndVdsVDSCommandParametersBase(vds));
if (!ret.getSucceeded()) {
AuditLogableBase logable = new AuditLogableBase(vds.getId());
AuditLogDirector.log(logable, AuditLogType.VDS_FAILED_TO_GET_HOST_HARDWARE_INFO);
}
}
VDSStatus returnStatus = vds.getStatus();
boolean isSetNonOperational = CollectVdsNetworkDataVDSCommand.persistAndEnforceNetworkCompliance(vds);
if (isSetNonOperational) {
setIsSetNonOperationalExecuted(true);
}
if (isSetNonOperational && returnStatus != VDSStatus.NonOperational) {
if (log.isDebugEnabled()) {
log.debugFormat(
"refreshCapabilities:GetCapabilitiesVDSCommand vds {0} networks do not match its cluster networks, vds will be moved to NonOperational",
vds.getStaticData().getId());
}
vds.setStatus(VDSStatus.NonOperational);
vds.setNonOperationalReason(NonOperationalReason.NETWORK_UNREACHABLE);
returnStatus = vds.getStatus();
}
// We process the software capabilities.
VDSStatus oldStatus = vds.getStatus();
monitoringStrategy.processSoftwareCapabilities(vds);
returnStatus = vds.getStatus();
if (returnStatus != oldStatus && returnStatus == VDSStatus.NonOperational) {
setIsSetNonOperationalExecuted(true);
}
processHardwareCapsNeeded.set(monitoringStrategy.processHardwareCapabilitiesNeeded(oldVDS, vds));
return returnStatus;
} else if (vdsBrokerCommand.getVDSReturnValue().getExceptionObject() != null) {
// if exception is VDSNetworkException then call to
// handleNetworkException
if (vdsBrokerCommand.getVDSReturnValue().getExceptionObject() instanceof VDSNetworkException
&& handleNetworkException((VDSNetworkException) vdsBrokerCommand.getVDSReturnValue()
.getExceptionObject(), vds)) {
UpdateDynamicData(vds.getDynamicData());
UpdateStatisticsData(vds.getStatisticsData());
}
throw vdsBrokerCommand.getVDSReturnValue().getExceptionObject();
} else {
log.errorFormat("refreshCapabilities:GetCapabilitiesVDSCommand failed with no exception!");
throw new RuntimeException(vdsBrokerCommand.getVDSReturnValue().getExceptionString());
}
}
/**
* Handle network exception, return true if save vdsDynamic to DB is needed.
*
* @param ex
* @return
*/
public boolean handleNetworkException(VDSNetworkException ex, VDS vds) {
if (vds.getStatus() != VDSStatus.Down) {
if (mUnrespondedAttempts.get() < Config.<Integer> GetValue(ConfigValues.VDSAttemptsToResetCount)
|| lastUpdate
+ (TimeUnit.SECONDS.toMillis(Config.<Integer> GetValue(ConfigValues.TimeoutToResetVdsInSeconds))) > System.currentTimeMillis()) {
boolean result = false;
if (vds.getStatus() != VDSStatus.Connecting && vds.getStatus() != VDSStatus.PreparingForMaintenance
&& vds.getStatus() != VDSStatus.NonResponsive) {
setStatus(VDSStatus.Connecting, vds);
result = true;
}
mUnrespondedAttempts.incrementAndGet();
return result;
}
if (vds.getStatus() == VDSStatus.NonResponsive || vds.getStatus() == VDSStatus.Maintenance) {
setStatus(VDSStatus.NonResponsive, vds);
return true;
}
setStatus(VDSStatus.NonResponsive, vds);
log.errorFormat(
"Server failed to respond, vds_id = {0}, vds_name = {1}, error = {2}",
vds.getId(), vds.getName(), ex.getMessage());
AuditLogableBase logable = new AuditLogableBase(vds.getId());
AuditLogDirector.log(logable, AuditLogType.VDS_FAILURE);
ResourceManager.getInstance().getEventListener().vdsNotResponding(vds);
}
return true;
}
public void dispose() {
log.info("vdsManager::disposing");
SchedulerUtilQuartzImpl.getInstance().deleteJob(onTimerJobId);
XmlRpcUtils.shutDownConnection(((VdsServerWrapper) _vdsProxy).getHttpClient());
}
/**
* Log the network exception depending on the VDS status.
*
* @param e
* The exception to log.
*/
private void logNetworkException(VDSNetworkException e) {
switch (_vds.getStatus()) {
case Down:
break;
case NonResponsive:
log.debugFormat(
"Failed to refresh VDS , vds = {0} : {1}, VDS Network Error, continuing.\n{2}",
_vds.getId(),
_vds.getName(),
e.getMessage());
break;
default:
log.warnFormat(
"Failed to refresh VDS , vds = {0} : {1}, VDS Network Error, continuing.\n{2}",
_vds.getId(),
_vds.getName(),
e.getMessage());
}
}
public void setIsSetNonOperationalExecuted(boolean isExecuted) {
this.isSetNonOperationalExecuted = isExecuted;
}
public boolean isSetNonOperationalExecuted() {
return isSetNonOperationalExecuted;
}
private void setStartTime() {
updateStartTime = System.currentTimeMillis();
}
private void setLastUpdate() {
lastUpdate = System.currentTimeMillis();
}
/**
* @return elapsed time in milliseconds it took to update the Host run-time info. 0 means the updater never ran.
*/
public long getLastUpdateElapsed() {
return lastUpdate - updateStartTime;
}
/**
* @return VdsMonitor a class with means for lock and conditions for signaling
*/
public VdsMonitor getVdsMonitor() {
return vdsMonitor;
}
}
| engine: Clear compiler warnings
The patch clears compiler/eclipse warnings.
Change-Id: I34991414aa6055e2adabab189d7ae4b1f4b4f9f9
Signed-off-by: Moti Asayag <[email protected]>
| backend/manager/modules/vdsbroker/src/main/java/org/ovirt/engine/core/vdsbroker/VdsManager.java | engine: Clear compiler warnings |
|
Java | apache-2.0 | ec9feedffad3d20670c780c55882e4a7aecd663f | 0 | ctomc/jboss-modules,doctau/jboss-modules,ropalka/jboss-modules,jboss-modules/jboss-modules,jasinner/jboss-modules,Sanne/jboss-modules,Kast0rTr0y/jboss-modules,rogerchina/jboss-modules | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.modules.management;
import java.beans.ConstructorProperties;
import java.util.List;
/**
* Management information about a module instance.
*
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
public final class ModuleInfo {
private final String name;
private final ModuleLoaderMXBean moduleLoader;
private final List<DependencyInfo> dependencies;
private final List<ResourceLoaderInfo> resourceLoaders;
private final String mainClass;
private final String classLoader;
private final String fallbackLoader;
/**
* Construct a new instance.
*
* @param name the module name
* @param moduleLoader the module loader
* @param dependencies the dependencies list
* @param resourceLoaders the resource loaders list
* @param mainClass the main class name
* @param classLoader the class loader
* @param fallbackLoader the fallback loader
*/
@ConstructorProperties({"name", "moduleLoader", "dependencies", "resourceLoaders", "mainClass", "classLoader", "fallbackLoader"})
public ModuleInfo(final String name, final ModuleLoaderMXBean moduleLoader, final List<DependencyInfo> dependencies, final List<ResourceLoaderInfo> resourceLoaders, final String mainClass, final String classLoader, final String fallbackLoader) {
this.name = name;
this.moduleLoader = moduleLoader;
this.dependencies = dependencies;
this.resourceLoaders = resourceLoaders;
this.mainClass = mainClass;
this.classLoader = classLoader;
this.fallbackLoader = fallbackLoader;
}
/**
* Get the name of the corresponding module.
*
* @return the name of the corresponding module
*/
public String getName() {
return name;
}
/**
* Get the associated module loader MXBean.
*
* @return the associated module loader MXBean
*/
public ModuleLoaderMXBean getModuleLoader() {
return moduleLoader;
}
/**
* Get the dependency information list.
*
* @return the dependency information list
*/
public List<DependencyInfo> getDependencies() {
return dependencies;
}
/**
* Get the resource loader information list.
*
* @return the resource loader information list
*/
public List<ResourceLoaderInfo> getResourceLoaders() {
return resourceLoaders;
}
/**
* Get the main class name.
*
* @return the main class name
*/
public String getMainClass() {
return mainClass;
}
/**
* Get the class loader (as a string).
*
* @return the class loader (as a string)
*/
public String getClassLoader() {
return classLoader;
}
/**
* Get the fallback loader (as a string).
*
* @return the fallback loader (as a string)
*/
public String getFallbackLoader() {
return fallbackLoader;
}
}
| src/main/java/org/jboss/modules/management/ModuleInfo.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.modules.management;
import java.beans.ConstructorProperties;
import java.util.List;
/**
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
public final class ModuleInfo {
private final String name;
private final ModuleLoaderMXBean moduleLoader;
private final List<DependencyInfo> dependencies;
private final List<ResourceLoaderInfo> resourceLoaders;
private final String mainClass;
private final String classLoader;
private final String fallbackLoader;
@ConstructorProperties({"name", "moduleLoader", "dependencies", "resourceLoaders", "mainClass", "classLoader", "fallbackLoader"})
public ModuleInfo(final String name, final ModuleLoaderMXBean moduleLoader, final List<DependencyInfo> dependencies, final List<ResourceLoaderInfo> resourceLoaders, final String mainClass, final String classLoader, final String fallbackLoader) {
this.name = name;
this.moduleLoader = moduleLoader;
this.dependencies = dependencies;
this.resourceLoaders = resourceLoaders;
this.mainClass = mainClass;
this.classLoader = classLoader;
this.fallbackLoader = fallbackLoader;
}
public String getName() {
return name;
}
public ModuleLoaderMXBean getModuleLoader() {
return moduleLoader;
}
public List<DependencyInfo> getDependencies() {
return dependencies;
}
public List<ResourceLoaderInfo> getResourceLoaders() {
return resourceLoaders;
}
public String getMainClass() {
return mainClass;
}
public String getClassLoader() {
return classLoader;
}
public String getFallbackLoader() {
return fallbackLoader;
}
}
| Add missing javadoc
| src/main/java/org/jboss/modules/management/ModuleInfo.java | Add missing javadoc |
|
Java | apache-2.0 | ea185a58045db9203fd01e3c0b273505053e6768 | 0 | aloubyansky/pm | /*
* Copyright 2016-2018 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.provisioning.runtime;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.stream.XMLStreamException;
import org.jboss.provisioning.ArtifactCoords;
import org.jboss.provisioning.ArtifactRepositoryManager;
import org.jboss.provisioning.Constants;
import org.jboss.provisioning.DefaultMessageWriter;
import org.jboss.provisioning.Errors;
import org.jboss.provisioning.MessageWriter;
import org.jboss.provisioning.ProvisioningDescriptionException;
import org.jboss.provisioning.ProvisioningException;
import org.jboss.provisioning.config.ConfigId;
import org.jboss.provisioning.config.ConfigItem;
import org.jboss.provisioning.config.ConfigItemContainer;
import org.jboss.provisioning.config.FeatureConfig;
import org.jboss.provisioning.config.FeaturePackConfig;
import org.jboss.provisioning.config.PackageConfig;
import org.jboss.provisioning.config.ProvisioningConfig;
import org.jboss.provisioning.config.ConfigModel;
import org.jboss.provisioning.config.FeatureGroup;
import org.jboss.provisioning.config.FeatureGroupSupport;
import org.jboss.provisioning.spec.FeatureDependencySpec;
import org.jboss.provisioning.spec.FeatureId;
import org.jboss.provisioning.spec.FeatureReferenceSpec;
import org.jboss.provisioning.spec.PackageDependencySpec;
import org.jboss.provisioning.spec.PackageDepsSpec;
import org.jboss.provisioning.spec.SpecId;
import org.jboss.provisioning.util.IoUtils;
import org.jboss.provisioning.util.LayoutUtils;
import org.jboss.provisioning.util.PmCollections;
import org.jboss.provisioning.util.ZipUtils;
import org.jboss.provisioning.xml.FeaturePackXmlParser;
import org.jboss.provisioning.xml.PackageXmlParser;
/**
*
* @author Alexey Loubyansky
*/
public class ProvisioningRuntimeBuilder {
public static ProvisioningRuntimeBuilder newInstance() {
return newInstance(DefaultMessageWriter.getDefaultInstance());
}
public static ProvisioningRuntimeBuilder newInstance(final MessageWriter messageWriter) {
return new ProvisioningRuntimeBuilder(messageWriter);
}
private static void mkdirs(final Path path) throws ProvisioningException {
try {
Files.createDirectories(path);
} catch (IOException e) {
throw new ProvisioningException(Errors.mkdirs(path));
}
}
final long startTime;
String encoding;
String operation;
ArtifactRepositoryManager artifactResolver;
ProvisioningConfig config;
Path installDir;
final Path workDir;
final Path layoutDir;
Path pluginsDir = null;
private final Map<ArtifactCoords.Ga, FeaturePackRuntime.Builder> fpRtBuilders = new HashMap<>();
private final MessageWriter messageWriter;
private List<FeaturePackRuntime.Builder> fpRtBuildersOrdered = new ArrayList<>();
List<ConfigModelResolver> anonymousConfigs = Collections.emptyList();
Map<String, ConfigModelResolver> nameOnlyConfigs = Collections.emptyMap();
Map<String, ConfigModelResolver> modelOnlyConfigs = Collections.emptyMap();
Map<String, Map<String, ConfigModelResolver>> namedModelConfigs = Collections.emptyMap();
Map<ArtifactCoords.Gav, FeaturePackRuntime> fpRuntimes;
Map<String, String> rtParams = Collections.emptyMap();
private ResolvedFeature parentFeature;
// this is a stack of model only configs that are resolved and merged after all
// the named model configs have been resolved. This is done to:
// 1) avoid resolving model only configs that are not going to get merged;
// 2) to avoid adding package dependencies of the model only configs that are not merged.
private List<ConfigModel> modelOnlyConfigSpecs = Collections.emptyList();
private List<ArtifactCoords.Gav> modelOnlyGavs = Collections.emptyList();
private FeaturePackRuntime.Builder thisFpOrigin;
private FeaturePackRuntime.Builder currentFp;
private ConfigModelResolver configResolver;
private FpStack fpConfigStack;
private ProvisioningRuntimeBuilder(final MessageWriter messageWriter) {
startTime = System.currentTimeMillis();
workDir = IoUtils.createRandomTmpDir();
layoutDir = workDir.resolve("layout");
this.messageWriter = messageWriter;
}
public ProvisioningRuntimeBuilder setEncoding(String encoding) {
this.encoding = encoding;
return this;
}
public ProvisioningRuntimeBuilder setArtifactResolver(ArtifactRepositoryManager artifactResolver) {
this.artifactResolver = artifactResolver;
return this;
}
public ProvisioningRuntimeBuilder setConfig(ProvisioningConfig config) {
this.config = config;
return this;
}
public ProvisioningRuntimeBuilder setInstallDir(Path installDir) {
this.installDir = installDir;
return this;
}
public ProvisioningRuntimeBuilder setOperation(String operation) {
this.operation = operation;
return this;
}
public ProvisioningRuntime build() throws ProvisioningException {
fpConfigStack = new FpStack(config);
List<ConfigModelResolver> fpConfigResolvers = Collections.emptyList();
List<ConfigModel> fpConfigConfigs = Collections.emptyList();
List<List<ResolvedFeatureGroupConfig>> fpConfigPushedConfigs = Collections.emptyList();
for(ConfigModel config : config.getDefinedConfigs()) {
if(fpConfigStack.isFilteredOut(config.getId(), true)) {
continue;
}
configResolver = getConfigResolver(config.getId());
fpConfigResolvers = PmCollections.add(fpConfigResolvers, configResolver);
fpConfigConfigs = PmCollections.add(fpConfigConfigs, config);
final List<ResolvedFeatureGroupConfig> pushedFgConfigs = pushResolvedFgConfigs(config);
if(!pushedFgConfigs.isEmpty()) {
fpConfigPushedConfigs = PmCollections.add(fpConfigPushedConfigs, pushedFgConfigs);
}
}
final Collection<FeaturePackConfig> fpConfigs = config.getFeaturePackDeps();
boolean extendedStackLevel = false;
for (FeaturePackConfig fpConfig : fpConfigs) {
extendedStackLevel |= fpConfigStack.push(fpConfig, extendedStackLevel);
}
while(fpConfigStack.hasNext()) {
processFpConfig(fpConfigStack.next());
}
if(extendedStackLevel) {
fpConfigStack.popLevel();
}
if(!fpConfigPushedConfigs.isEmpty()) {
for(List<ResolvedFeatureGroupConfig> pushedConfigs : fpConfigPushedConfigs) {
popResolvedFgConfigs(pushedConfigs);
}
}
for(int i = 0; i < fpConfigConfigs.size(); ++i) {
final ConfigModel config = fpConfigConfigs.get(i);
if(config.getId().isModelOnly()) {
recordModelOnlyConfig(null, config);
continue;
}
processConfig(fpConfigResolvers.get(i), config);
}
resolveConfigs();
switch(fpRtBuildersOrdered.size()) {
case 0: {
fpRuntimes = Collections.emptyMap();
break;
}
case 1: {
final FeaturePackRuntime.Builder builder = fpRtBuildersOrdered.get(0);
copyResources(builder);
fpRuntimes = Collections.singletonMap(builder.gav, builder.build());
break;
}
default: {
fpRuntimes = new LinkedHashMap<>(fpRtBuildersOrdered.size());
for(FeaturePackRuntime.Builder builder : fpRtBuildersOrdered) {
copyResources(builder);
fpRuntimes.put(builder.gav, builder.build());
}
fpRuntimes = Collections.unmodifiableMap(fpRuntimes);
}
}
return new ProvisioningRuntime(this, messageWriter);
}
private void resolveConfigs() throws ProvisioningException {
if(!anonymousConfigs.isEmpty()) {
for(ConfigModelResolver config : anonymousConfigs) {
config.resolve(this);
}
}
if(!nameOnlyConfigs.isEmpty()) {
for(Map.Entry<String, ConfigModelResolver> entry : nameOnlyConfigs.entrySet()) {
entry.getValue().resolve(this);
}
}
if(!modelOnlyConfigSpecs.isEmpty()) {
for(int i = 0; i < modelOnlyConfigSpecs.size(); ++i) {
final ConfigModel modelOnlySpec = modelOnlyConfigSpecs.get(i);
if(!namedModelConfigs.containsKey(modelOnlySpec.getModel())) {
continue;
}
fpConfigStack.activateConfigStack(i);
final ArtifactCoords.Gav fpGav = modelOnlyGavs.get(i);
thisFpOrigin = fpGav == null ? null : loadFpBuilder(modelOnlyGavs.get(i));
currentFp = thisFpOrigin;
if(processConfig(getConfigResolver(modelOnlySpec.getId()), modelOnlySpec) && currentFp != null && !currentFp.ordered) {
orderFpRtBuilder(currentFp);
}
}
}
if(!modelOnlyConfigs.isEmpty()) {
final Iterator<Map.Entry<String, ConfigModelResolver>> i = modelOnlyConfigs.entrySet().iterator();
if(modelOnlyConfigs.size() == 1) {
final Map.Entry<String, ConfigModelResolver> entry = i.next();
final Map<String, ConfigModelResolver> targetConfigs = namedModelConfigs.get(entry.getKey());
if (targetConfigs != null) {
for (Map.Entry<String, ConfigModelResolver> targetConfig : targetConfigs.entrySet()) {
targetConfig.getValue().merge(entry.getValue());
}
}
} else {
while (i.hasNext()) {
final Map.Entry<String, ConfigModelResolver> entry = i.next();
final Map<String, ConfigModelResolver> targetConfigs = namedModelConfigs.get(entry.getKey());
if (targetConfigs != null) {
for (Map.Entry<String, ConfigModelResolver> targetConfig : targetConfigs.entrySet()) {
targetConfig.getValue().merge(entry.getValue());
}
}
}
}
modelOnlyConfigs = Collections.emptyMap();
}
for(Map<String, ConfigModelResolver> configMap : namedModelConfigs.values()) {
for(Map.Entry<String, ConfigModelResolver> configEntry : configMap.entrySet()) {
configEntry.getValue().resolve(this);
}
}
}
private void processFpConfig(FeaturePackConfig fpConfig) throws ProvisioningException {
final FeaturePackRuntime.Builder parentFp = currentFp;
thisFpOrigin = loadFpBuilder(fpConfig.getGav());
currentFp = thisFpOrigin;
List<ConfigModelResolver> fpConfigResolvers = Collections.emptyList();
List<ConfigModel> fpConfigConfigs = Collections.emptyList();
List<List<ResolvedFeatureGroupConfig>> fpConfigPushedConfigs = Collections.emptyList();
for(ConfigModel config : fpConfig.getDefinedConfigs()) {
if(fpConfigStack.isFilteredOut(config.getId(), true)) {
continue;
}
configResolver = getConfigResolver(config.getId());
fpConfigResolvers = PmCollections.add(fpConfigResolvers, configResolver);
fpConfigConfigs = PmCollections.add(fpConfigConfigs, config);
final List<ResolvedFeatureGroupConfig> pushedFgConfigs = pushResolvedFgConfigs(config);
if(!pushedFgConfigs.isEmpty()) {
fpConfigPushedConfigs = PmCollections.add(fpConfigPushedConfigs, pushedFgConfigs);
}
}
List<ConfigModelResolver> specResolvers = Collections.emptyList();
List<ConfigModel> specConfigs = Collections.emptyList();
List<List<ResolvedFeatureGroupConfig>> specPushedConfigs = Collections.emptyList();
for(ConfigModel config : currentFp.spec.getDefinedConfigs()) {
if(fpConfigStack.isFilteredOut(config.getId(), false)) {
continue;
}
configResolver = getConfigResolver(config.getId());
specResolvers = PmCollections.add(specResolvers, configResolver);
specConfigs = PmCollections.add(specConfigs, config);
final List<ResolvedFeatureGroupConfig> pushedFgConfigs = pushResolvedFgConfigs(config);
if(!pushedFgConfigs.isEmpty()) {
specPushedConfigs = PmCollections.add(specPushedConfigs, pushedFgConfigs);
}
}
configResolver = null;
boolean extendedStackLevel = false;
if(currentFp.spec.hasFeaturePackDeps()) {
final Collection<FeaturePackConfig> fpDeps = currentFp.spec.getFeaturePackDeps();
for (FeaturePackConfig fpDep : fpDeps) {
extendedStackLevel |= fpConfigStack.push(fpDep, extendedStackLevel);
}
if (extendedStackLevel) {
while(fpConfigStack.hasNext()) {
processFpConfig(fpConfigStack.next());
}
}
}
boolean contributed = false;
if(!specPushedConfigs.isEmpty()) {
for(List<ResolvedFeatureGroupConfig> pushedConfigs : specPushedConfigs) {
contributed |= popResolvedFgConfigs(pushedConfigs);
}
}
for(int i = 0; i < specConfigs.size(); ++i) {
final ConfigModel config = specConfigs.get(i);
if(config.getId().isModelOnly()) {
recordModelOnlyConfig(fpConfig.getGav(), config);
continue;
}
contributed |= processConfig(specResolvers.get(i), config);
}
if(fpConfig.isInheritPackages()) {
for(String packageName : currentFp.spec.getDefaultPackageNames()) {
if(!fpConfigStack.isPackageExcluded(currentFp.gav, packageName)) {
resolvePackage(packageName);
contributed = true;
}
}
}
if (fpConfig.hasIncludedPackages()) {
for (PackageConfig pkgConfig : fpConfig.getIncludedPackages()) {
if (!fpConfigStack.isPackageExcluded(currentFp.gav, pkgConfig.getName())) {
resolvePackage(pkgConfig.getName());
contributed = true;
} else {
throw new ProvisioningDescriptionException(Errors.unsatisfiedPackageDependency(currentFp.gav, pkgConfig.getName()));
}
}
}
if(!fpConfigPushedConfigs.isEmpty()) {
for(List<ResolvedFeatureGroupConfig> pushedConfigs : fpConfigPushedConfigs) {
contributed |= popResolvedFgConfigs(pushedConfigs);
}
}
for(int i = 0; i < fpConfigConfigs.size(); ++i) {
final ConfigModel config = fpConfigConfigs.get(i);
if(config.getId().isModelOnly()) {
recordModelOnlyConfig(fpConfig.getGav(), config);
continue;
}
contributed |= processConfig(fpConfigResolvers.get(i), config);
}
if (extendedStackLevel) {
fpConfigStack.popLevel();
}
if(!currentFp.ordered && contributed) {
orderFpRtBuilder(currentFp);
}
this.thisFpOrigin = parentFp;
this.currentFp = parentFp;
}
private void recordModelOnlyConfig(ArtifactCoords.Gav gav, ConfigModel config) {
modelOnlyConfigSpecs = PmCollections.add(modelOnlyConfigSpecs, config);
modelOnlyGavs = PmCollections.add(modelOnlyGavs, gav);
fpConfigStack.recordStack();
}
private boolean processConfig(ConfigModelResolver configResolver, ConfigModel config) throws ProvisioningException {
if(this.configResolver != null) {
throw new IllegalStateException();
}
this.configResolver = configResolver;
configResolver.overwriteProps(config.getProperties());
try {
if(config.hasPackageDeps()) {
processPackageDeps(config);
}
processConfigItemContainer(config);
this.configResolver = null;
return true; // the config may be empty but it may tigger model-only merge into it
} catch (ProvisioningException e) {
throw new ProvisioningException(Errors.failedToResolveConfigSpec(config.getModel(), config.getName()), e);
}
}
private ConfigModelResolver getConfigResolver(ConfigId config) {
if(config.getModel() == null) {
if(config.getName() == null) {
final ConfigModelResolver modelBuilder = ConfigModelResolver.anonymous();
anonymousConfigs = PmCollections.add(anonymousConfigs, modelBuilder);
return modelBuilder;
}
ConfigModelResolver modelBuilder = nameOnlyConfigs.get(config.getName());
if(modelBuilder == null) {
modelBuilder = ConfigModelResolver.forName(config.getName());
nameOnlyConfigs = PmCollections.putLinked(nameOnlyConfigs, config.getName(), modelBuilder);
}
return modelBuilder;
}
if(config.getName() == null) {
ConfigModelResolver modelBuilder = modelOnlyConfigs.get(config.getModel());
if(modelBuilder == null) {
modelBuilder = ConfigModelResolver.forModel(config.getModel());
modelOnlyConfigs = PmCollections.putLinked(modelOnlyConfigs, config.getModel(), modelBuilder);
}
return modelBuilder;
}
Map<String, ConfigModelResolver> namedConfigs = namedModelConfigs.get(config.getModel());
if(namedConfigs == null) {
final ConfigModelResolver modelBuilder = ConfigModelResolver.forConfig(config.getModel(), config.getName());
namedConfigs = Collections.singletonMap(config.getName(), modelBuilder);
namedModelConfigs = PmCollections.putLinked(namedModelConfigs, config.getModel(), namedConfigs);
return modelBuilder;
}
ConfigModelResolver modelBuilder = namedConfigs.get(config.getName());
if (modelBuilder == null) {
if (namedConfigs.size() == 1) {
namedConfigs = new LinkedHashMap<>(namedConfigs);
if (namedModelConfigs.size() == 1) {
namedModelConfigs = new LinkedHashMap<>(namedModelConfigs);
}
namedModelConfigs.put(config.getModel(), namedConfigs);
}
modelBuilder = ConfigModelResolver.forConfig(config.getModel(), config.getName());
namedConfigs.put(config.getName(), modelBuilder);
}
return modelBuilder;
}
private boolean processFeatureGroup(FeatureGroupSupport includedFg)
throws ProvisioningException {
final List<ResolvedFeatureGroupConfig> pushedConfigs = pushResolvedFgConfigs(includedFg);
final FeatureGroupSupport originalFg = currentFp.getFeatureGroupSpec(includedFg.getName());
if(originalFg.hasPackageDeps()) {
processPackageDeps(originalFg);
}
if (pushedConfigs.isEmpty()) {
return false;
}
configResolver.startGroup();
boolean resolvedFeatures = processConfigItemContainer(originalFg);
resolvedFeatures |= popResolvedFgConfigs(pushedConfigs);
configResolver.endGroup();
if(includedFg.hasItems()) {
resolvedFeatures |= processConfigItemContainer(includedFg);
}
return resolvedFeatures;
}
private List<ResolvedFeatureGroupConfig> pushResolvedFgConfigs(FeatureGroupSupport config)
throws ProvisioningException {
List<ResolvedFeatureGroupConfig> pushedConfigs = Collections.emptyList();
if(config.hasExternalFeatureGroups()) {
for(Map.Entry<String, FeatureGroup> entry : config.getExternalFeatureGroups().entrySet()) {
final FeaturePackRuntime.Builder originalFp = currentFp;
currentFp = getFpDep(entry.getKey());
final ResolvedFeatureGroupConfig resolvedFgConfig = resolveFeatureGroupConfig(entry.getValue());
if (configResolver.pushConfig(resolvedFgConfig)) {
pushedConfigs = PmCollections.add(pushedConfigs, resolvedFgConfig);
}
currentFp = originalFp;
}
}
if(currentFp == null) {
// if it's the provisioning config which is being processed it doesn't make sense to push it into the config resolver
return pushedConfigs;
}
final ResolvedFeatureGroupConfig resolvedFgConfig = resolveFeatureGroupConfig(config);
if(configResolver.pushConfig(resolvedFgConfig)) {
pushedConfigs = PmCollections.add(pushedConfigs, resolvedFgConfig);
}
return pushedConfigs;
}
private boolean popResolvedFgConfigs(final List<ResolvedFeatureGroupConfig> pushedConfigs)
throws ProvisioningException {
boolean resolvedFeatures = false;
final FeaturePackRuntime.Builder originalFp = currentFp;
for(ResolvedFeatureGroupConfig pushedFgConfig : pushedConfigs) {
currentFp = this.loadFpBuilder(pushedFgConfig.gav);
pushedFgConfig.configResolver.popConfig(currentFp.gav);
if (pushedFgConfig.includedFeatures.isEmpty()) {
continue;
}
for (Map.Entry<ResolvedFeatureId, FeatureConfig> feature : pushedFgConfig.includedFeatures.entrySet()) {
final FeatureConfig includedFc = feature.getValue();
if (includedFc != null && includedFc.hasParams()) {
final ResolvedFeatureId includedId = feature.getKey();
if (pushedFgConfig.configResolver.isFilteredOut(includedId.specId, includedId)) {
continue;
}
// make sure the included ID is in fact present on the feature group branch
if (!pushedFgConfig.configResolver.includes(includedId)) {
throw new ProvisioningException(Errors.featureNotInScope(includedId, pushedFgConfig.fg.getId().toString(), currentFp.gav));
}
resolvedFeatures |= resolveFeature(pushedFgConfig.configResolver, includedFc);
}
}
}
currentFp = originalFp;
return resolvedFeatures;
}
private ResolvedFeatureGroupConfig resolveFeatureGroupConfig(FeatureGroupSupport fg)
throws ProvisioningException {
final ResolvedFeatureGroupConfig resolvedFgc = new ResolvedFeatureGroupConfig(configResolver, fg, currentFp.gav);
resolvedFgc.inheritFeatures = fg.isInheritFeatures();
if(fg.hasExcludedSpecs()) {
resolvedFgc.excludedSpecs = resolveSpecIds(currentFp.gav, fg.getExcludedSpecs());
}
if(fg.hasIncludedSpecs()) {
resolvedFgc.includedSpecs = resolveSpecIds(currentFp.gav, fg.getIncludedSpecs());
}
if(fg.hasExcludedFeatures()) {
resolvedFgc.excludedFeatures = resolveExcludedIds(fg.getExcludedFeatures());
}
if(fg.hasIncludedFeatures()) {
resolvedFgc.includedFeatures = resolveIncludedIds(fg.getIncludedFeatures());
}
return resolvedFgc;
}
private Map<ResolvedFeatureId, FeatureConfig> resolveIncludedIds(Map<FeatureId, FeatureConfig> features) throws ProvisioningException {
if (features.size() == 1) {
final Map.Entry<FeatureId, FeatureConfig> included = features.entrySet().iterator().next();
final FeatureConfig fc = new FeatureConfig(included.getValue());
final ResolvedFeatureSpec resolvedSpec = currentFp.getFeatureSpec(fc.getSpecId().getName());
if (parentFeature != null) {
return Collections.singletonMap(resolvedSpec.resolveIdFromForeignKey(parentFeature.id, fc.getParentRef(), fc.getParams()), fc);
}
return Collections.singletonMap(resolvedSpec.resolveFeatureId(fc.getParams()), fc);
}
final Map<ResolvedFeatureId, FeatureConfig> tmp = new HashMap<>(features.size());
for (Map.Entry<FeatureId, FeatureConfig> included : features.entrySet()) {
final FeatureConfig fc = new FeatureConfig(included.getValue());
final ResolvedFeatureSpec resolvedSpec = currentFp.getFeatureSpec(fc.getSpecId().getName());
if (parentFeature != null) {
tmp.put(resolvedSpec.resolveIdFromForeignKey(parentFeature.id, fc.getParentRef(), fc.getParams()), fc);
} else {
tmp.put(resolvedSpec.resolveFeatureId(fc.getParams()), fc);
}
}
return tmp;
}
private Set<ResolvedFeatureId> resolveExcludedIds(Map<FeatureId, String> features) throws ProvisioningException {
if (features.size() == 1) {
final Map.Entry<FeatureId, String> excluded = features.entrySet().iterator().next();
final FeatureId excludedId = excluded.getKey();
final ResolvedFeatureSpec resolvedSpec = currentFp.getFeatureSpec(excludedId.getSpec().getName());
if(parentFeature != null) {
return Collections.singleton(resolvedSpec.resolveIdFromForeignKey(parentFeature.id, excluded.getValue(), excludedId.getParams()));
}
return Collections.singleton(resolvedSpec.resolveFeatureId(excludedId.getParams()));
}
final Set<ResolvedFeatureId> tmp = new HashSet<>(features.size());
for (Map.Entry<FeatureId, String> excluded : features.entrySet()) {
final FeatureId excludedId = excluded.getKey();
final ResolvedFeatureSpec resolvedSpec = currentFp.getFeatureSpec(excludedId.getSpec().getName());
if(parentFeature != null) {
tmp.add(resolvedSpec.resolveIdFromForeignKey(parentFeature.id, excluded.getValue(), excludedId.getParams()));
} else {
tmp.add(resolvedSpec.resolveFeatureId(excludedId.getParams()));
}
}
return tmp;
}
private static Set<ResolvedSpecId> resolveSpecIds(ArtifactCoords.Gav gav, Set<SpecId> specs) throws ProvisioningException {
if(specs.size() == 1) {
final SpecId specId = specs.iterator().next();
return Collections.singleton(new ResolvedSpecId(gav, specId.getName()));
}
final Set<ResolvedSpecId> tmp = new HashSet<>(specs.size());
for (SpecId specId : specs) {
tmp.add(new ResolvedSpecId(gav, specId.getName()));
}
return tmp;
}
private boolean processConfigItemContainer(ConfigItemContainer ciContainer) throws ProvisioningException {
boolean resolvedFeatures = false;
final FeaturePackRuntime.Builder prevFpOrigin = thisFpOrigin;
if(ciContainer.isResetFeaturePackOrigin()) {
thisFpOrigin = currentFp;
}
if(ciContainer.hasItems()) {
for(ConfigItem item : ciContainer.getItems()) {
final FeaturePackRuntime.Builder originalFp = currentFp;
currentFp = item.getFpDep() == null ? currentFp : getFpDep(item.getFpDep());
try {
if (item.isGroup()) {
final FeatureGroup nestedFg = (FeatureGroup) item;
resolvedFeatures |= processFeatureGroup(nestedFg);
} else {
resolvedFeatures |= resolveFeature(configResolver, (FeatureConfig) item);
}
} catch (ProvisioningException e) {
throw new ProvisioningException(item.isGroup() ?
Errors.failedToProcess(currentFp.gav, ((FeatureGroup)item).getName()) : Errors.failedToProcess(currentFp.gav, (FeatureConfig)item),
e);
}
currentFp = originalFp;
}
}
thisFpOrigin = prevFpOrigin;
return resolvedFeatures;
}
FeaturePackRuntime.Builder getFpDep(final String depName) throws ProvisioningException {
if(Constants.THIS.equals(depName)) {
if(thisFpOrigin == null) {
throw new ProvisioningException("Feature-pack reference 'this' cannot be used in the current context.");
}
return thisFpOrigin;
}
final ArtifactCoords.Gav depGav = currentFp == null ? config.getFeaturePackDep(depName).getGav() : currentFp.spec.getFeaturePackDep(depName).getGav();
return loadFpBuilder(depGav);
}
private boolean resolveFeature(ConfigModelResolver modelBuilder, FeatureConfig fc) throws ProvisioningException {
final ResolvedFeatureSpec spec = currentFp.getFeatureSpec(fc.getSpecId().getName());
final ResolvedFeatureId resolvedId = parentFeature == null ? spec.resolveFeatureId(fc.getParams()) : spec.resolveIdFromForeignKey(parentFeature.id, fc.getParentRef(), fc.getParams());
if(modelBuilder.isFilteredOut(spec.id, resolvedId)) {
return false;
}
final ResolvedFeature myParent = parentFeature;
parentFeature = resolveFeatureDepsAndRefs(modelBuilder, spec, resolvedId,
spec.resolveNonIdParams(parentFeature == null ? null : parentFeature.id, fc.getParentRef(), fc.getParams()), fc.getFeatureDeps());
if(fc.hasUnsetParams()) {
parentFeature.unsetAllParams(fc.getUnsetParams(), true);
}
if(fc.hasResetParams()) {
parentFeature.resetAllParams(fc.getResetParams());
}
processConfigItemContainer(fc);
parentFeature = myParent;
return true;
}
private ResolvedFeature resolveFeatureDepsAndRefs(ConfigModelResolver modelBuilder,
final ResolvedFeatureSpec spec, final ResolvedFeatureId resolvedId, Map<String, Object> resolvedParams,
Collection<FeatureDependencySpec> featureDeps)
throws ProvisioningException {
if(spec.xmlSpec.hasPackageDeps()) {
processPackageDeps(spec.xmlSpec);
}
final ResolvedFeature resolvedFeature = modelBuilder.includeFeature(resolvedId, spec, resolvedParams, resolveFeatureDeps(modelBuilder, featureDeps, spec));
if(spec.xmlSpec.hasFeatureRefs()) {
final ResolvedFeature myParent = parentFeature;
parentFeature = resolvedFeature;
for(FeatureReferenceSpec refSpec : spec.xmlSpec.getFeatureRefs()) {
if(!refSpec.isInclude()) {
continue;
}
final FeaturePackRuntime.Builder originalFp = currentFp;
currentFp = refSpec.getDependency() == null ? currentFp : getFpDep(refSpec.getDependency());
final ResolvedFeatureSpec refResolvedSpec = currentFp.getFeatureSpec(refSpec.getFeature().getName());
final List<ResolvedFeatureId> refIds = spec.resolveRefId(parentFeature, refSpec, refResolvedSpec);
if(!refIds.isEmpty()) {
for (ResolvedFeatureId refId : refIds) {
if (modelBuilder.includes(refId) || modelBuilder.isFilteredOut(refId.specId, refId)) {
continue;
}
resolveFeatureDepsAndRefs(modelBuilder, refResolvedSpec, refId, Collections.emptyMap(), Collections.emptyList());
}
}
currentFp = originalFp;
}
parentFeature = myParent;
}
return resolvedFeature;
}
private Map<ResolvedFeatureId, FeatureDependencySpec> resolveFeatureDeps(ConfigModelResolver modelBuilder,
Collection<FeatureDependencySpec> featureDeps, final ResolvedFeatureSpec spec)
throws ProvisioningException {
Map<ResolvedFeatureId, FeatureDependencySpec> resolvedDeps = spec.resolveFeatureDeps(this, featureDeps);
if(!resolvedDeps.isEmpty()) {
for(Map.Entry<ResolvedFeatureId, FeatureDependencySpec> dep : resolvedDeps.entrySet()) {
if(!dep.getValue().isInclude()) {
continue;
}
final ResolvedFeatureId depId = dep.getKey();
if(modelBuilder.includes(depId) || modelBuilder.isFilteredOut(depId.specId, depId)) {
continue;
}
final FeatureDependencySpec depSpec = dep.getValue();
final FeaturePackRuntime.Builder originalFp = currentFp;
currentFp = depSpec.getDependency() == null ? currentFp : getFpDep(depSpec.getDependency());
resolveFeatureDepsAndRefs(modelBuilder, currentFp.getFeatureSpec(depId.getSpecId().getName()), depId, Collections.emptyMap(), Collections.emptyList());
currentFp = originalFp;
}
}
return resolvedDeps;
}
FeaturePackRuntime.Builder getFpBuilder(ArtifactCoords.Gav gav) throws ProvisioningDescriptionException {
final FeaturePackRuntime.Builder fpRtBuilder = fpRtBuilders.get(gav.toGa());
if(fpRtBuilder == null) {
throw new ProvisioningDescriptionException(Errors.unknownFeaturePack(gav));
}
return fpRtBuilder;
}
private FeaturePackRuntime.Builder loadFpBuilder(ArtifactCoords.Gav gav) throws ProvisioningException {
FeaturePackRuntime.Builder fp = fpRtBuilders.get(gav.toGa());
if(fp == null) {
final Path fpDir = LayoutUtils.getFeaturePackDir(layoutDir, gav, false);
mkdirs(fpDir);
final Path artifactPath = artifactResolver.resolve(gav.toArtifactCoords());
try {
ZipUtils.unzip(artifactPath, fpDir);
} catch (IOException e) {
throw new ProvisioningException("Failed to unzip " + artifactPath + " to " + layoutDir, e);
}
final Path fpXml = fpDir.resolve(Constants.FEATURE_PACK_XML);
if(!Files.exists(fpXml)) {
throw new ProvisioningDescriptionException(Errors.pathDoesNotExist(fpXml));
}
try(BufferedReader reader = Files.newBufferedReader(fpXml)) {
fp = FeaturePackRuntime.builder(gav, FeaturePackXmlParser.getInstance().parse(reader), fpDir);
} catch (IOException | XMLStreamException e) {
throw new ProvisioningException(Errors.parseXml(fpXml), e);
}
fpRtBuilders.put(gav.toGa(), fp);
} else if(!fp.gav.equals(gav)) {
throw new ProvisioningException(Errors.featurePackVersionConflict(fp.gav, gav));
}
return fp;
}
private void resolvePackage(final String pkgName)
throws ProvisioningException {
final PackageRuntime.Builder pkgRt = currentFp.pkgBuilders.get(pkgName);
if(pkgRt != null) {
return;
}
final PackageRuntime.Builder pkg = currentFp.newPackage(pkgName, LayoutUtils.getPackageDir(currentFp.dir, pkgName, false));
if(!Files.exists(pkg.dir)) {
throw new ProvisioningDescriptionException(Errors.packageNotFound(currentFp.gav, pkgName));
}
final Path pkgXml = pkg.dir.resolve(Constants.PACKAGE_XML);
if(!Files.exists(pkgXml)) {
throw new ProvisioningDescriptionException(Errors.pathDoesNotExist(pkgXml));
}
try(BufferedReader reader = Files.newBufferedReader(pkgXml)) {
pkg.spec = PackageXmlParser.getInstance().parse(reader);
} catch (IOException | XMLStreamException e) {
throw new ProvisioningException(Errors.parseXml(pkgXml), e);
}
if(pkg.spec.hasPackageDeps()) {
try {
processPackageDeps(pkg.spec);
} catch(ProvisioningException e) {
throw new ProvisioningDescriptionException(Errors.resolvePackage(currentFp.gav, pkg.spec.getName()), e);
}
}
currentFp.addPackage(pkgName);
}
private void processPackageDeps(final PackageDepsSpec pkgDeps)
throws ProvisioningException {
if (pkgDeps.hasLocalPackageDeps()) {
for (PackageDependencySpec dep : pkgDeps.getLocalPackageDeps()) {
if(fpConfigStack.isPackageExcluded(currentFp.gav, dep.getName())) {
if(!dep.isOptional()) {
throw new ProvisioningDescriptionException(Errors.unsatisfiedPackageDependency(currentFp.gav, dep.getName()));
}
continue;
}
try {
resolvePackage(dep.getName());
} catch(ProvisioningDescriptionException e) {
if(dep.isOptional()) {
continue;
} else {
throw e;
}
}
}
}
if(!pkgDeps.hasExternalPackageDeps()) {
return;
}
for (String depName : pkgDeps.getExternalPackageSources()) {
final FeaturePackRuntime.Builder originalFp = currentFp;
currentFp = this.getFpDep(depName);
boolean resolvedPackages = false;
for (PackageDependencySpec pkgDep : pkgDeps.getExternalPackageDeps(depName)) {
if (fpConfigStack.isPackageExcluded(currentFp.gav, pkgDep.getName())) {
if (!pkgDep.isOptional()) {
final ArtifactCoords.Gav originGav = currentFp.gav;
currentFp = originalFp;
throw new ProvisioningDescriptionException(Errors.unsatisfiedPackageDependency(originGav, pkgDep.getName()));
}
continue;
}
try {
resolvePackage(pkgDep.getName());
resolvedPackages = true;
} catch (ProvisioningDescriptionException e) {
if (pkgDep.isOptional()) {
continue;
} else {
currentFp = originalFp;
throw e;
}
}
}
if (!currentFp.ordered && resolvedPackages) {
orderFpRtBuilder(currentFp);
}
currentFp = originalFp;
}
}
private void orderFpRtBuilder(final FeaturePackRuntime.Builder fpRtBuilder) {
this.fpRtBuildersOrdered.add(fpRtBuilder);
fpRtBuilder.ordered = true;
}
private void copyResources(FeaturePackRuntime.Builder fpRtBuilder) throws ProvisioningException {
// resources should be copied last overriding the dependency resources
final Path fpResources = fpRtBuilder.dir.resolve(Constants.RESOURCES);
if(Files.exists(fpResources)) {
try {
IoUtils.copy(fpResources, workDir.resolve(Constants.RESOURCES));
} catch (IOException e) {
throw new ProvisioningException(Errors.copyFile(fpResources, workDir.resolve(Constants.RESOURCES)), e);
}
}
final Path fpPlugins = fpRtBuilder.dir.resolve(Constants.PLUGINS);
if(Files.exists(fpPlugins)) {
if(pluginsDir == null) {
pluginsDir = workDir.resolve(Constants.PLUGINS);
}
try {
IoUtils.copy(fpPlugins, pluginsDir);
} catch (IOException e) {
throw new ProvisioningException(Errors.copyFile(fpPlugins, workDir.resolve(Constants.PLUGINS)), e);
}
}
}
public ProvisioningRuntimeBuilder addParameter(String name, String param) {
rtParams = PmCollections.put(rtParams, name, param);
return this;
}
public ProvisioningRuntimeBuilder addAllParameters(Map<String, String> params) {
for(Map.Entry<String, String> param : params.entrySet()) {
addParameter(param.getKey(), param.getValue());
}
return this;
}
}
| feature-pack-api/src/main/java/org/jboss/provisioning/runtime/ProvisioningRuntimeBuilder.java | /*
* Copyright 2016-2018 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.provisioning.runtime;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.stream.XMLStreamException;
import org.jboss.provisioning.ArtifactCoords;
import org.jboss.provisioning.ArtifactRepositoryManager;
import org.jboss.provisioning.Constants;
import org.jboss.provisioning.DefaultMessageWriter;
import org.jboss.provisioning.Errors;
import org.jboss.provisioning.MessageWriter;
import org.jboss.provisioning.ProvisioningDescriptionException;
import org.jboss.provisioning.ProvisioningException;
import org.jboss.provisioning.config.ConfigId;
import org.jboss.provisioning.config.ConfigItem;
import org.jboss.provisioning.config.ConfigItemContainer;
import org.jboss.provisioning.config.FeatureConfig;
import org.jboss.provisioning.config.FeaturePackConfig;
import org.jboss.provisioning.config.PackageConfig;
import org.jboss.provisioning.config.ProvisioningConfig;
import org.jboss.provisioning.config.ConfigModel;
import org.jboss.provisioning.config.FeatureGroup;
import org.jboss.provisioning.config.FeatureGroupSupport;
import org.jboss.provisioning.spec.FeatureDependencySpec;
import org.jboss.provisioning.spec.FeatureId;
import org.jboss.provisioning.spec.FeatureReferenceSpec;
import org.jboss.provisioning.spec.PackageDependencySpec;
import org.jboss.provisioning.spec.PackageDepsSpec;
import org.jboss.provisioning.spec.SpecId;
import org.jboss.provisioning.util.IoUtils;
import org.jboss.provisioning.util.LayoutUtils;
import org.jboss.provisioning.util.PmCollections;
import org.jboss.provisioning.util.ZipUtils;
import org.jboss.provisioning.xml.FeaturePackXmlParser;
import org.jboss.provisioning.xml.PackageXmlParser;
/**
*
* @author Alexey Loubyansky
*/
public class ProvisioningRuntimeBuilder {
public static ProvisioningRuntimeBuilder newInstance() {
return newInstance(DefaultMessageWriter.getDefaultInstance());
}
public static ProvisioningRuntimeBuilder newInstance(final MessageWriter messageWriter) {
return new ProvisioningRuntimeBuilder(messageWriter);
}
private static void mkdirs(final Path path) throws ProvisioningException {
try {
Files.createDirectories(path);
} catch (IOException e) {
throw new ProvisioningException(Errors.mkdirs(path));
}
}
final long startTime;
String encoding;
String operation;
ArtifactRepositoryManager artifactResolver;
ProvisioningConfig config;
Path installDir;
final Path workDir;
final Path layoutDir;
Path pluginsDir = null;
private final Map<ArtifactCoords.Ga, FeaturePackRuntime.Builder> fpRtBuilders = new HashMap<>();
private final MessageWriter messageWriter;
private List<FeaturePackRuntime.Builder> fpRtBuildersOrdered = new ArrayList<>();
List<ConfigModelResolver> anonymousConfigs = Collections.emptyList();
Map<String, ConfigModelResolver> nameOnlyConfigs = Collections.emptyMap();
Map<String, ConfigModelResolver> modelOnlyConfigs = Collections.emptyMap();
Map<String, Map<String, ConfigModelResolver>> namedModelConfigs = Collections.emptyMap();
Map<ArtifactCoords.Gav, FeaturePackRuntime> fpRuntimes;
Map<String, String> rtParams = Collections.emptyMap();
private ResolvedFeature parentFeature;
// this is a stack of model only configs that are resolved and merged after all
// the named model configs have been resolved. This is done to:
// 1) avoid resolving model only configs that are not going to get merged;
// 2) to avoid adding package dependencies of the model only configs that are not merged.
private List<ConfigModel> modelOnlyConfigSpecs = Collections.emptyList();
private List<ArtifactCoords.Gav> modelOnlyGavs = Collections.emptyList();
private FeaturePackRuntime.Builder thisFpOrigin;
private FeaturePackRuntime.Builder currentFp;
private ConfigModelResolver configResolver;
private FpStack fpConfigStack;
private ProvisioningRuntimeBuilder(final MessageWriter messageWriter) {
startTime = System.currentTimeMillis();
workDir = IoUtils.createRandomTmpDir();
layoutDir = workDir.resolve("layout");
this.messageWriter = messageWriter;
}
public ProvisioningRuntimeBuilder setEncoding(String encoding) {
this.encoding = encoding;
return this;
}
public ProvisioningRuntimeBuilder setArtifactResolver(ArtifactRepositoryManager artifactResolver) {
this.artifactResolver = artifactResolver;
return this;
}
public ProvisioningRuntimeBuilder setConfig(ProvisioningConfig config) {
this.config = config;
return this;
}
public ProvisioningRuntimeBuilder setInstallDir(Path installDir) {
this.installDir = installDir;
return this;
}
public ProvisioningRuntimeBuilder setOperation(String operation) {
this.operation = operation;
return this;
}
public ProvisioningRuntime build() throws ProvisioningException {
fpConfigStack = new FpStack(config);
List<ConfigModelResolver> fpConfigResolvers = Collections.emptyList();
List<ConfigModel> fpConfigConfigs = Collections.emptyList();
List<List<ResolvedFeatureGroupConfig>> fpConfigPushedConfigs = Collections.emptyList();
for(ConfigModel config : config.getDefinedConfigs()) {
if(fpConfigStack.isFilteredOut(config.getId(), true)) {
continue;
}
configResolver = getConfigResolver(config.getId());
fpConfigResolvers = PmCollections.add(fpConfigResolvers, configResolver);
fpConfigConfigs = PmCollections.add(fpConfigConfigs, config);
final List<ResolvedFeatureGroupConfig> pushedFgConfigs = pushResolvedFgConfigs(config);
if(!pushedFgConfigs.isEmpty()) {
fpConfigPushedConfigs = PmCollections.add(fpConfigPushedConfigs, pushedFgConfigs);
}
}
final Collection<FeaturePackConfig> fpConfigs = config.getFeaturePackDeps();
boolean extendedStackLevel = false;
for (FeaturePackConfig fpConfig : fpConfigs) {
extendedStackLevel |= fpConfigStack.push(fpConfig, extendedStackLevel);
}
while(fpConfigStack.hasNext()) {
processFpConfig(fpConfigStack.next());
}
if(extendedStackLevel) {
fpConfigStack.popLevel();
}
if(!fpConfigPushedConfigs.isEmpty()) {
for(List<ResolvedFeatureGroupConfig> pushedConfigs : fpConfigPushedConfigs) {
popResolvedFgConfigs(pushedConfigs);
}
}
for(int i = 0; i < fpConfigConfigs.size(); ++i) {
final ConfigModel config = fpConfigConfigs.get(i);
if(config.getId().isModelOnly()) {
recordModelOnlyConfig(null, config);
continue;
}
processConfig(fpConfigResolvers.get(i), config);
}
resolveConfigs();
switch(fpRtBuildersOrdered.size()) {
case 0: {
fpRuntimes = Collections.emptyMap();
break;
}
case 1: {
final FeaturePackRuntime.Builder builder = fpRtBuildersOrdered.get(0);
copyResources(builder);
fpRuntimes = Collections.singletonMap(builder.gav, builder.build());
break;
}
default: {
fpRuntimes = new LinkedHashMap<>(fpRtBuildersOrdered.size());
for(FeaturePackRuntime.Builder builder : fpRtBuildersOrdered) {
copyResources(builder);
fpRuntimes.put(builder.gav, builder.build());
}
fpRuntimes = Collections.unmodifiableMap(fpRuntimes);
}
}
return new ProvisioningRuntime(this, messageWriter);
}
private void resolveConfigs() throws ProvisioningException {
if(!anonymousConfigs.isEmpty()) {
for(ConfigModelResolver config : anonymousConfigs) {
config.resolve(this);
}
}
if(!nameOnlyConfigs.isEmpty()) {
for(Map.Entry<String, ConfigModelResolver> entry : nameOnlyConfigs.entrySet()) {
entry.getValue().resolve(this);
}
}
if(!modelOnlyConfigSpecs.isEmpty()) {
for(int i = 0; i < modelOnlyConfigSpecs.size(); ++i) {
final ConfigModel modelOnlySpec = modelOnlyConfigSpecs.get(i);
if(!namedModelConfigs.containsKey(modelOnlySpec.getModel())) {
continue;
}
fpConfigStack.activateConfigStack(i);
final ArtifactCoords.Gav fpGav = modelOnlyGavs.get(i);
thisFpOrigin = fpGav == null ? null : loadFpBuilder(modelOnlyGavs.get(i));
currentFp = thisFpOrigin;
if(processConfig(getConfigResolver(modelOnlySpec.getId()), modelOnlySpec) && currentFp != null && !currentFp.ordered) {
orderFpRtBuilder(currentFp);
}
}
}
if(!modelOnlyConfigs.isEmpty()) {
final Iterator<Map.Entry<String, ConfigModelResolver>> i = modelOnlyConfigs.entrySet().iterator();
if(modelOnlyConfigs.size() == 1) {
final Map.Entry<String, ConfigModelResolver> entry = i.next();
final Map<String, ConfigModelResolver> targetConfigs = namedModelConfigs.get(entry.getKey());
if (targetConfigs != null) {
for (Map.Entry<String, ConfigModelResolver> targetConfig : targetConfigs.entrySet()) {
targetConfig.getValue().merge(entry.getValue());
}
}
} else {
while (i.hasNext()) {
final Map.Entry<String, ConfigModelResolver> entry = i.next();
final Map<String, ConfigModelResolver> targetConfigs = namedModelConfigs.get(entry.getKey());
if (targetConfigs != null) {
for (Map.Entry<String, ConfigModelResolver> targetConfig : targetConfigs.entrySet()) {
targetConfig.getValue().merge(entry.getValue());
}
}
}
}
modelOnlyConfigs = Collections.emptyMap();
}
for(Map<String, ConfigModelResolver> configMap : namedModelConfigs.values()) {
for(Map.Entry<String, ConfigModelResolver> configEntry : configMap.entrySet()) {
configEntry.getValue().resolve(this);
}
}
}
private void processFpConfig(FeaturePackConfig fpConfig) throws ProvisioningException {
final FeaturePackRuntime.Builder parentFp = currentFp;
thisFpOrigin = loadFpBuilder(fpConfig.getGav());
currentFp = thisFpOrigin;
List<ConfigModelResolver> fpConfigResolvers = Collections.emptyList();
List<ConfigModel> fpConfigConfigs = Collections.emptyList();
List<List<ResolvedFeatureGroupConfig>> fpConfigPushedConfigs = Collections.emptyList();
for(ConfigModel config : fpConfig.getDefinedConfigs()) {
if(fpConfigStack.isFilteredOut(config.getId(), true)) {
continue;
}
configResolver = getConfigResolver(config.getId());
fpConfigResolvers = PmCollections.add(fpConfigResolvers, configResolver);
fpConfigConfigs = PmCollections.add(fpConfigConfigs, config);
final List<ResolvedFeatureGroupConfig> pushedFgConfigs = pushResolvedFgConfigs(config);
if(!pushedFgConfigs.isEmpty()) {
fpConfigPushedConfigs = PmCollections.add(fpConfigPushedConfigs, pushedFgConfigs);
}
}
List<ConfigModelResolver> specResolvers = Collections.emptyList();
List<ConfigModel> specConfigs = Collections.emptyList();
List<List<ResolvedFeatureGroupConfig>> specPushedConfigs = Collections.emptyList();
for(ConfigModel config : currentFp.spec.getDefinedConfigs()) {
if(fpConfigStack.isFilteredOut(config.getId(), false)) {
continue;
}
configResolver = getConfigResolver(config.getId());
specResolvers = PmCollections.add(specResolvers, configResolver);
specConfigs = PmCollections.add(specConfigs, config);
final List<ResolvedFeatureGroupConfig> pushedFgConfigs = pushResolvedFgConfigs(config);
if(!pushedFgConfigs.isEmpty()) {
specPushedConfigs = PmCollections.add(specPushedConfigs, pushedFgConfigs);
}
}
configResolver = null;
boolean extendedStackLevel = false;
if(currentFp.spec.hasFeaturePackDeps()) {
final Collection<FeaturePackConfig> fpDeps = currentFp.spec.getFeaturePackDeps();
for (FeaturePackConfig fpDep : fpDeps) {
extendedStackLevel |= fpConfigStack.push(fpDep, extendedStackLevel);
}
if (extendedStackLevel) {
while(fpConfigStack.hasNext()) {
processFpConfig(fpConfigStack.next());
}
}
}
boolean contributed = false;
if(!specPushedConfigs.isEmpty()) {
for(List<ResolvedFeatureGroupConfig> pushedConfigs : specPushedConfigs) {
contributed |= popResolvedFgConfigs(pushedConfigs);
}
}
for(int i = 0; i < specConfigs.size(); ++i) {
final ConfigModel config = specConfigs.get(i);
if(config.getId().isModelOnly()) {
recordModelOnlyConfig(fpConfig.getGav(), config);
continue;
}
contributed |= processConfig(specResolvers.get(i), config);
}
if(fpConfig.isInheritPackages()) {
for(String packageName : currentFp.spec.getDefaultPackageNames()) {
if(!fpConfigStack.isPackageExcluded(currentFp.gav, packageName)) {
resolvePackage(packageName);
contributed = true;
}
}
}
if (fpConfig.hasIncludedPackages()) {
for (PackageConfig pkgConfig : fpConfig.getIncludedPackages()) {
if (!fpConfigStack.isPackageExcluded(currentFp.gav, pkgConfig.getName())) {
resolvePackage(pkgConfig.getName());
contributed = true;
} else {
throw new ProvisioningDescriptionException(Errors.unsatisfiedPackageDependency(currentFp.gav, pkgConfig.getName()));
}
}
}
if(!fpConfigPushedConfigs.isEmpty()) {
for(List<ResolvedFeatureGroupConfig> pushedConfigs : fpConfigPushedConfigs) {
contributed |= popResolvedFgConfigs(pushedConfigs);
}
}
for(int i = 0; i < fpConfigConfigs.size(); ++i) {
final ConfigModel config = fpConfigConfigs.get(i);
if(config.getId().isModelOnly()) {
recordModelOnlyConfig(fpConfig.getGav(), config);
continue;
}
contributed |= processConfig(fpConfigResolvers.get(i), config);
}
if (extendedStackLevel) {
fpConfigStack.popLevel();
}
if(!currentFp.ordered && contributed) {
orderFpRtBuilder(currentFp);
}
this.thisFpOrigin = parentFp;
this.currentFp = parentFp;
}
private void recordModelOnlyConfig(ArtifactCoords.Gav gav, ConfigModel config) {
modelOnlyConfigSpecs = PmCollections.add(modelOnlyConfigSpecs, config);
modelOnlyGavs = PmCollections.add(modelOnlyGavs, gav);
fpConfigStack.recordStack();
}
private boolean processConfig(ConfigModelResolver configResolver, ConfigModel config) throws ProvisioningException {
if(this.configResolver != null) {
throw new IllegalStateException();
}
this.configResolver = configResolver;
configResolver.overwriteProps(config.getProperties());
try {
if(config.hasPackageDeps()) {
processPackageDeps(config);
}
processConfigItemContainer(config);
this.configResolver = null;
return true; // the config may be empty but it may tigger model-only merge into it
} catch (ProvisioningException e) {
throw new ProvisioningException(Errors.failedToResolveConfigSpec(config.getModel(), config.getName()), e);
}
}
private ConfigModelResolver getConfigResolver(ConfigId config) {
if(config.getModel() == null) {
if(config.getName() == null) {
final ConfigModelResolver modelBuilder = ConfigModelResolver.anonymous();
anonymousConfigs = PmCollections.add(anonymousConfigs, modelBuilder);
return modelBuilder;
}
ConfigModelResolver modelBuilder = nameOnlyConfigs.get(config.getName());
if(modelBuilder == null) {
modelBuilder = ConfigModelResolver.forName(config.getName());
nameOnlyConfigs = PmCollections.putLinked(nameOnlyConfigs, config.getName(), modelBuilder);
}
return modelBuilder;
}
if(config.getName() == null) {
ConfigModelResolver modelBuilder = modelOnlyConfigs.get(config.getModel());
if(modelBuilder == null) {
modelBuilder = ConfigModelResolver.forModel(config.getModel());
modelOnlyConfigs = PmCollections.putLinked(modelOnlyConfigs, config.getModel(), modelBuilder);
}
return modelBuilder;
}
Map<String, ConfigModelResolver> namedConfigs = namedModelConfigs.get(config.getModel());
if(namedConfigs == null) {
final ConfigModelResolver modelBuilder = ConfigModelResolver.forConfig(config.getModel(), config.getName());
namedConfigs = Collections.singletonMap(config.getName(), modelBuilder);
namedModelConfigs = PmCollections.putLinked(namedModelConfigs, config.getModel(), namedConfigs);
return modelBuilder;
}
ConfigModelResolver modelBuilder = namedConfigs.get(config.getName());
if (modelBuilder == null) {
if (namedConfigs.size() == 1) {
namedConfigs = new LinkedHashMap<>(namedConfigs);
if (namedModelConfigs.size() == 1) {
namedModelConfigs = new LinkedHashMap<>(namedModelConfigs);
}
namedModelConfigs.put(config.getModel(), namedConfigs);
}
modelBuilder = ConfigModelResolver.forConfig(config.getModel(), config.getName());
namedConfigs.put(config.getName(), modelBuilder);
}
return modelBuilder;
}
private boolean processFeatureGroup(FeatureGroupSupport includedFg, final FeatureGroupSupport originalFg)
throws ProvisioningException {
final List<ResolvedFeatureGroupConfig> pushedConfigs = pushResolvedFgConfigs(includedFg);
if(originalFg.hasPackageDeps()) {
processPackageDeps(originalFg);
}
if (pushedConfigs.isEmpty()) {
return false;
}
configResolver.startGroup();
boolean resolvedFeatures = processConfigItemContainer(originalFg);
resolvedFeatures |= popResolvedFgConfigs(pushedConfigs);
configResolver.endGroup();
return resolvedFeatures;
}
private List<ResolvedFeatureGroupConfig> pushResolvedFgConfigs(FeatureGroupSupport config)
throws ProvisioningException {
List<ResolvedFeatureGroupConfig> pushedConfigs = Collections.emptyList();
if(config.hasExternalFeatureGroups()) {
for(Map.Entry<String, FeatureGroup> entry : config.getExternalFeatureGroups().entrySet()) {
final FeaturePackRuntime.Builder originalFp = currentFp;
currentFp = getFpDep(entry.getKey());
final ResolvedFeatureGroupConfig resolvedFgConfig = resolveFeatureGroupConfig(entry.getValue());
if (configResolver.pushConfig(resolvedFgConfig)) {
pushedConfigs = PmCollections.add(pushedConfigs, resolvedFgConfig);
}
currentFp = originalFp;
}
}
if(currentFp == null) {
// if it's the provisioning config which is being processed it doesn't make sense to push it into the config resolver
return pushedConfigs;
}
final ResolvedFeatureGroupConfig resolvedFgConfig = resolveFeatureGroupConfig(config);
if(configResolver.pushConfig(resolvedFgConfig)) {
pushedConfigs = PmCollections.add(pushedConfigs, resolvedFgConfig);
}
return pushedConfigs;
}
private boolean popResolvedFgConfigs(final List<ResolvedFeatureGroupConfig> pushedConfigs)
throws ProvisioningException {
boolean resolvedFeatures = false;
final FeaturePackRuntime.Builder originalFp = currentFp;
for(ResolvedFeatureGroupConfig pushedFgConfig : pushedConfigs) {
currentFp = this.loadFpBuilder(pushedFgConfig.gav);
pushedFgConfig.configResolver.popConfig(currentFp.gav);
if (pushedFgConfig.includedFeatures.isEmpty()) {
continue;
}
for (Map.Entry<ResolvedFeatureId, FeatureConfig> feature : pushedFgConfig.includedFeatures.entrySet()) {
final FeatureConfig includedFc = feature.getValue();
if (includedFc != null && includedFc.hasParams()) {
final ResolvedFeatureId includedId = feature.getKey();
if (pushedFgConfig.configResolver.isFilteredOut(includedId.specId, includedId)) {
continue;
}
// make sure the included ID is in fact present on the feature group branch
if (!pushedFgConfig.configResolver.includes(includedId)) {
throw new ProvisioningException(Errors.featureNotInScope(includedId, pushedFgConfig.fg.getId().toString(), currentFp.gav));
}
resolvedFeatures |= resolveFeature(pushedFgConfig.configResolver, includedFc);
}
}
}
currentFp = originalFp;
return resolvedFeatures;
}
private ResolvedFeatureGroupConfig resolveFeatureGroupConfig(FeatureGroupSupport fg)
throws ProvisioningException {
final ResolvedFeatureGroupConfig resolvedFgc = new ResolvedFeatureGroupConfig(configResolver, fg, currentFp.gav);
resolvedFgc.inheritFeatures = fg.isInheritFeatures();
if(fg.hasExcludedSpecs()) {
resolvedFgc.excludedSpecs = resolveSpecIds(currentFp.gav, fg.getExcludedSpecs());
}
if(fg.hasIncludedSpecs()) {
resolvedFgc.includedSpecs = resolveSpecIds(currentFp.gav, fg.getIncludedSpecs());
}
if(fg.hasExcludedFeatures()) {
resolvedFgc.excludedFeatures = resolveExcludedIds(fg.getExcludedFeatures());
}
if(fg.hasIncludedFeatures()) {
resolvedFgc.includedFeatures = resolveIncludedIds(fg.getIncludedFeatures());
}
return resolvedFgc;
}
private Map<ResolvedFeatureId, FeatureConfig> resolveIncludedIds(Map<FeatureId, FeatureConfig> features) throws ProvisioningException {
if (features.size() == 1) {
final Map.Entry<FeatureId, FeatureConfig> included = features.entrySet().iterator().next();
final FeatureConfig fc = new FeatureConfig(included.getValue());
final ResolvedFeatureSpec resolvedSpec = currentFp.getFeatureSpec(fc.getSpecId().getName());
if (parentFeature != null) {
return Collections.singletonMap(resolvedSpec.resolveIdFromForeignKey(parentFeature.id, fc.getParentRef(), fc.getParams()), fc);
}
return Collections.singletonMap(resolvedSpec.resolveFeatureId(fc.getParams()), fc);
}
final Map<ResolvedFeatureId, FeatureConfig> tmp = new HashMap<>(features.size());
for (Map.Entry<FeatureId, FeatureConfig> included : features.entrySet()) {
final FeatureConfig fc = new FeatureConfig(included.getValue());
final ResolvedFeatureSpec resolvedSpec = currentFp.getFeatureSpec(fc.getSpecId().getName());
if (parentFeature != null) {
tmp.put(resolvedSpec.resolveIdFromForeignKey(parentFeature.id, fc.getParentRef(), fc.getParams()), fc);
} else {
tmp.put(resolvedSpec.resolveFeatureId(fc.getParams()), fc);
}
}
return tmp;
}
private Set<ResolvedFeatureId> resolveExcludedIds(Map<FeatureId, String> features) throws ProvisioningException {
if (features.size() == 1) {
final Map.Entry<FeatureId, String> excluded = features.entrySet().iterator().next();
final FeatureId excludedId = excluded.getKey();
final ResolvedFeatureSpec resolvedSpec = currentFp.getFeatureSpec(excludedId.getSpec().getName());
if(parentFeature != null) {
return Collections.singleton(resolvedSpec.resolveIdFromForeignKey(parentFeature.id, excluded.getValue(), excludedId.getParams()));
}
return Collections.singleton(resolvedSpec.resolveFeatureId(excludedId.getParams()));
}
final Set<ResolvedFeatureId> tmp = new HashSet<>(features.size());
for (Map.Entry<FeatureId, String> excluded : features.entrySet()) {
final FeatureId excludedId = excluded.getKey();
final ResolvedFeatureSpec resolvedSpec = currentFp.getFeatureSpec(excludedId.getSpec().getName());
if(parentFeature != null) {
tmp.add(resolvedSpec.resolveIdFromForeignKey(parentFeature.id, excluded.getValue(), excludedId.getParams()));
} else {
tmp.add(resolvedSpec.resolveFeatureId(excludedId.getParams()));
}
}
return tmp;
}
private static Set<ResolvedSpecId> resolveSpecIds(ArtifactCoords.Gav gav, Set<SpecId> specs) throws ProvisioningException {
if(specs.size() == 1) {
final SpecId specId = specs.iterator().next();
return Collections.singleton(new ResolvedSpecId(gav, specId.getName()));
}
final Set<ResolvedSpecId> tmp = new HashSet<>(specs.size());
for (SpecId specId : specs) {
tmp.add(new ResolvedSpecId(gav, specId.getName()));
}
return tmp;
}
private boolean processConfigItemContainer(ConfigItemContainer ciContainer) throws ProvisioningException {
boolean resolvedFeatures = false;
final FeaturePackRuntime.Builder prevFpOrigin = thisFpOrigin;
if(ciContainer.isResetFeaturePackOrigin()) {
thisFpOrigin = currentFp;
}
if(ciContainer.hasItems()) {
for(ConfigItem item : ciContainer.getItems()) {
final FeaturePackRuntime.Builder originalFp = currentFp;
currentFp = item.getFpDep() == null ? currentFp : getFpDep(item.getFpDep());
try {
if (item.isGroup()) {
final FeatureGroup nestedFg = (FeatureGroup) item;
resolvedFeatures |= processFeatureGroup(nestedFg, currentFp.getFeatureGroupSpec(nestedFg.getName()));
if(nestedFg.hasItems()) {
resolvedFeatures |= processConfigItemContainer(nestedFg);
}
} else {
resolvedFeatures |= resolveFeature(configResolver, (FeatureConfig) item);
}
} catch (ProvisioningException e) {
throw new ProvisioningException(item.isGroup() ?
Errors.failedToProcess(currentFp.gav, ((FeatureGroup)item).getName()) : Errors.failedToProcess(currentFp.gav, (FeatureConfig)item),
e);
}
currentFp = originalFp;
}
}
thisFpOrigin = prevFpOrigin;
return resolvedFeatures;
}
FeaturePackRuntime.Builder getFpDep(final String depName) throws ProvisioningException {
if(Constants.THIS.equals(depName)) {
if(thisFpOrigin == null) {
throw new ProvisioningException("Feature-pack reference 'this' cannot be used in the current context.");
}
return thisFpOrigin;
}
final ArtifactCoords.Gav depGav = currentFp == null ? config.getFeaturePackDep(depName).getGav() : currentFp.spec.getFeaturePackDep(depName).getGav();
return loadFpBuilder(depGav);
}
private boolean resolveFeature(ConfigModelResolver modelBuilder, FeatureConfig fc) throws ProvisioningException {
final ResolvedFeatureSpec spec = currentFp.getFeatureSpec(fc.getSpecId().getName());
final ResolvedFeatureId resolvedId = parentFeature == null ? spec.resolveFeatureId(fc.getParams()) : spec.resolveIdFromForeignKey(parentFeature.id, fc.getParentRef(), fc.getParams());
if(modelBuilder.isFilteredOut(spec.id, resolvedId)) {
return false;
}
final ResolvedFeature myParent = parentFeature;
parentFeature = resolveFeatureDepsAndRefs(modelBuilder, spec, resolvedId,
spec.resolveNonIdParams(parentFeature == null ? null : parentFeature.id, fc.getParentRef(), fc.getParams()), fc.getFeatureDeps());
if(fc.hasUnsetParams()) {
parentFeature.unsetAllParams(fc.getUnsetParams(), true);
}
if(fc.hasResetParams()) {
parentFeature.resetAllParams(fc.getResetParams());
}
processConfigItemContainer(fc);
parentFeature = myParent;
return true;
}
private ResolvedFeature resolveFeatureDepsAndRefs(ConfigModelResolver modelBuilder,
final ResolvedFeatureSpec spec, final ResolvedFeatureId resolvedId, Map<String, Object> resolvedParams,
Collection<FeatureDependencySpec> featureDeps)
throws ProvisioningException {
if(spec.xmlSpec.hasPackageDeps()) {
processPackageDeps(spec.xmlSpec);
}
final ResolvedFeature resolvedFeature = modelBuilder.includeFeature(resolvedId, spec, resolvedParams, resolveFeatureDeps(modelBuilder, featureDeps, spec));
if(spec.xmlSpec.hasFeatureRefs()) {
final ResolvedFeature myParent = parentFeature;
parentFeature = resolvedFeature;
for(FeatureReferenceSpec refSpec : spec.xmlSpec.getFeatureRefs()) {
if(!refSpec.isInclude()) {
continue;
}
final FeaturePackRuntime.Builder originalFp = currentFp;
currentFp = refSpec.getDependency() == null ? currentFp : getFpDep(refSpec.getDependency());
final ResolvedFeatureSpec refResolvedSpec = currentFp.getFeatureSpec(refSpec.getFeature().getName());
final List<ResolvedFeatureId> refIds = spec.resolveRefId(parentFeature, refSpec, refResolvedSpec);
if(!refIds.isEmpty()) {
for (ResolvedFeatureId refId : refIds) {
if (modelBuilder.includes(refId) || modelBuilder.isFilteredOut(refId.specId, refId)) {
continue;
}
resolveFeatureDepsAndRefs(modelBuilder, refResolvedSpec, refId, Collections.emptyMap(), Collections.emptyList());
}
}
currentFp = originalFp;
}
parentFeature = myParent;
}
return resolvedFeature;
}
private Map<ResolvedFeatureId, FeatureDependencySpec> resolveFeatureDeps(ConfigModelResolver modelBuilder,
Collection<FeatureDependencySpec> featureDeps, final ResolvedFeatureSpec spec)
throws ProvisioningException {
Map<ResolvedFeatureId, FeatureDependencySpec> resolvedDeps = spec.resolveFeatureDeps(this, featureDeps);
if(!resolvedDeps.isEmpty()) {
for(Map.Entry<ResolvedFeatureId, FeatureDependencySpec> dep : resolvedDeps.entrySet()) {
if(!dep.getValue().isInclude()) {
continue;
}
final ResolvedFeatureId depId = dep.getKey();
if(modelBuilder.includes(depId) || modelBuilder.isFilteredOut(depId.specId, depId)) {
continue;
}
final FeatureDependencySpec depSpec = dep.getValue();
final FeaturePackRuntime.Builder originalFp = currentFp;
currentFp = depSpec.getDependency() == null ? currentFp : getFpDep(depSpec.getDependency());
resolveFeatureDepsAndRefs(modelBuilder, currentFp.getFeatureSpec(depId.getSpecId().getName()), depId, Collections.emptyMap(), Collections.emptyList());
currentFp = originalFp;
}
}
return resolvedDeps;
}
FeaturePackRuntime.Builder getFpBuilder(ArtifactCoords.Gav gav) throws ProvisioningDescriptionException {
final FeaturePackRuntime.Builder fpRtBuilder = fpRtBuilders.get(gav.toGa());
if(fpRtBuilder == null) {
throw new ProvisioningDescriptionException(Errors.unknownFeaturePack(gav));
}
return fpRtBuilder;
}
private FeaturePackRuntime.Builder loadFpBuilder(ArtifactCoords.Gav gav) throws ProvisioningException {
FeaturePackRuntime.Builder fp = fpRtBuilders.get(gav.toGa());
if(fp == null) {
final Path fpDir = LayoutUtils.getFeaturePackDir(layoutDir, gav, false);
mkdirs(fpDir);
final Path artifactPath = artifactResolver.resolve(gav.toArtifactCoords());
try {
ZipUtils.unzip(artifactPath, fpDir);
} catch (IOException e) {
throw new ProvisioningException("Failed to unzip " + artifactPath + " to " + layoutDir, e);
}
final Path fpXml = fpDir.resolve(Constants.FEATURE_PACK_XML);
if(!Files.exists(fpXml)) {
throw new ProvisioningDescriptionException(Errors.pathDoesNotExist(fpXml));
}
try(BufferedReader reader = Files.newBufferedReader(fpXml)) {
fp = FeaturePackRuntime.builder(gav, FeaturePackXmlParser.getInstance().parse(reader), fpDir);
} catch (IOException | XMLStreamException e) {
throw new ProvisioningException(Errors.parseXml(fpXml), e);
}
fpRtBuilders.put(gav.toGa(), fp);
} else if(!fp.gav.equals(gav)) {
throw new ProvisioningException(Errors.featurePackVersionConflict(fp.gav, gav));
}
return fp;
}
private void resolvePackage(final String pkgName)
throws ProvisioningException {
final PackageRuntime.Builder pkgRt = currentFp.pkgBuilders.get(pkgName);
if(pkgRt != null) {
return;
}
final PackageRuntime.Builder pkg = currentFp.newPackage(pkgName, LayoutUtils.getPackageDir(currentFp.dir, pkgName, false));
if(!Files.exists(pkg.dir)) {
throw new ProvisioningDescriptionException(Errors.packageNotFound(currentFp.gav, pkgName));
}
final Path pkgXml = pkg.dir.resolve(Constants.PACKAGE_XML);
if(!Files.exists(pkgXml)) {
throw new ProvisioningDescriptionException(Errors.pathDoesNotExist(pkgXml));
}
try(BufferedReader reader = Files.newBufferedReader(pkgXml)) {
pkg.spec = PackageXmlParser.getInstance().parse(reader);
} catch (IOException | XMLStreamException e) {
throw new ProvisioningException(Errors.parseXml(pkgXml), e);
}
if(pkg.spec.hasPackageDeps()) {
try {
processPackageDeps(pkg.spec);
} catch(ProvisioningException e) {
throw new ProvisioningDescriptionException(Errors.resolvePackage(currentFp.gav, pkg.spec.getName()), e);
}
}
currentFp.addPackage(pkgName);
}
private void processPackageDeps(final PackageDepsSpec pkgDeps)
throws ProvisioningException {
if (pkgDeps.hasLocalPackageDeps()) {
for (PackageDependencySpec dep : pkgDeps.getLocalPackageDeps()) {
if(fpConfigStack.isPackageExcluded(currentFp.gav, dep.getName())) {
if(!dep.isOptional()) {
throw new ProvisioningDescriptionException(Errors.unsatisfiedPackageDependency(currentFp.gav, dep.getName()));
}
continue;
}
try {
resolvePackage(dep.getName());
} catch(ProvisioningDescriptionException e) {
if(dep.isOptional()) {
continue;
} else {
throw e;
}
}
}
}
if(!pkgDeps.hasExternalPackageDeps()) {
return;
}
for (String depName : pkgDeps.getExternalPackageSources()) {
final FeaturePackRuntime.Builder originalFp = currentFp;
currentFp = this.getFpDep(depName);
boolean resolvedPackages = false;
for (PackageDependencySpec pkgDep : pkgDeps.getExternalPackageDeps(depName)) {
if (fpConfigStack.isPackageExcluded(currentFp.gav, pkgDep.getName())) {
if (!pkgDep.isOptional()) {
final ArtifactCoords.Gav originGav = currentFp.gav;
currentFp = originalFp;
throw new ProvisioningDescriptionException(Errors.unsatisfiedPackageDependency(originGav, pkgDep.getName()));
}
continue;
}
try {
resolvePackage(pkgDep.getName());
resolvedPackages = true;
} catch (ProvisioningDescriptionException e) {
if (pkgDep.isOptional()) {
continue;
} else {
currentFp = originalFp;
throw e;
}
}
}
if (!currentFp.ordered && resolvedPackages) {
orderFpRtBuilder(currentFp);
}
currentFp = originalFp;
}
}
private void orderFpRtBuilder(final FeaturePackRuntime.Builder fpRtBuilder) {
this.fpRtBuildersOrdered.add(fpRtBuilder);
fpRtBuilder.ordered = true;
}
private void copyResources(FeaturePackRuntime.Builder fpRtBuilder) throws ProvisioningException {
// resources should be copied last overriding the dependency resources
final Path fpResources = fpRtBuilder.dir.resolve(Constants.RESOURCES);
if(Files.exists(fpResources)) {
try {
IoUtils.copy(fpResources, workDir.resolve(Constants.RESOURCES));
} catch (IOException e) {
throw new ProvisioningException(Errors.copyFile(fpResources, workDir.resolve(Constants.RESOURCES)), e);
}
}
final Path fpPlugins = fpRtBuilder.dir.resolve(Constants.PLUGINS);
if(Files.exists(fpPlugins)) {
if(pluginsDir == null) {
pluginsDir = workDir.resolve(Constants.PLUGINS);
}
try {
IoUtils.copy(fpPlugins, pluginsDir);
} catch (IOException e) {
throw new ProvisioningException(Errors.copyFile(fpPlugins, workDir.resolve(Constants.PLUGINS)), e);
}
}
}
public ProvisioningRuntimeBuilder addParameter(String name, String param) {
rtParams = PmCollections.put(rtParams, name, param);
return this;
}
public ProvisioningRuntimeBuilder addAllParameters(Map<String, String> params) {
for(Map.Entry<String, String> param : params.entrySet()) {
addParameter(param.getKey(), param.getValue());
}
return this;
}
}
| minor change
| feature-pack-api/src/main/java/org/jboss/provisioning/runtime/ProvisioningRuntimeBuilder.java | minor change |
|
Java | apache-2.0 | 33649e55dcb3d76aa4b6d7339b5eaed13cbe6d7c | 0 | sonar-perl/sonar-perl,sonar-perl/sonar-perl,otrosien/sonar-perl,otrosien/sonar-perl,sonar-perl/sonar-perl,otrosien/sonar-perl,otrosien/sonar-perl,sonar-perl/sonar-perl,otrosien/sonar-perl,sonar-perl/sonar-perl | package com.epages.sonar.perl.rules;
import static java.lang.String.format;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.sonar.api.batch.Sensor;
import org.sonar.api.batch.SensorContext;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.component.ResourcePerspectives;
import org.sonar.api.config.Settings;
import org.sonar.api.issue.Issuable;
import org.sonar.api.issue.Issue;
import org.sonar.api.resources.Project;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleFinder;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import com.google.common.base.Strings;
public class PerlCriticIssuesLoaderSensor implements Sensor {
static final Logger log = Loggers.get(PerlCriticIssuesLoaderSensor.class);
protected final Settings settings;
protected final FileSystem fileSystem;
protected final RuleFinder ruleFinder;
protected final ResourcePerspectives perspectives;
/**
* Use of IoC to get Settings, FileSystem, RuleFinder and
* ResourcePerspectives
*/
public PerlCriticIssuesLoaderSensor(final Settings settings, final FileSystem fileSystem,
final RuleFinder ruleFinder, final ResourcePerspectives perspectives) {
this.settings = settings;
this.fileSystem = fileSystem;
this.ruleFinder = ruleFinder;
this.perspectives = perspectives;
}
@Override
public boolean shouldExecuteOnProject(final Project project) {
return !Strings.isNullOrEmpty(getReportPath());
}
protected String reportPathKey() {
return PerlCritic.PERLCRITIC_REPORT_PATH_KEY;
}
protected String getReportPath() {
String reportPath = settings.getString(reportPathKey());
log.info("Configured report path: {}", reportPath);
if (!Strings.isNullOrEmpty(reportPath)) {
return reportPath;
} else {
return null;
}
}
@Override
public void analyse(final Project project, final SensorContext context) {
String reportPath = getReportPath();
File analysisResultsFile = new File(reportPath);
try {
parseAndSaveResults(analysisResultsFile);
} catch (IOException e) {
throw new IllegalStateException("Unable to parse the provided PerlCritic report file", e);
}
}
protected void parseAndSaveResults(final File file) throws IOException {
log.info("Parsing 'PerlCritic' Analysis Results");
PerlCriticAnalysisResultsParser parser = new PerlCriticAnalysisResultsParser();
List<PerlCriticViolation> parseResult = parser.parse(file);
log.info("Found {} PerlCritic violations.", parseResult.size());
for (PerlCriticViolation error : parseResult) {
getResourceAndSaveIssue(error);
}
}
private void getResourceAndSaveIssue(PerlCriticViolation violation) {
log.debug(violation.toString());
InputFile inputFile = fileSystem
.inputFile(fileSystem.predicates().and(fileSystem.predicates().hasRelativePath(violation.getFilePath()),
fileSystem.predicates().hasType(InputFile.Type.MAIN)));
if (inputFile != null) {
saveIssue(inputFile, violation.getLine(), violation.getType(), violation.getDescription());
} else {
log.error("Not able to find an InputFile with path '{}'", violation.getFilePath());
}
}
private boolean saveIssue(InputFile inputFile, int line, String externalRuleKey, String message) {
RuleKey rule = RuleKey.of(PerlCriticRulesDefinition.getRepositoryKeyForLanguage(inputFile.language()),
externalRuleKey);
log.debug("Now saving an issue of type {}", rule);
Issuable issuable = perspectives.as(Issuable.class, inputFile);
boolean result = false;
if (issuable != null) {
log.debug("Issuable is not null: {}", issuable.toString());
Issuable.IssueBuilder issueBuilder = issuable.newIssueBuilder().ruleKey(rule).message(message);
if (line > 0) {
log.debug("Line is > 0");
issueBuilder = issueBuilder.line(line);
}
Issue issue = issueBuilder.build();
log.debug("Issue == null? " + (issue == null));
try {
result = issuable.addIssue(issue);
log.debug("after addIssue: result={}", result);
} catch (org.sonar.api.utils.MessageException me) {
log.error(format("Can't add issue on file %s at line %d.", inputFile.absolutePath(), line), me);
}
} else {
log.debug("Can't find an Issuable corresponding to InputFile:" + inputFile.absolutePath());
}
return result;
}
@Override
public String toString() {
return getClass().getSimpleName();
}
}
| sonar-perl-plugin/src/main/java/com/epages/sonar/perl/rules/PerlCriticIssuesLoaderSensor.java | package com.epages.sonar.perl.rules;
import static java.lang.String.format;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.stream.StreamSupport;
import javax.xml.stream.XMLStreamException;
import org.sonar.api.batch.Sensor;
import org.sonar.api.batch.SensorContext;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.component.ResourcePerspectives;
import org.sonar.api.config.Settings;
import org.sonar.api.issue.Issuable;
import org.sonar.api.issue.Issue;
import org.sonar.api.resources.Project;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleFinder;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import com.google.common.base.Strings;
public class PerlCriticIssuesLoaderSensor implements Sensor {
static final Logger log = Loggers.get(PerlCriticIssuesLoaderSensor.class);
protected final Settings settings;
protected final FileSystem fileSystem;
protected final RuleFinder ruleFinder;
protected final ResourcePerspectives perspectives;
/**
* Use of IoC to get Settings, FileSystem, RuleFinder and
* ResourcePerspectives
*/
public PerlCriticIssuesLoaderSensor(final Settings settings, final FileSystem fileSystem,
final RuleFinder ruleFinder, final ResourcePerspectives perspectives) {
this.settings = settings;
this.fileSystem = fileSystem;
this.ruleFinder = ruleFinder;
this.perspectives = perspectives;
}
@Override
public boolean shouldExecuteOnProject(final Project project) {
return !Strings.isNullOrEmpty(getReportPath());
}
protected String reportPathKey() {
return PerlCritic.PERLCRITIC_REPORT_PATH_KEY;
}
protected String getReportPath() {
String reportPath = settings.getString(reportPathKey());
log.info("Configured report path: {}", reportPath);
if (!Strings.isNullOrEmpty(reportPath)) {
return reportPath;
} else {
return null;
}
}
@Override
public void analyse(final Project project, final SensorContext context) {
String reportPath = getReportPath();
File analysisResultsFile = new File(reportPath);
try {
parseAndSaveResults(analysisResultsFile);
} catch (IOException e) {
throw new IllegalStateException("Unable to parse the provided PerlCritic report file", e);
}
}
protected void parseAndSaveResults(final File file) throws IOException {
log.info("Parsing 'PerlCritic' Analysis Results");
PerlCriticAnalysisResultsParser parser = new PerlCriticAnalysisResultsParser();
List<PerlCriticViolation> parseResult = parser.parse(file);
log.info("Found {} PerlCritic violations.", parseResult.size());
for (PerlCriticViolation error : parseResult) {
getResourceAndSaveIssue(error);
}
}
private void getResourceAndSaveIssue(PerlCriticViolation violation) {
log.debug(violation.toString());
InputFile inputFile = fileSystem
.inputFile(fileSystem.predicates().and(fileSystem.predicates().hasRelativePath(violation.getFilePath()),
fileSystem.predicates().hasType(InputFile.Type.MAIN)));
if (inputFile != null) {
saveIssue(inputFile, violation.getLine(), violation.getType(), violation.getDescription());
} else {
log.error("Not able to find an InputFile with path '{}'", violation.getFilePath());
}
}
private boolean saveIssue(InputFile inputFile, int line, String externalRuleKey, String message) {
RuleKey rule = RuleKey.of(PerlCriticRulesDefinition.getRepositoryKeyForLanguage(inputFile.language()),
externalRuleKey);
log.debug("Now saving an issue of type {}", rule);
Issuable issuable = perspectives.as(Issuable.class, inputFile);
boolean result = false;
if (issuable != null) {
log.debug("Issuable is not null: {}", issuable.toString());
Issuable.IssueBuilder issueBuilder = issuable.newIssueBuilder().ruleKey(rule).message(message);
if (line > 0) {
log.debug("Line is > 0");
issueBuilder = issueBuilder.line(line);
}
Issue issue = issueBuilder.build();
log.debug("Issue == null? " + (issue == null));
try {
result = issuable.addIssue(issue);
log.debug("after addIssue: result={}", result);
} catch (org.sonar.api.utils.MessageException me) {
log.error(format("Can't add issue on file %s at line %d.", inputFile.absolutePath(), line), me);
}
} else {
log.debug("Can't find an Issuable corresponding to InputFile:" + inputFile.absolutePath());
}
return result;
}
@Override
public String toString() {
return getClass().getSimpleName();
}
}
| imports cleanup | sonar-perl-plugin/src/main/java/com/epages/sonar/perl/rules/PerlCriticIssuesLoaderSensor.java | imports cleanup |
|
Java | apache-2.0 | 5cddd2a485a4f90c40333d0488c91fc2663b1325 | 0 | yona-projects/yona,yona-projects/yona,yona-projects/yona,doortts/fork-yobi,doortts/fork-yobi,doortts/fork-yobi,doortts/fork-yobi,yona-projects/yona | /**
* Yona, 21st Century Project Hosting SW
* <p>
* Copyright Yona & Yobi Authors & NAVER Corp. & NAVER LABS Corp.
* https://yona.io
**/
package controllers;
import com.fasterxml.jackson.databind.JsonNode;
import controllers.annotation.AnonymousCheck;
import models.*;
import models.enumeration.Direction;
import models.enumeration.Operation;
import models.resource.Resource;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import play.data.Form;
import play.db.ebean.Model;
import play.i18n.Messages;
import play.mvc.Call;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Result;
import utils.*;
import java.util.LinkedList;
import java.util.Map;
import static utils.JodaDateUtil.getDateString;
import static utils.diff_match_patch.Diff;
@AnonymousCheck
public class AbstractPostingApp extends Controller {
public static final int ITEMS_PER_PAGE = 15;
private static final short Diff_EditCost = 16;
public static class SearchCondition {
public String orderBy;
public String orderDir;
public String filter;
public int pageNum;
public SearchCondition() {
this.orderDir = Direction.DESC.direction();
this.orderBy = "id";
this.filter = "";
this.pageNum = 1;
}
}
public static Comment saveComment(final Comment comment, Runnable containerUpdater) {
containerUpdater.run(); // this updates comment.issue or comment.posting;
if(comment.id != null && AccessControl.isAllowed(UserApp.currentUser(), comment.asResource(), Operation.UPDATE)) {
comment.update();
} else {
comment.setAuthor(UserApp.currentUser());
comment.save();
}
// Attach all of the files in the current user's temporary storage.
attachUploadFilesToPost(comment.asResource());
return comment;
}
protected static Result delete(Model target, Resource resource, Call redirectTo) {
if (!AccessControl.isAllowed(UserApp.currentUser(), resource, Operation.DELETE)) {
return forbidden(ErrorViews.Forbidden.render("error.forbidden", resource.getProject()));
}
target.delete();
if(HttpUtil.isRequestedWithXHR(request())){
response().setHeader("Location", redirectTo.url());
return status(204);
}
return redirect(redirectTo);
}
protected static Result editPosting(AbstractPosting original, AbstractPosting posting, Form<? extends AbstractPosting> postingForm, Call redirectTo, Runnable preUpdateHook) {
if (postingForm.hasErrors()) {
return badRequest(ErrorViews.BadRequest.render("error.validation", original.project));
}
if (!AccessControl.isAllowed(UserApp.currentUser(), original.asResource(), Operation.UPDATE)) {
return forbidden(ErrorViews.Forbidden.render("error.forbidden", original.project));
}
if (posting.body == null) {
return status(REQUEST_ENTITY_TOO_LARGE,
ErrorViews.RequestTextEntityTooLarge.render());
}
posting.id = original.id;
posting.createdDate = original.createdDate;
posting.updatedDate = JodaDateUtil.now();
posting.authorId = original.authorId;
posting.authorLoginId = original.authorLoginId;
posting.authorName = original.authorName;
posting.project = original.project;
posting.setNumber(original.getNumber());
if (!StringUtils.defaultString(original.body, "").equals(StringUtils.defaultString(posting.body, ""))) {
posting.history = addToHistory(original, posting) + StringUtils.defaultString(original.history, "");
}
preUpdateHook.run();
try {
posting.checkLabels();
} catch (IssueLabel.IssueLabelException e) {
return badRequest(e.getMessage());
}
posting.update();
posting.updateProperties();
TitleHead.saveTitleHeadKeyword(posting.project, posting.title);
TitleHead.deleteTitleHeadKeyword(original.project, original.title);
// Attach the files in the current user's temporary storage.
attachUploadFilesToPost(original.asResource());
return redirect(redirectTo);
}
private static String addToHistory(AbstractPosting original, AbstractPosting posting) {
diff_match_patch dmp = new diff_match_patch();
dmp.Diff_EditCost = Diff_EditCost;
LinkedList<diff_match_patch.Diff> diffs = dmp.diff_main(original.body, posting.body);
dmp.diff_cleanupEfficiency(diffs);
return (getHistoryMadeBy(posting, diffs) + getDiffText(original.body, posting.body) + "\n").replaceAll("\n", "</br>\n");
}
private static String getHistoryMadeBy(AbstractPosting posting, LinkedList<diff_match_patch.Diff> diffs) {
int insertions = 0;
int deletions = 0;
for (Diff diff : diffs) {
switch (diff.operation) {
case DELETE:
deletions++;
break;
case INSERT:
insertions++;
break;
default:
break;
}
}
StringBuilder sb = new StringBuilder();
sb.append("<div class='history-made-by'>").append(UserApp.currentUser().name)
.append("(").append(UserApp.currentUser().loginId).append(") ");
if (insertions > 0) {
sb.append("<span class='added'> ")
.append(" + ")
.append(insertions).append(" </span>");
}
if (deletions > 0) {
sb.append("<span class='deleted'> ")
.append(" - ")
.append(deletions).append(" </span>");
}
sb.append(" at ").append(getDateString(posting.updatedDate, "yyyy-MM-dd h:mm:ss a")).append("</div><hr/>\n");
return sb.toString();
}
private static String getDiffText(String oldValue, String newValue) {
final int EQUAL_TEXT_ELLIPSIS_SIZE = 100;
diff_match_patch dmp = new diff_match_patch();
dmp.Diff_EditCost = Diff_EditCost;
StringBuilder sb = new StringBuilder();
if (oldValue != null) {
LinkedList<diff_match_patch.Diff> diffs = dmp.diff_main(oldValue, newValue);
dmp.diff_cleanupEfficiency(diffs);
for(Diff diff: diffs){
switch (diff.operation) {
case DELETE:
sb.append("<span class='diff-deleted'>");
sb.append(StringEscapeUtils.escapeHtml4(diff.text));
sb.append("</span>");
break;
case EQUAL:
int textLength = diff.text.length();
if(textLength > EQUAL_TEXT_ELLIPSIS_SIZE) {
if(!diff.text.substring(0, 50).equals(oldValue.substring(0, 50))) {
sb.append(StringEscapeUtils.escapeHtml4(diff.text.substring(0, 50)));
}
sb.append("<span class='diff-ellipsis'>...\n")
.append("......\n")
.append("......\n")
.append("...</span>");
if(!diff.text.substring(textLength - 50).equals(oldValue.substring(oldValue.length() - 50))) {
sb.append(StringEscapeUtils.escapeHtml4(diff.text.substring(textLength - 50)));
}
} else {
sb.append(StringEscapeUtils.escapeHtml4(diff.text));
}
break;
case INSERT:
sb.append("<span class='diff-added'>");
sb.append(StringEscapeUtils.escapeHtml4(diff.text));
sb.append("</span>");
break;
default:
break;
}
}
}
return sb.toString().replaceAll("\n", " <br/>\n");
}
public static void attachUploadFilesToPost(Resource resource) {
final String[] temporaryUploadFiles = getTemporaryFileListFromHiddenForm();
if(isTemporaryFilesExist(temporaryUploadFiles)){
int attachedFileCount = Attachment.moveOnlySelected(UserApp.currentUser().asResource(), resource,
temporaryUploadFiles);
if( attachedFileCount != temporaryUploadFiles.length){
flash(Constants.TITLE, Messages.get("post.popup.fileAttach.hasMissing", temporaryUploadFiles.length - attachedFileCount));
flash(Constants.DESCRIPTION, Messages.get("post.popup.fileAttach.hasMissing.description", getTemporaryFilesServerKeepUpTimeOfMinuntes()));
}
}
}
public static void attachUploadFilesToPost(JsonNode files, Resource resource) {
if(files != null && files.isArray() && files.size() > 0){
String [] fileIds = new String[files.size()];
int idx = 0;
for (JsonNode fileNo : files) {
fileIds[idx] = fileNo.asText();
idx++;
}
int attachedFileCount = Attachment.moveOnlySelected(UserApp.currentUser().asResource(), resource,
fileIds);
if( attachedFileCount != files.size()){
flash(Constants.TITLE, Messages.get("post.popup.fileAttach.hasMissing", files.size() - attachedFileCount));
flash(Constants.DESCRIPTION, Messages.get("post.popup.fileAttach.hasMissing.description", getTemporaryFilesServerKeepUpTimeOfMinuntes()));
}
}
}
private static long getTemporaryFilesServerKeepUpTimeOfMinuntes() {
return AttachmentApp.TEMPORARYFILES_KEEPUP_TIME_MILLIS/(60*1000l);
}
public static String[] getTemporaryFileListFromHiddenForm() {
Http.MultipartFormData body = request().body().asMultipartFormData();
if (body == null) {
return new String[] {};
}
String [] temporaryUploadFiles = body.asFormUrlEncoded().get(AttachmentApp.TAG_NAME_FOR_TEMPORARY_UPLOAD_FILES);
if (temporaryUploadFiles == null) {
return new String[] {};
}
final String CSV_DELIMITER = ",";
return temporaryUploadFiles[0].split(CSV_DELIMITER);
}
private static boolean isTemporaryFilesExist(String[] files) {
if (ArrayUtils.getLength(files) == 0) {
return false;
}
return StringUtils.isNotBlank(files[0]);
}
protected static boolean isSelectedToSendNotificationMail() {
Map<String,String[]> data;
if (isMultiPartFormData()) {
data = request().body().asMultipartFormData().asFormUrlEncoded();
} else {
data = request().body().asFormUrlEncoded();
}
return "yes".equalsIgnoreCase(HttpUtil.getFirstValueFromQuery(data, "notificationMail"));
}
private static boolean isMultiPartFormData() {
return request().body().asMultipartFormData() != null;
}
}
| app/controllers/AbstractPostingApp.java | /**
* Yona, 21st Century Project Hosting SW
* <p>
* Copyright Yona & Yobi Authors & NAVER Corp. & NAVER LABS Corp.
* https://yona.io
**/
package controllers;
import com.fasterxml.jackson.databind.JsonNode;
import controllers.annotation.AnonymousCheck;
import models.*;
import models.enumeration.Direction;
import models.enumeration.Operation;
import models.resource.Resource;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import play.data.Form;
import play.db.ebean.Model;
import play.i18n.Messages;
import play.mvc.Call;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Result;
import utils.*;
import java.util.LinkedList;
import java.util.Map;
import static utils.JodaDateUtil.getDateString;
import static utils.diff_match_patch.Diff;
@AnonymousCheck
public class AbstractPostingApp extends Controller {
public static final int ITEMS_PER_PAGE = 15;
public static class SearchCondition {
public String orderBy;
public String orderDir;
public String filter;
public int pageNum;
public SearchCondition() {
this.orderDir = Direction.DESC.direction();
this.orderBy = "id";
this.filter = "";
this.pageNum = 1;
}
}
public static Comment saveComment(final Comment comment, Runnable containerUpdater) {
containerUpdater.run(); // this updates comment.issue or comment.posting;
if(comment.id != null && AccessControl.isAllowed(UserApp.currentUser(), comment.asResource(), Operation.UPDATE)) {
comment.update();
} else {
comment.setAuthor(UserApp.currentUser());
comment.save();
}
// Attach all of the files in the current user's temporary storage.
attachUploadFilesToPost(comment.asResource());
return comment;
}
protected static Result delete(Model target, Resource resource, Call redirectTo) {
if (!AccessControl.isAllowed(UserApp.currentUser(), resource, Operation.DELETE)) {
return forbidden(ErrorViews.Forbidden.render("error.forbidden", resource.getProject()));
}
target.delete();
if(HttpUtil.isRequestedWithXHR(request())){
response().setHeader("Location", redirectTo.url());
return status(204);
}
return redirect(redirectTo);
}
protected static Result editPosting(AbstractPosting original, AbstractPosting posting, Form<? extends AbstractPosting> postingForm, Call redirectTo, Runnable preUpdateHook) {
if (postingForm.hasErrors()) {
return badRequest(ErrorViews.BadRequest.render("error.validation", original.project));
}
if (!AccessControl.isAllowed(UserApp.currentUser(), original.asResource(), Operation.UPDATE)) {
return forbidden(ErrorViews.Forbidden.render("error.forbidden", original.project));
}
if (posting.body == null) {
return status(REQUEST_ENTITY_TOO_LARGE,
ErrorViews.RequestTextEntityTooLarge.render());
}
posting.id = original.id;
posting.createdDate = original.createdDate;
posting.updatedDate = JodaDateUtil.now();
posting.authorId = original.authorId;
posting.authorLoginId = original.authorLoginId;
posting.authorName = original.authorName;
posting.project = original.project;
posting.setNumber(original.getNumber());
if (!StringUtils.defaultString(original.body, "").equals(StringUtils.defaultString(posting.body, ""))) {
posting.history = addToHistory(original, posting) + StringUtils.defaultString(original.history, "");
}
preUpdateHook.run();
try {
posting.checkLabels();
} catch (IssueLabel.IssueLabelException e) {
return badRequest(e.getMessage());
}
posting.update();
posting.updateProperties();
TitleHead.saveTitleHeadKeyword(posting.project, posting.title);
TitleHead.deleteTitleHeadKeyword(original.project, original.title);
// Attach the files in the current user's temporary storage.
attachUploadFilesToPost(original.asResource());
return redirect(redirectTo);
}
private static String addToHistory(AbstractPosting original, AbstractPosting posting) {
diff_match_patch dmp = new diff_match_patch();
dmp.Diff_EditCost = 8;
LinkedList<diff_match_patch.Diff> diffs = dmp.diff_main(original.body, posting.body);
dmp.diff_cleanupEfficiency(diffs);
return (getHistoryMadeBy(posting, diffs) + getDiffText(original.body, posting.body) + "\n").replaceAll("\n", "</br>\n");
}
private static String getHistoryMadeBy(AbstractPosting posting, LinkedList<diff_match_patch.Diff> diffs) {
int insertions = 0;
int deletions = 0;
for (Diff diff : diffs) {
switch (diff.operation) {
case DELETE:
deletions++;
break;
case INSERT:
insertions++;
break;
default:
break;
}
}
StringBuilder sb = new StringBuilder();
sb.append("<div class='history-made-by'>").append(UserApp.currentUser().name)
.append("(").append(UserApp.currentUser().loginId).append(") ");
if (insertions > 0) {
sb.append("<span class='added'> ")
.append(" + ")
.append(insertions).append(" </span>");
}
if (deletions > 0) {
sb.append("<span class='deleted'> ")
.append(" - ")
.append(deletions).append(" </span>");
}
sb.append(" at ").append(getDateString(posting.updatedDate, "yyyy-MM-dd h:mm:ss a")).append("</div><hr/>\n");
return sb.toString();
}
private static String getDiffText(String oldValue, String newValue) {
final int EQUAL_TEXT_ELLIPSIS_SIZE = 100;
diff_match_patch dmp = new diff_match_patch();
dmp.Diff_EditCost = 8;
StringBuilder sb = new StringBuilder();
if (oldValue != null) {
LinkedList<diff_match_patch.Diff> diffs = dmp.diff_main(oldValue, newValue);
dmp.diff_cleanupEfficiency(diffs);
for(Diff diff: diffs){
switch (diff.operation) {
case DELETE:
sb.append("<span class='diff-deleted'>");
sb.append(StringEscapeUtils.escapeHtml4(diff.text));
sb.append("</span>");
break;
case EQUAL:
int textLength = diff.text.length();
if(textLength > EQUAL_TEXT_ELLIPSIS_SIZE) {
if(!diff.text.substring(0, 50).equals(oldValue.substring(0, 50))) {
sb.append(StringEscapeUtils.escapeHtml4(diff.text.substring(0, 50)));
}
sb.append("<span class='diff-ellipsis'>...\n")
.append("......\n")
.append("......\n")
.append("...</span>");
if(!diff.text.substring(textLength - 50).equals(oldValue.substring(oldValue.length() - 50))) {
sb.append(StringEscapeUtils.escapeHtml4(diff.text.substring(textLength - 50)));
}
} else {
sb.append(StringEscapeUtils.escapeHtml4(diff.text));
}
break;
case INSERT:
sb.append("<span class='diff-added'>");
sb.append(StringEscapeUtils.escapeHtml4(diff.text));
sb.append("</span>");
break;
default:
break;
}
}
}
return sb.toString().replaceAll("\n", " <br/>\n");
}
public static void attachUploadFilesToPost(Resource resource) {
final String[] temporaryUploadFiles = getTemporaryFileListFromHiddenForm();
if(isTemporaryFilesExist(temporaryUploadFiles)){
int attachedFileCount = Attachment.moveOnlySelected(UserApp.currentUser().asResource(), resource,
temporaryUploadFiles);
if( attachedFileCount != temporaryUploadFiles.length){
flash(Constants.TITLE, Messages.get("post.popup.fileAttach.hasMissing", temporaryUploadFiles.length - attachedFileCount));
flash(Constants.DESCRIPTION, Messages.get("post.popup.fileAttach.hasMissing.description", getTemporaryFilesServerKeepUpTimeOfMinuntes()));
}
}
}
public static void attachUploadFilesToPost(JsonNode files, Resource resource) {
if(files != null && files.isArray() && files.size() > 0){
String [] fileIds = new String[files.size()];
int idx = 0;
for (JsonNode fileNo : files) {
fileIds[idx] = fileNo.asText();
idx++;
}
int attachedFileCount = Attachment.moveOnlySelected(UserApp.currentUser().asResource(), resource,
fileIds);
if( attachedFileCount != files.size()){
flash(Constants.TITLE, Messages.get("post.popup.fileAttach.hasMissing", files.size() - attachedFileCount));
flash(Constants.DESCRIPTION, Messages.get("post.popup.fileAttach.hasMissing.description", getTemporaryFilesServerKeepUpTimeOfMinuntes()));
}
}
}
private static long getTemporaryFilesServerKeepUpTimeOfMinuntes() {
return AttachmentApp.TEMPORARYFILES_KEEPUP_TIME_MILLIS/(60*1000l);
}
public static String[] getTemporaryFileListFromHiddenForm() {
Http.MultipartFormData body = request().body().asMultipartFormData();
if (body == null) {
return new String[] {};
}
String [] temporaryUploadFiles = body.asFormUrlEncoded().get(AttachmentApp.TAG_NAME_FOR_TEMPORARY_UPLOAD_FILES);
if (temporaryUploadFiles == null) {
return new String[] {};
}
final String CSV_DELIMITER = ",";
return temporaryUploadFiles[0].split(CSV_DELIMITER);
}
private static boolean isTemporaryFilesExist(String[] files) {
if (ArrayUtils.getLength(files) == 0) {
return false;
}
return StringUtils.isNotBlank(files[0]);
}
protected static boolean isSelectedToSendNotificationMail() {
Map<String,String[]> data;
if (isMultiPartFormData()) {
data = request().body().asMultipartFormData().asFormUrlEncoded();
} else {
data = request().body().asFormUrlEncoded();
}
return "yes".equalsIgnoreCase(HttpUtil.getFirstValueFromQuery(data, "notificationMail"));
}
private static boolean isMultiPartFormData() {
return request().body().asMultipartFormData() != null;
}
}
| issue: Increase diff cost for readability
| app/controllers/AbstractPostingApp.java | issue: Increase diff cost for readability |
|
Java | apache-2.0 | e9c383704ad01545def2dd6abec31554314848bf | 0 | kwin/jackrabbit-oak,chetanmeh/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,code-distillery/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,code-distillery/jackrabbit-oak,alexparvulescu/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,francescomari/jackrabbit-oak,alexkli/jackrabbit-oak,francescomari/jackrabbit-oak,stillalex/jackrabbit-oak,code-distillery/jackrabbit-oak,code-distillery/jackrabbit-oak,anchela/jackrabbit-oak,kwin/jackrabbit-oak,meggermo/jackrabbit-oak,stillalex/jackrabbit-oak,anchela/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,yesil/jackrabbit-oak,yesil/jackrabbit-oak,anchela/jackrabbit-oak,stillalex/jackrabbit-oak,stillalex/jackrabbit-oak,alexparvulescu/jackrabbit-oak,alexkli/jackrabbit-oak,catholicon/jackrabbit-oak,alexkli/jackrabbit-oak,catholicon/jackrabbit-oak,meggermo/jackrabbit-oak,chetanmeh/jackrabbit-oak,yesil/jackrabbit-oak,stillalex/jackrabbit-oak,anchela/jackrabbit-oak,chetanmeh/jackrabbit-oak,francescomari/jackrabbit-oak,chetanmeh/jackrabbit-oak,catholicon/jackrabbit-oak,code-distillery/jackrabbit-oak,alexparvulescu/jackrabbit-oak,alexparvulescu/jackrabbit-oak,francescomari/jackrabbit-oak,catholicon/jackrabbit-oak,kwin/jackrabbit-oak,meggermo/jackrabbit-oak,catholicon/jackrabbit-oak,alexkli/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,kwin/jackrabbit-oak,meggermo/jackrabbit-oak,yesil/jackrabbit-oak,kwin/jackrabbit-oak,anchela/jackrabbit-oak,francescomari/jackrabbit-oak,chetanmeh/jackrabbit-oak,alexkli/jackrabbit-oak,alexparvulescu/jackrabbit-oak,meggermo/jackrabbit-oak | /*
* 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.jackrabbit.oak.security.authentication.token;
import java.security.Principal;
import java.util.List;
import com.google.common.collect.ImmutableSet;
import org.apache.jackrabbit.oak.AbstractSecurityTest;
import org.apache.jackrabbit.oak.spi.commit.MoveTracker;
import org.apache.jackrabbit.oak.spi.commit.ValidatorProvider;
import org.apache.jackrabbit.oak.spi.security.ConfigurationParameters;
import org.apache.jackrabbit.oak.spi.security.authentication.token.TokenConfiguration;
import org.apache.jackrabbit.oak.spi.security.authentication.token.TokenProvider;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class TokenConfigurationImplTest extends AbstractSecurityTest {
private static final int DEFAULT_EXPIRATION = 2 * 3600 * 1000;
private TokenConfigurationImpl tc;
@Override
public void before() throws Exception {
super.before();
tc = new TokenConfigurationImpl(getSecurityProvider());
}
@Override
protected ConfigurationParameters getSecurityConfigParameters() {
ConfigurationParameters config = ConfigurationParameters.of(
TokenProvider.PARAM_TOKEN_EXPIRATION, 60,
TokenProvider.PARAM_TOKEN_REFRESH, true);
return ConfigurationParameters.of(TokenConfiguration.NAME, config);
}
@Test
public void testGetName() {
assertEquals(TokenConfiguration.NAME, tc.getName());
}
@Test
public void testConfigOptions() {
int exp = tc.getParameters().getConfigValue(TokenProvider.PARAM_TOKEN_EXPIRATION, DEFAULT_EXPIRATION);
assertEquals(60, exp);
}
@Test
public void testConfigOptions2() {
int exp = getConfig(TokenConfiguration.class).getParameters().getConfigValue(TokenProvider.PARAM_TOKEN_EXPIRATION, DEFAULT_EXPIRATION);
assertEquals(60, exp);
}
@Test
public void testRefresh() {
boolean refresh = getConfig(TokenConfiguration.class).getParameters().getConfigValue(TokenProvider.PARAM_TOKEN_REFRESH, false);
assertTrue(refresh);
}
@Test
public void testGetValidators() {
List<? extends ValidatorProvider> validators = tc.getValidators(root.getContentSession().getWorkspaceName(), ImmutableSet.<Principal>of(), new MoveTracker());
assertNotNull(validators);
assertEquals(1, validators.size());
assertTrue(validators.get(0) instanceof TokenValidatorProvider);
}
@Test
public void testGetTokenProvider() {
TokenProvider tp = tc.getTokenProvider(root);
assertTrue(tp instanceof TokenProviderImpl);
}
} | oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenConfigurationImplTest.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.jackrabbit.oak.security.authentication.token;
import org.apache.jackrabbit.oak.AbstractSecurityTest;
import org.apache.jackrabbit.oak.spi.security.ConfigurationParameters;
import org.apache.jackrabbit.oak.spi.security.authentication.token.TokenConfiguration;
import org.apache.jackrabbit.oak.spi.security.authentication.token.TokenProvider;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class TokenConfigurationImplTest extends AbstractSecurityTest {
private static final int DEFAULT_EXPIRATION = 2 * 3600 * 1000;
private TokenConfigurationImpl tc;
@Override
public void before() throws Exception {
super.before();
tc = new TokenConfigurationImpl(getSecurityProvider());
}
@Override
protected ConfigurationParameters getSecurityConfigParameters() {
ConfigurationParameters config = ConfigurationParameters.of(
TokenProvider.PARAM_TOKEN_EXPIRATION, 60,
TokenProvider.PARAM_TOKEN_REFRESH, true);
return ConfigurationParameters.of(TokenConfiguration.NAME, config);
}
@Test
public void testConfigOptions() {
int exp = tc.getParameters().getConfigValue(TokenProvider.PARAM_TOKEN_EXPIRATION, DEFAULT_EXPIRATION);
assertEquals(60, exp);
}
@Test
public void testConfigOptions2() {
int exp = getConfig(TokenConfiguration.class).getParameters().getConfigValue(TokenProvider.PARAM_TOKEN_EXPIRATION, DEFAULT_EXPIRATION);
assertEquals(60, exp);
}
@Test
public void testRefresh() {
boolean refresh = getConfig(TokenConfiguration.class).getParameters().getConfigValue(TokenProvider.PARAM_TOKEN_REFRESH, false);
assertTrue(refresh);
}
} | minor improvement: test coverage for authentication
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1755689 13f79535-47bb-0310-9956-ffa450edef68
| oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenConfigurationImplTest.java | minor improvement: test coverage for authentication |
|
Java | apache-2.0 | 86e9d8ca4e016f970c888518b93c4dd852099824 | 0 | Arshardh/carbon-apimgt,pradeepmurugesan/carbon-apimgt,thusithak/carbon-apimgt,harsha89/carbon-apimgt,pradeepmurugesan/carbon-apimgt,sineth-neranjana/carbon-apimgt,Rajith90/carbon-apimgt,pubudu538/carbon-apimgt,pubudu538/carbon-apimgt,prasa7/carbon-apimgt,dewmini/carbon-apimgt,ruks/carbon-apimgt,Arshardh/carbon-apimgt,malinthaprasan/carbon-apimgt,tharikaGitHub/carbon-apimgt,chamilaadhi/carbon-apimgt,sineth-neranjana/carbon-apimgt,tharindu1st/carbon-apimgt,harsha89/carbon-apimgt,pradeepmurugesan/carbon-apimgt,dewmini/carbon-apimgt,tharikaGitHub/carbon-apimgt,lalaji/carbon-apimgt,chamindias/carbon-apimgt,jaadds/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,Minoli/carbon-apimgt,uvindra/carbon-apimgt,prasa7/carbon-apimgt,knPerera/carbon-apimgt,tharikaGitHub/carbon-apimgt,fazlan-nazeem/carbon-apimgt,chamilaadhi/carbon-apimgt,wso2/carbon-apimgt,uvindra/carbon-apimgt,sineth-neranjana/carbon-apimgt,knPerera/carbon-apimgt,pubudu538/carbon-apimgt,malinthaprasan/carbon-apimgt,lalaji/carbon-apimgt,uvindra/carbon-apimgt,jaadds/carbon-apimgt,lalaji/carbon-apimgt,chamindias/carbon-apimgt,chamindias/carbon-apimgt,ChamNDeSilva/carbon-apimgt,malinthaprasan/carbon-apimgt,wso2/carbon-apimgt,fazlan-nazeem/carbon-apimgt,harsha89/carbon-apimgt,jaadds/carbon-apimgt,wso2/carbon-apimgt,sambaheerathan/carbon-apimgt,nuwand/carbon-apimgt,lakmali/carbon-apimgt,ChamNDeSilva/carbon-apimgt,jaadds/carbon-apimgt,tharindu1st/carbon-apimgt,abimarank/carbon-apimgt,wso2/carbon-apimgt,fazlan-nazeem/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,Arshardh/carbon-apimgt,ruks/carbon-apimgt,ChamNDeSilva/carbon-apimgt,nuwand/carbon-apimgt,isharac/carbon-apimgt,praminda/carbon-apimgt,dewmini/carbon-apimgt,sambaheerathan/carbon-apimgt,ruks/carbon-apimgt,tharikaGitHub/carbon-apimgt,Arshardh/carbon-apimgt,knPerera/carbon-apimgt,malinthaprasan/carbon-apimgt,hevayo/carbon-apimgt,pubudu538/carbon-apimgt,pradeepmurugesan/carbon-apimgt,hevayo/carbon-apimgt,lakmali/carbon-apimgt,tharindu1st/carbon-apimgt,thusithak/carbon-apimgt,sambaheerathan/carbon-apimgt,bhathiya/carbon-apimgt,chamilaadhi/carbon-apimgt,isharac/carbon-apimgt,uvindra/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,chamindias/carbon-apimgt,praminda/carbon-apimgt,rswijesena/carbon-apimgt,prasa7/carbon-apimgt,Minoli/carbon-apimgt,nuwand/carbon-apimgt,Rajith90/carbon-apimgt,rswijesena/carbon-apimgt,chamilaadhi/carbon-apimgt,ruks/carbon-apimgt,bhathiya/carbon-apimgt,sineth-neranjana/carbon-apimgt,nuwand/carbon-apimgt,knPerera/carbon-apimgt,bhathiya/carbon-apimgt,Minoli/carbon-apimgt,hevayo/carbon-apimgt,thusithak/carbon-apimgt,harsha89/carbon-apimgt,rswijesena/carbon-apimgt,praminda/carbon-apimgt,bhathiya/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,fazlan-nazeem/carbon-apimgt,hevayo/carbon-apimgt,Rajith90/carbon-apimgt,Rajith90/carbon-apimgt,lakmali/carbon-apimgt,isharac/carbon-apimgt,abimarank/carbon-apimgt,abimarank/carbon-apimgt,isharac/carbon-apimgt,prasa7/carbon-apimgt,tharindu1st/carbon-apimgt | /*
* Copyright (c) 2005-2011, 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.apimgt.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.apimgt.api.APIDefinition;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.APIManager;
import org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException;
import org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException;
import org.wso2.carbon.apimgt.api.BlockConditionNotFoundException;
import org.wso2.carbon.apimgt.api.PolicyNotFoundException;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.api.model.APIIdentifier;
import org.wso2.carbon.apimgt.api.model.APIKey;
import org.wso2.carbon.apimgt.api.model.Application;
import org.wso2.carbon.apimgt.api.model.Documentation;
import org.wso2.carbon.apimgt.api.model.DocumentationType;
import org.wso2.carbon.apimgt.api.model.ResourceFile;
import org.wso2.carbon.apimgt.api.model.SubscribedAPI;
import org.wso2.carbon.apimgt.api.model.Subscriber;
import org.wso2.carbon.apimgt.api.model.Tier;
import org.wso2.carbon.apimgt.api.model.policy.APIPolicy;
import org.wso2.carbon.apimgt.api.model.policy.BandwidthLimit;
import org.wso2.carbon.apimgt.api.model.policy.Limit;
import org.wso2.carbon.apimgt.api.model.policy.Policy;
import org.wso2.carbon.apimgt.api.model.policy.PolicyConstants;
import org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit;
import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO;
import org.wso2.carbon.apimgt.impl.definitions.APIDefinitionFromSwagger20;
import org.wso2.carbon.apimgt.impl.dto.ThrottleProperties;
import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder;
import org.wso2.carbon.apimgt.impl.utils.APINameComparator;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.apimgt.impl.utils.LRUCache;
import org.wso2.carbon.apimgt.impl.utils.TierNameComparator;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact;
import org.wso2.carbon.governance.api.generic.GenericArtifactManager;
import org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact;
import org.wso2.carbon.governance.api.util.GovernanceUtils;
import org.wso2.carbon.registry.core.ActionConstants;
import org.wso2.carbon.registry.core.Association;
import org.wso2.carbon.registry.core.Collection;
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.registry.core.config.RegistryContext;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager;
import org.wso2.carbon.registry.core.pagination.PaginationContext;
import org.wso2.carbon.registry.core.session.UserRegistry;
import org.wso2.carbon.registry.core.utils.RegistryUtils;
import org.wso2.carbon.user.api.AuthorizationManager;
import org.wso2.carbon.user.core.UserRealm;
import org.wso2.carbon.user.core.UserStoreException;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* The basic abstract implementation of the core APIManager interface. This implementation uses
* the governance system registry for storing APIs and related metadata.
*/
public abstract class AbstractAPIManager implements APIManager {
protected Log log = LogFactory.getLog(getClass());
protected Registry registry;
protected UserRegistry configRegistry;
protected ApiMgtDAO apiMgtDAO;
protected int tenantId = MultitenantConstants.INVALID_TENANT_ID; //-1 the issue does not occur.;
protected String tenantDomain;
protected String username;
private LRUCache<String, GenericArtifactManager> genericArtifactCache = new LRUCache<String, GenericArtifactManager>(
5);
// API definitions from swagger v2.0
protected static final APIDefinition definitionFromSwagger20 = new APIDefinitionFromSwagger20();
public AbstractAPIManager() throws APIManagementException {
}
public AbstractAPIManager(String username) throws APIManagementException {
apiMgtDAO = ApiMgtDAO.getInstance();
try {
if (username == null) {
this.registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceUserRegistry();
this.configRegistry = ServiceReferenceHolder.getInstance().getRegistryService().getConfigSystemRegistry();
this.username= CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME;
ServiceReferenceHolder.setUserRealm((ServiceReferenceHolder.getInstance().getRealmService().getBootstrapRealm()));
} else {
String tenantDomainName = MultitenantUtils.getTenantDomain(username);
String tenantUserName = MultitenantUtils.getTenantAwareUsername(username);
int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomainName);
this.tenantId=tenantId;
this.tenantDomain=tenantDomainName;
this.username=tenantUserName;
APIUtil.loadTenantRegistry(tenantId);
this.registry = ServiceReferenceHolder.getInstance().
getRegistryService().getGovernanceUserRegistry(tenantUserName, tenantId);
this.configRegistry = ServiceReferenceHolder.getInstance().getRegistryService().getConfigSystemRegistry(tenantId);
//load resources for each tenants.
APIUtil.loadloadTenantAPIRXT( tenantUserName, tenantId);
APIUtil.loadTenantAPIPolicy( tenantUserName, tenantId);
//Check whether GatewayType is "Synapse" before attempting to load Custom-Sequences into registry
APIManagerConfiguration configuration = ServiceReferenceHolder.getInstance()
.getAPIManagerConfigurationService().getAPIManagerConfiguration();
String gatewayType = configuration.getFirstProperty(APIConstants.API_GATEWAY_TYPE);
if (APIConstants.API_GATEWAY_TYPE_SYNAPSE.equalsIgnoreCase(gatewayType)) {
APIUtil.writeDefinedSequencesToTenantRegistry(tenantId);
}
ServiceReferenceHolder.setUserRealm((UserRealm) (ServiceReferenceHolder.getInstance().
getRealmService().getTenantUserRealm(tenantId)));
}
ServiceReferenceHolder.setUserRealm(ServiceReferenceHolder.getInstance().
getRegistryService().getConfigSystemRegistry().getUserRealm());
registerCustomQueries(configRegistry, username);
} catch (RegistryException e) {
handleException("Error while obtaining registry objects", e);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
handleException("Error while getting user registry for user:"+username, e);
}
}
/**
* method to register custom registry queries
* @param registry Registry instance to use
* @throws RegistryException n error
*/
private void registerCustomQueries(UserRegistry registry, String username)
throws RegistryException, APIManagementException {
String tagsQueryPath = RegistryConstants.QUERIES_COLLECTION_PATH + "/tag-summary";
String latestAPIsQueryPath = RegistryConstants.QUERIES_COLLECTION_PATH + "/latest-apis";
String resourcesByTag = RegistryConstants.QUERIES_COLLECTION_PATH + "/resource-by-tag";
String path = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(),
APIUtil.getMountedPath(RegistryContext.getBaseInstance(),
RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) +
APIConstants.GOVERNANCE_COMPONENT_REGISTRY_LOCATION);
if (username == null) {
try {
UserRealm realm = ServiceReferenceHolder.getUserRealm();
RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager(realm);
authorizationManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
} catch (UserStoreException e) {
handleException("Error while setting the permissions", e);
}
}else if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
int tenantId;
try {
tenantId = ServiceReferenceHolder.getInstance().getRealmService().
getTenantManager().getTenantId(tenantDomain);
AuthorizationManager authManager = ServiceReferenceHolder.getInstance().getRealmService().
getTenantUserRealm(tenantId).getAuthorizationManager();
authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
handleException("Error while setting the permissions", e);
}
}
if (!registry.resourceExists(tagsQueryPath)) {
Resource resource = registry.newResource();
//Tag Search Query
//'MOCK_PATH' used to bypass ChrootWrapper -> filterSearchResult. A valid registry path is
// a must for executeQuery results to be passed to client side
String sql1 =
"SELECT '" + APIUtil.getMountedPath(RegistryContext.getBaseInstance(),
RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) +
APIConstants.GOVERNANCE_COMPONENT_REGISTRY_LOCATION + "' AS MOCK_PATH, " +
" RT.REG_TAG_NAME AS TAG_NAME, " +
" COUNT(RT.REG_TAG_NAME) AS USED_COUNT " +
"FROM " +
" REG_RESOURCE_TAG RRT, " +
" REG_TAG RT, " +
" REG_RESOURCE R, " +
" REG_RESOURCE_PROPERTY RRP, " +
" REG_PROPERTY RP " +
"WHERE " +
" RT.REG_ID = RRT.REG_TAG_ID " +
" AND R.REG_MEDIA_TYPE = 'application/vnd.wso2-api+xml' " +
" AND RRT.REG_VERSION = R.REG_VERSION " +
" AND RRP.REG_VERSION = R.REG_VERSION " +
" AND RP.REG_NAME = 'STATUS' " +
" AND RRP.REG_PROPERTY_ID = RP.REG_ID " +
" AND (RP.REG_VALUE !='DEPRECATED' AND RP.REG_VALUE !='CREATED' AND RP.REG_VALUE !='BLOCKED' AND RP.REG_VALUE !='RETIRED') " +
"GROUP BY " +
" RT.REG_TAG_NAME";
resource.setContent(sql1);
resource.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
resource.addProperty(RegistryConstants.RESULT_TYPE_PROPERTY_NAME,
RegistryConstants.TAG_SUMMARY_RESULT_TYPE);
registry.put(tagsQueryPath, resource);
}
if (!registry.resourceExists(latestAPIsQueryPath)) {
//Recently added APIs
Resource resource = registry.newResource();
String sql =
"SELECT " +
" RR.REG_PATH_ID AS REG_PATH_ID, " +
" RR.REG_NAME AS REG_NAME " +
"FROM " +
" REG_RESOURCE RR, " +
" REG_RESOURCE_PROPERTY RRP, " +
" REG_PROPERTY RP " +
"WHERE " +
" RR.REG_MEDIA_TYPE = 'application/vnd.wso2-api+xml' " +
" AND RRP.REG_VERSION = RR.REG_VERSION " +
" AND RP.REG_NAME = 'STATUS' " +
" AND RRP.REG_PROPERTY_ID = RP.REG_ID " +
" AND (RP.REG_VALUE !='DEPRECATED' AND RP.REG_VALUE !='CREATED') " +
"ORDER BY " +
" RR.REG_LAST_UPDATED_TIME " +
"DESC ";
resource.setContent(sql);
resource.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
resource.addProperty(RegistryConstants.RESULT_TYPE_PROPERTY_NAME,
RegistryConstants.RESOURCES_RESULT_TYPE);
registry.put(latestAPIsQueryPath, resource);
}
if(!registry.resourceExists(resourcesByTag)){
Resource resource = registry.newResource();
String sql =
"SELECT '" + APIUtil.getMountedPath(RegistryContext.getBaseInstance(),
RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) +
APIConstants.GOVERNANCE_COMPONENT_REGISTRY_LOCATION + "' AS MOCK_PATH, " +
" R.REG_UUID AS REG_UUID " +
"FROM " +
" REG_RESOURCE_TAG RRT, " +
" REG_TAG RT, " +
" REG_RESOURCE R, " +
" REG_PATH RP " +
"WHERE " +
" RT.REG_TAG_NAME = ? " +
" AND R.REG_MEDIA_TYPE = 'application/vnd.wso2-api+xml' " +
" AND RP.REG_PATH_ID = R.REG_PATH_ID " +
" AND RT.REG_ID = RRT.REG_TAG_ID " +
" AND RRT.REG_VERSION = R.REG_VERSION ";
resource.setContent(sql);
resource.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
resource.addProperty(RegistryConstants.RESULT_TYPE_PROPERTY_NAME,
RegistryConstants.RESOURCE_UUID_RESULT_TYPE);
registry.put(resourcesByTag, resource);
}
}
public void cleanup() {
}
public List<API> getAllAPIs() throws APIManagementException {
List<API> apiSortedList = new ArrayList<API>();
boolean isTenantFlowStarted = false;
try {
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
isTenantFlowStarted = true;
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
}
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry,
APIConstants.API_KEY);
GenericArtifact[] artifacts = artifactManager.getAllGenericArtifacts();
for (GenericArtifact artifact : artifacts) {
API api = null;
try {
api = APIUtil.getAPI(artifact);
} catch (APIManagementException e) {
//log and continue since we want to load the rest of the APIs.
log.error("Error while loading API " + artifact.getAttribute(APIConstants.API_OVERVIEW_NAME), e);
}
if (api != null) {
apiSortedList.add(api);
}
}
} catch (RegistryException e) {
handleException("Failed to get APIs from the registry", e);
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
Collections.sort(apiSortedList, new APINameComparator());
return apiSortedList;
}
public API getAPI(APIIdentifier identifier) throws APIManagementException {
String apiPath = APIUtil.getAPIPath(identifier);
Registry registry;
try {
String apiTenantDomain = MultitenantUtils.getTenantDomain(
APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
int apiTenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
.getTenantId(apiTenantDomain);
if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(apiTenantDomain)) {
APIUtil.loadTenantRegistry(apiTenantId);
}
if (this.tenantDomain == null || !this.tenantDomain.equals(apiTenantDomain)) { //cross tenant scenario
registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceUserRegistry(
MultitenantUtils.getTenantAwareUsername(
APIUtil.replaceEmailDomainBack(identifier.getProviderName())), apiTenantId);
} else {
registry = this.registry;
}
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry,
APIConstants.API_KEY);
Resource apiResource = registry.get(apiPath);
String artifactId = apiResource.getUUID();
if (artifactId == null) {
throw new APIManagementException("artifact id is null for : " + apiPath);
}
GenericArtifact apiArtifact = artifactManager.getGenericArtifact(artifactId);
API api = APIUtil.getAPIForPublishing(apiArtifact, registry);
//check for API visibility
if (APIConstants.API_GLOBAL_VISIBILITY.equals(api.getVisibility())) { //global api
return api;
}
if (this.tenantDomain == null || !this.tenantDomain.equals(apiTenantDomain)) {
throw new APIManagementException("User " + username + " does not have permission to view API : "
+ api.getId().getApiName());
}
return api;
} catch (RegistryException e) {
handleException("Failed to get API from : " + apiPath, e);
return null;
} catch (org.wso2.carbon.user.api.UserStoreException e) {
handleException("Failed to get API from : " + apiPath, e);
return null;
}
}
/**
* Get API by registry artifact id
*
* @param uuid Registry artifact id
* @param requestedTenantDomain tenantDomain for the registry
* @return API of the provided artifact id
* @throws APIManagementException
*/
public API getAPIbyUUID(String uuid, String requestedTenantDomain) throws APIManagementException {
try {
Registry registry;
if (requestedTenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals
(requestedTenantDomain)) {
int id = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
.getTenantId(requestedTenantDomain);
registry = ServiceReferenceHolder.getInstance().
getRegistryService().getGovernanceSystemRegistry(id);
} else {
if (this.tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(this.tenantDomain)) {
// at this point, requested tenant = carbon.super but logged in user is anonymous or tenant
registry = ServiceReferenceHolder.getInstance().
getRegistryService().getGovernanceSystemRegistry(MultitenantConstants.SUPER_TENANT_ID);
} else {
// both requested tenant and logged in user's tenant are carbon.super
registry = this.registry;
}
}
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
GenericArtifact apiArtifact = artifactManager.getGenericArtifact(uuid);
if (apiArtifact != null) {
return APIUtil.getAPIForPublishing(apiArtifact, registry);
} else {
handleResourceNotFoundException(
"Failed to get API. API artifact corresponding to artifactId " + uuid + " does not exist");
return null;
}
} catch (RegistryException e) {
handleException("Failed to get API", e);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
handleException("Failed to get API", e);
return null;
}
return null;
}
/**
* Get minimal details of API by registry artifact id
*
* @param uuid Registry artifact id
* @return API of the provided artifact id
* @throws APIManagementException
*/
public API getLightweightAPIByUUID(String uuid, String requestedTenantDomain) throws APIManagementException {
try {
Registry registry;
if (requestedTenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals
(requestedTenantDomain)) {
int id = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
.getTenantId(requestedTenantDomain);
registry = ServiceReferenceHolder.getInstance().
getRegistryService().getGovernanceSystemRegistry(id);
} else {
if (this.tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(this.tenantDomain)) {
// at this point, requested tenant = carbon.super but logged in user is anonymous or tenant
registry = ServiceReferenceHolder.getInstance().
getRegistryService().getGovernanceSystemRegistry(MultitenantConstants.SUPER_TENANT_ID);
} else {
// both requested tenant and logged in user's tenant are carbon.super
registry = this.registry;
}
}
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
GenericArtifact apiArtifact = artifactManager.getGenericArtifact(uuid);
if (apiArtifact != null) {
return APIUtil.getAPIInformation(apiArtifact, registry);
} else {
handleResourceNotFoundException(
"Failed to get API. API artifact corresponding to artifactId " + uuid + " does not exist");
}
} catch (RegistryException e) {
handleException("Failed to get API with uuid " + uuid, e);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
handleException("Failed to get tenant Id while getting API with uuid " + uuid, e);
}
return null;
}
/**
* Get minimal details of API by API identifier
*
* @param identifier APIIdentifier object
* @return API of the provided APIIdentifier
* @throws APIManagementException
*/
public API getLightweightAPI(APIIdentifier identifier) throws APIManagementException {
String apiPath = APIUtil.getAPIPath(identifier);
boolean tenantFlowStarted = false;
try {
String tenantDomain = MultitenantUtils.getTenantDomain(
APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
tenantFlowStarted = true;
Registry registry = getRegistry(identifier, apiPath);
if (registry != null) {
Resource apiResource = registry.get(apiPath);
String artifactId = apiResource.getUUID();
if (artifactId == null) {
throw new APIManagementException("artifact id is null for : " + apiPath);
}
GenericArtifactManager artifactManager = getGenericArtifactManager(identifier, registry);
GovernanceArtifact apiArtifact = artifactManager.getGenericArtifact(artifactId);
return APIUtil.getAPIInformation(apiArtifact, registry);
} else {
handleException("Failed to get registry from api identifier: " + identifier);
return null;
}
} catch (RegistryException e) {
handleException("Failed to get API from : " + apiPath, e);
return null;
} finally {
if (tenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
private GenericArtifactManager getGenericArtifactManager(APIIdentifier identifier, Registry registry)
throws APIManagementException {
String tenantDomain = MultitenantUtils
.getTenantDomain(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
GenericArtifactManager manager = genericArtifactCache.get(tenantDomain);
if (manager != null) {
return manager;
}
manager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
genericArtifactCache.put(tenantDomain, manager);
return manager;
}
private Registry getRegistry(APIIdentifier identifier, String apiPath)
throws APIManagementException {
Registry passRegistry;
try {
String tenantDomain = MultitenantUtils
.getTenantDomain(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
int id = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
.getTenantId(tenantDomain);
// explicitly load the tenant's registry
APIUtil.loadTenantRegistry(id);
passRegistry = ServiceReferenceHolder.getInstance().getRegistryService()
.getGovernanceSystemRegistry(id);
} else {
if (this.tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(this.tenantDomain)) {
// explicitly load the tenant's registry
APIUtil.loadTenantRegistry(MultitenantConstants.SUPER_TENANT_ID);
passRegistry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceUserRegistry(
identifier.getProviderName(), MultitenantConstants.SUPER_TENANT_ID);
} else {
passRegistry = this.registry;
}
}
} catch (RegistryException e) {
handleException("Failed to get API from registry on path of : " + apiPath, e);
return null;
} catch (org.wso2.carbon.user.api.UserStoreException e) {
handleException("Failed to get API from registry on path of : " + apiPath, e);
return null;
}
return passRegistry;
}
public API getAPI(String apiPath) throws APIManagementException {
try {
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry,
APIConstants.API_KEY);
Resource apiResource = registry.get(apiPath);
String artifactId = apiResource.getUUID();
if (artifactId == null) {
throw new APIManagementException("artifact id is null for : " + apiPath);
}
GenericArtifact apiArtifact = artifactManager.getGenericArtifact(artifactId);
return APIUtil.getAPI(apiArtifact);
} catch (RegistryException e) {
handleException("Failed to get API from : " + apiPath, e);
return null;
}
}
public boolean isAPIAvailable(APIIdentifier identifier) throws APIManagementException {
String path = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR +
identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR +
identifier.getApiName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion();
try {
return registry.resourceExists(path);
} catch (RegistryException e) {
handleException("Failed to check availability of api :" + path, e);
return false;
}
}
public Set<String> getAPIVersions(String providerName, String apiName)
throws APIManagementException {
Set<String> versionSet = new HashSet<String>();
String apiPath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR +
providerName + RegistryConstants.PATH_SEPARATOR + apiName;
try {
Resource resource = registry.get(apiPath);
if (resource instanceof Collection) {
Collection collection = (Collection) resource;
String[] versionPaths = collection.getChildren();
if (versionPaths == null || versionPaths.length == 0) {
return versionSet;
}
for (String path : versionPaths) {
versionSet.add(path.substring(apiPath.length() + 1));
}
} else {
throw new APIManagementException("API version must be a collection " + apiName);
}
} catch (RegistryException e) {
handleException("Failed to get versions for API: " + apiName, e);
}
return versionSet;
}
/**
* Returns the swagger 2.0 definition of the given API
*
* @param apiId id of the APIIdentifier
* @return An String containing the swagger 2.0 definition
* @throws APIManagementException
*/
@Override
public String getSwagger20Definition(APIIdentifier apiId) throws APIManagementException {
String apiTenantDomain = MultitenantUtils.getTenantDomain(
APIUtil.replaceEmailDomainBack(apiId.getProviderName()));
String swaggerDoc = null;
try {
Registry registryType;
//Tenant store anonymous mode if current tenant and the required tenant is not matching
if (this.tenantDomain == null || isTenantDomainNotMatching(apiTenantDomain)) {
int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(
apiTenantDomain);
registryType = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceUserRegistry(
CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId);
} else {
registryType = registry;
}
swaggerDoc = definitionFromSwagger20.getAPIDefinition(apiId, registryType);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
handleException("Failed to get swagger documentation of API : " + apiId, e);
} catch (RegistryException e) {
handleException("Failed to get swagger documentation of API : " + apiId, e);
}
return swaggerDoc;
}
public String addResourceFile(String resourcePath, ResourceFile resourceFile) throws APIManagementException {
try {
Resource thumb = registry.newResource();
thumb.setContentStream(resourceFile.getContent());
thumb.setMediaType(resourceFile.getContentType());
registry.put(resourcePath, thumb);
if(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(tenantDomain)){
return RegistryConstants.PATH_SEPARATOR + "registry"
+ RegistryConstants.PATH_SEPARATOR + "resource"
+ RegistryConstants.PATH_SEPARATOR + "_system"
+ RegistryConstants.PATH_SEPARATOR + "governance"
+ resourcePath;
}
else{
return "/t/"+tenantDomain+ RegistryConstants.PATH_SEPARATOR + "registry"
+ RegistryConstants.PATH_SEPARATOR + "resource"
+ RegistryConstants.PATH_SEPARATOR + "_system"
+ RegistryConstants.PATH_SEPARATOR + "governance"
+ resourcePath;
}
} catch (RegistryException e) {
handleException("Error while adding the resource to the registry", e);
}
return null;
}
/**
* Checks whether the given document already exists for the given api
*
* @param identifier API Identifier
* @param docName Name of the document
* @return true if document already exists for the given api
* @throws APIManagementException if failed to check existence of the documentation
*/
public boolean isDocumentationExist(APIIdentifier identifier, String docName) throws APIManagementException {
String docPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR +
identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR +
identifier.getApiName() + RegistryConstants.PATH_SEPARATOR +
identifier.getVersion() + RegistryConstants.PATH_SEPARATOR +
APIConstants.DOC_DIR + RegistryConstants.PATH_SEPARATOR + docName;
try {
return registry.resourceExists(docPath);
} catch (RegistryException e) {
handleException("Failed to check existence of the document :" + docPath, e);
}
return false;
}
public List<Documentation> getAllDocumentation(APIIdentifier apiId) throws APIManagementException {
List<Documentation> documentationList = new ArrayList<Documentation>();
String apiResourcePath = APIUtil.getAPIPath(apiId);
try {
Association[] docAssociations = registry.getAssociations(apiResourcePath,
APIConstants.DOCUMENTATION_ASSOCIATION);
for (Association association : docAssociations) {
String docPath = association.getDestinationPath();
Resource docResource = registry.get(docPath);
GenericArtifactManager artifactManager = new GenericArtifactManager(registry,
APIConstants.DOCUMENTATION_KEY);
GenericArtifact docArtifact = artifactManager.getGenericArtifact(docResource.getUUID());
Documentation doc = APIUtil.getDocumentation(docArtifact);
Date contentLastModifiedDate;
Date docLastModifiedDate = docResource.getLastModified();
if (Documentation.DocumentSourceType.INLINE.equals(doc.getSourceType())) {
String contentPath = APIUtil.getAPIDocContentPath(apiId, doc.getName());
contentLastModifiedDate = registry.get(contentPath).getLastModified();
doc.setLastUpdated((contentLastModifiedDate.after(docLastModifiedDate) ?
contentLastModifiedDate : docLastModifiedDate));
} else {
doc.setLastUpdated(docLastModifiedDate);
}
documentationList.add(doc);
}
} catch (RegistryException e) {
handleException("Failed to get documentations for api " + apiId.getApiName(), e);
}
return documentationList;
}
public List<Documentation> getAllDocumentation(APIIdentifier apiId,String loggedUsername) throws APIManagementException {
List<Documentation> documentationList = new ArrayList<Documentation>();
String apiResourcePath = APIUtil.getAPIPath(apiId);
try {
String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(apiId.getProviderName()));
Registry registryType;
/* If the API provider is a tenant, load tenant registry*/
boolean isTenantMode=(tenantDomain != null);
if ((isTenantMode && this.tenantDomain==null) || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {//Tenant store anonymous mode
int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
.getTenantId(tenantDomain);
registryType = ServiceReferenceHolder.getInstance().
getRegistryService().getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId);
} else {
registryType = registry;
}
Association[] docAssociations = registryType.getAssociations(apiResourcePath,
APIConstants.DOCUMENTATION_ASSOCIATION);
for (Association association : docAssociations) {
String docPath = association.getDestinationPath();
Resource docResource = null;
try {
docResource = registryType.get(docPath);
} catch (org.wso2.carbon.registry.core.secure.AuthorizationFailedException e) {
//do nothing. Permission not allowed to access the doc.
}catch (RegistryException e){
handleException("Failed to get documentations for api " + apiId.getApiName(), e);
}
if (docResource != null) {
GenericArtifactManager artifactManager = new GenericArtifactManager(registryType,
APIConstants.DOCUMENTATION_KEY);
GenericArtifact docArtifact = artifactManager.getGenericArtifact(
docResource.getUUID());
Documentation doc = APIUtil.getDocumentation(docArtifact, apiId.getProviderName());
Date contentLastModifiedDate;
Date docLastModifiedDate = docResource.getLastModified();
if (Documentation.DocumentSourceType.INLINE.equals(doc.getSourceType())) {
String contentPath = APIUtil.getAPIDocContentPath(apiId, doc.getName());
try {
contentLastModifiedDate = registryType.get(contentPath).getLastModified();
doc.setLastUpdated((contentLastModifiedDate.after(docLastModifiedDate) ?
contentLastModifiedDate : docLastModifiedDate));
} catch (org.wso2.carbon.registry.core.secure.AuthorizationFailedException e) {
//do nothing. Permission not allowed to access the doc.
}
} else {
doc.setLastUpdated(docLastModifiedDate);
}
documentationList.add(doc);
}
}
} catch (RegistryException e) {
handleException("Failed to get documentations for api " + apiId.getApiName(), e);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
handleException("Failed to get documentations for api " + apiId.getApiName(), e);
}
return documentationList;
}
private boolean isTenantDomainNotMatching(String tenantDomain) {
if (this.tenantDomain != null) {
return !(this.tenantDomain.equals(tenantDomain));
}
return true;
}
public Documentation getDocumentation(APIIdentifier apiId, DocumentationType docType,
String docName) throws APIManagementException {
Documentation documentation = null;
String docPath = APIUtil.getAPIDocPath(apiId) + docName;
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry,
APIConstants.DOCUMENTATION_KEY);
try {
Resource docResource = registry.get(docPath);
GenericArtifact artifact = artifactManager.getGenericArtifact(docResource.getUUID());
documentation = APIUtil.getDocumentation(artifact);
} catch (RegistryException e) {
handleException("Failed to get documentation details", e);
}
return documentation;
}
/**
* Get a documentation by artifact Id
*
* @param docId artifact id of the document
* @param requestedTenantDomain tenant domain of the registry where the artifact is located
* @return Document object which represents the artifact id
* @throws APIManagementException
*/
public Documentation getDocumentation(String docId, String requestedTenantDomain) throws APIManagementException {
Documentation documentation = null;
try {
Registry registryType;
boolean isTenantMode = (requestedTenantDomain != null);
//Tenant store anonymous mode if current tenant and the required tenant is not matching
if ((isTenantMode && this.tenantDomain == null) || (isTenantMode && isTenantDomainNotMatching(
requestedTenantDomain))) {
int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
.getTenantId(requestedTenantDomain);
registryType = ServiceReferenceHolder.getInstance().
getRegistryService()
.getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId);
} else {
registryType = registry;
}
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registryType,
APIConstants.DOCUMENTATION_KEY);
GenericArtifact artifact = artifactManager.getGenericArtifact(docId);
if (null != artifact) {
documentation = APIUtil.getDocumentation(artifact);
}
} catch (RegistryException e) {
handleException("Failed to get documentation details", e);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
handleException("Failed to get documentation details", e);
}
return documentation;
}
public String getDocumentationContent(APIIdentifier identifier, String documentationName)
throws APIManagementException {
String contentPath = APIUtil.getAPIDocPath(identifier) +
APIConstants.INLINE_DOCUMENT_CONTENT_DIR + RegistryConstants.PATH_SEPARATOR +
documentationName;
String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
Registry registry;
boolean isTenantFlowStarted = false;
try {
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
PrivilegedCarbonContext.startTenantFlow();
isTenantFlowStarted = true;
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
}
/* If the API provider is a tenant, load tenant registry*/
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
int id = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
registry = ServiceReferenceHolder.getInstance().
getRegistryService().getGovernanceSystemRegistry(id);
} else {
if (this.tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(this.tenantDomain)) {
registry = ServiceReferenceHolder.getInstance().
getRegistryService().getGovernanceUserRegistry(identifier.getProviderName(), MultitenantConstants.SUPER_TENANT_ID);
} else {
registry = this.registry;
}
}
if (registry.resourceExists(contentPath)) {
Resource docContent = registry.get(contentPath);
Object content = docContent.getContent();
if (content != null) {
return new String((byte[]) docContent.getContent(), Charset.defaultCharset());
}
}
} catch (RegistryException e) {
String msg = "No document content found for documentation: "
+ documentationName + " of API: "+identifier.getApiName();
handleException(msg, e);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
handleException("Failed to get ddocument content found for documentation: "
+ documentationName + " of API: "+identifier.getApiName(), e);
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
return null;
}
public Subscriber getSubscriberById(String accessToken) throws APIManagementException {
return apiMgtDAO.getSubscriberById(accessToken);
}
public boolean isContextExist(String context) throws APIManagementException {
// Since we don't have tenant in the APIM table, we do the filtering using this hack
if(context!=null && context.startsWith("/t/"))
context = context.replace("/t/" + MultitenantUtils.getTenantDomainFromUrl(context),""); //removing prefix
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
context = "/t/" + tenantDomain + context;
}
return apiMgtDAO.isContextExist(context);
}
public boolean isScopeKeyExist(String scopeKey, int tenantid) throws APIManagementException {
return apiMgtDAO.isScopeKeyExist(scopeKey, tenantid);
}
public boolean isScopeKeyAssigned(APIIdentifier identifier, String scopeKey, int tenantid)
throws APIManagementException {
return apiMgtDAO.isScopeKeyAssigned(identifier, scopeKey, tenantid);
}
public boolean isApiNameExist(String apiName) throws APIManagementException {
String tenantName = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
tenantName = tenantDomain;
}
return apiMgtDAO.isApiNameExist(apiName, tenantName);
}
public void addSubscriber(String username, String groupingId)
throws APIManagementException {
Subscriber subscriber = new Subscriber(username);
subscriber.setSubscribedDate(new Date());
//TODO : need to set the proper email
subscriber.setEmail("");
try {
int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
.getTenantId(MultitenantUtils.getTenantDomain(username));
subscriber.setTenantId(tenantId);
apiMgtDAO.addSubscriber(subscriber, groupingId);
//Add a default application once subscriber is added
addDefaultApplicationForSubscriber(subscriber);
} catch (APIManagementException e) {
handleException("Error while adding the subscriber " + subscriber.getName(), e);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
handleException("Error while adding the subscriber " + subscriber.getName(), e);
}
}
/**
* Add default application on the first time a subscriber is added to the database
* @param subscriber Subscriber
*
* @throws APIManagementException if an error occurs while adding default application
*/
private void addDefaultApplicationForSubscriber (Subscriber subscriber) throws APIManagementException {
Application defaultApp = new Application(APIConstants.DEFAULT_APPLICATION_NAME, subscriber);
if (APIUtil.isEnabledUnlimitedTier()) {
defaultApp.setTier(APIConstants.UNLIMITED_TIER);
} else {
Map<String, Tier> throttlingTiers = APIUtil.getTiers(APIConstants.TIER_APPLICATION_TYPE,
MultitenantUtils.getTenantDomain(subscriber.getName()));
Set<Tier> tierValueList = new HashSet<Tier>(throttlingTiers.values());
List<Tier> sortedTierList = APIUtil.sortTiers(tierValueList);
defaultApp.setTier(sortedTierList.get(0).getName());
}
//application will not be shared within the group
defaultApp.setGroupId("");
apiMgtDAO.addApplication(defaultApp, subscriber.getName());
}
public void updateSubscriber(Subscriber subscriber)
throws APIManagementException {
apiMgtDAO.updateSubscriber(subscriber);
}
public Subscriber getSubscriber(int subscriberId)
throws APIManagementException {
return apiMgtDAO.getSubscriber(subscriberId);
}
public ResourceFile getIcon(APIIdentifier identifier) throws APIManagementException {
String artifactPath = APIConstants.API_IMAGE_LOCATION + RegistryConstants.PATH_SEPARATOR +
identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR +
identifier.getApiName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion();
String thumbPath = artifactPath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_ICON_IMAGE;
try {
if (registry.resourceExists(thumbPath)) {
Resource res = registry.get(thumbPath);
return new ResourceFile(res.getContentStream(), res.getMediaType());
}
} catch (RegistryException e) {
handleException("Error while loading API icon from the registry", e);
}
return null;
}
public Set<API> getSubscriberAPIs(Subscriber subscriber) throws APIManagementException {
SortedSet<API> apiSortedSet = new TreeSet<API>(new APINameComparator());
Set<SubscribedAPI> subscribedAPIs = apiMgtDAO.getSubscribedAPIs(subscriber, null);
boolean isTenantFlowStarted = false;
try {
if(tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)){
isTenantFlowStarted = true;
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
}
for (SubscribedAPI subscribedAPI : subscribedAPIs) {
String apiPath = APIUtil.getAPIPath(subscribedAPI.getApiId());
Resource resource;
try {
resource = registry.get(apiPath);
GenericArtifactManager artifactManager = new GenericArtifactManager(registry, APIConstants.API_KEY);
GenericArtifact artifact = artifactManager.getGenericArtifact(
resource.getUUID());
API api = APIUtil.getAPI(artifact, registry);
if (api != null) {
apiSortedSet.add(api);
}
} catch (RegistryException e) {
handleException("Failed to get APIs for subscriber: " + subscriber.getName(), e);
}
}
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
return apiSortedSet;
}
/**
* Returns the corresponding application given the uuid
* @param uuid uuid of the Application
* @return it will return Application corresponds to the uuid provided.
* @throws APIManagementException
*/
public Application getApplicationByUUID(String uuid) throws APIManagementException {
return apiMgtDAO.getApplicationByUUID(uuid);
}
/** returns the SubscribedAPI object which is related to the UUID
*
* @param uuid UUID of Subscription
* @return SubscribedAPI object which is related to the UUID
* @throws APIManagementException
*/
public SubscribedAPI getSubscriptionByUUID(String uuid) throws APIManagementException {
return apiMgtDAO.getSubscriptionByUUID(uuid);
}
protected final void handleException(String msg, Exception e) throws APIManagementException {
log.error(msg, e);
throw new APIManagementException(msg, e);
}
protected final void handleException(String msg) throws APIManagementException {
log.error(msg);
throw new APIManagementException(msg);
}
protected final void handleResourceAlreadyExistsException(String msg) throws APIMgtResourceAlreadyExistsException {
log.error(msg);
throw new APIMgtResourceAlreadyExistsException(msg);
}
protected final void handleResourceNotFoundException(String msg) throws APIMgtResourceNotFoundException {
log.error(msg);
throw new APIMgtResourceNotFoundException(msg);
}
protected final void handlePolicyNotFoundException(String msg) throws PolicyNotFoundException {
log.error(msg);
throw new PolicyNotFoundException(msg);
}
protected final void handleBlockConditionNotFoundException(String msg) throws BlockConditionNotFoundException {
log.error(msg);
throw new BlockConditionNotFoundException(msg);
}
public boolean isApplicationTokenExists(String accessToken) throws APIManagementException {
return apiMgtDAO.isAccessTokenExists(accessToken);
}
public boolean isApplicationTokenRevoked(String accessToken) throws APIManagementException {
return apiMgtDAO.isAccessTokenRevoked(accessToken);
}
public APIKey getAccessTokenData(String accessToken) throws APIManagementException {
return apiMgtDAO.getAccessTokenData(accessToken);
}
public Map<Integer, APIKey> searchAccessToken(String searchType, String searchTerm, String loggedInUser)
throws APIManagementException {
if (searchType == null) {
return apiMgtDAO.getAccessTokens(searchTerm);
} else {
if ("User".equalsIgnoreCase(searchType)) {
return apiMgtDAO.getAccessTokensByUser(searchTerm, loggedInUser);
} else if ("Before".equalsIgnoreCase(searchType)) {
return apiMgtDAO.getAccessTokensByDate(searchTerm, false, loggedInUser);
} else if ("After".equalsIgnoreCase(searchType)) {
return apiMgtDAO.getAccessTokensByDate(searchTerm, true, loggedInUser);
} else {
return apiMgtDAO.getAccessTokens(searchTerm);
}
}
}
public Set<APIIdentifier> getAPIByAccessToken(String accessToken) throws APIManagementException{
return apiMgtDAO.getAPIByAccessToken(accessToken);
}
public API getAPI(APIIdentifier identifier,APIIdentifier oldIdentifier, String oldContext) throws
APIManagementException {
String apiPath = APIUtil.getAPIPath(identifier);
try {
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry,
APIConstants.API_KEY);
Resource apiResource = registry.get(apiPath);
String artifactId = apiResource.getUUID();
if (artifactId == null) {
throw new APIManagementException("artifact id is null for : " + apiPath);
}
GenericArtifact apiArtifact = artifactManager.getGenericArtifact(artifactId);
return APIUtil.getAPI(apiArtifact, registry,oldIdentifier, oldContext);
} catch (RegistryException e) {
handleException("Failed to get API from : " + apiPath, e);
return null;
}
}
@Override
public Set<Tier> getAllTiers() throws APIManagementException {
Set<Tier> tiers = new TreeSet<Tier>(new TierNameComparator());
Map<String, Tier> tierMap;
if (tenantId == MultitenantConstants.INVALID_TENANT_ID) {
tierMap = APIUtil.getAllTiers();
} else {
boolean isTenantFlowStarted = false;
try {
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
PrivilegedCarbonContext.startTenantFlow();
isTenantFlowStarted = true;
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
}
tierMap = APIUtil.getAllTiers(tenantId);
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
tiers.addAll(tierMap.values());
return tiers;
}
@Override
public Set<Tier> getAllTiers(String tenantDomain) throws APIManagementException {
Set<Tier> tiers = new TreeSet<Tier>(new TierNameComparator());
Map<String, Tier> tierMap;
boolean isTenantFlowStarted = false;
try {
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
PrivilegedCarbonContext.startTenantFlow();
isTenantFlowStarted = true;
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
}
int requestedTenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
if (requestedTenantId == MultitenantConstants.SUPER_TENANT_ID
|| requestedTenantId == MultitenantConstants.INVALID_TENANT_ID) {
tierMap = APIUtil.getAllTiers();
} else {
tierMap = APIUtil.getAllTiers(requestedTenantId);
}
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
tiers.addAll(tierMap.values());
return tiers;
}
/**
* Returns a list of pre-defined # {@link org.wso2.carbon.apimgt.api.model.Tier} in the system.
*
* @return Set<Tier>
*/
public Set<Tier> getTiers() throws APIManagementException {
Set<Tier> tiers = new TreeSet<Tier>(new TierNameComparator());
Map<String, Tier> tierMap;
if(!APIUtil.isAdvanceThrottlingEnabled()) {
if (tenantId == MultitenantConstants.INVALID_TENANT_ID) {
tierMap = APIUtil.getTiers();
} else {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
tierMap = APIUtil.getTiers(tenantId);
PrivilegedCarbonContext.endTenantFlow();
}
tiers.addAll(tierMap.values());
} else {
tierMap = APIUtil.getTiersFromPolicies(PolicyConstants.POLICY_LEVEL_SUB, tenantId);
tiers.addAll(tierMap.values());
}
return tiers;
}
/**
* Returns a list of pre-defined # {@link org.wso2.carbon.apimgt.api.model.Tier} in the system.
*
* @return Set<Tier>
*/
public Set<Tier> getTiers(String tenantDomain) throws APIManagementException {
Set<Tier> tiers = new TreeSet<Tier>(new TierNameComparator());
Map<String, Tier> tierMap;
if(!APIUtil.isAdvanceThrottlingEnabled()) {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
int requestedTenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
if (requestedTenantId == MultitenantConstants.SUPER_TENANT_ID
|| requestedTenantId == MultitenantConstants.INVALID_TENANT_ID) {
tierMap = APIUtil.getTiers();
} else {
tierMap = APIUtil.getTiers(requestedTenantId);
}
tiers.addAll(tierMap.values());
PrivilegedCarbonContext.endTenantFlow();
} else {
tierMap = APIUtil.getTiersFromPolicies(PolicyConstants.POLICY_LEVEL_SUB, tenantId);
tiers.addAll(tierMap.values());
}
return tiers;
}
/**
* Returns a list of pre-defined # {@link org.wso2.carbon.apimgt.api.model.Tier} in the system.
*
* @param tierType type of the tiers (api,resource ot application)
* @param username current logged user
* @return Set<Tier> return list of tier names
* @throws APIManagementException APIManagementException if failed to get the predefined tiers
*/
public Set<Tier> getTiers(int tierType, String username) throws APIManagementException {
Set<Tier> tiers = new TreeSet<Tier>(new TierNameComparator());
String tenantDomain = MultitenantUtils.getTenantDomain(username);
Map<String, Tier> tierMap;
if(!APIUtil.isAdvanceThrottlingEnabled()) {
tierMap = APIUtil.getTiers(tierType, tenantDomain);
tiers.addAll(tierMap.values());
} else {
int tenantIdFromUsername = APIUtil.getTenantId(username);
if (tierType == APIConstants.TIER_API_TYPE) {
tierMap = APIUtil.getTiersFromPolicies(PolicyConstants.POLICY_LEVEL_SUB, tenantIdFromUsername);
} else if (tierType == APIConstants.TIER_RESOURCE_TYPE) {
tierMap = APIUtil.getTiersFromPolicies(PolicyConstants.POLICY_LEVEL_API, tenantIdFromUsername);
} else if (tierType == APIConstants.TIER_APPLICATION_TYPE) {
tierMap = APIUtil.getTiersFromPolicies(PolicyConstants.POLICY_LEVEL_APP, tenantIdFromUsername);
} else {
throw new APIManagementException("No such a tier type : " + tierType);
}
tiers.addAll(tierMap.values());
}
return tiers;
}
/**
* Returns a list of pre-defined # {@link org.wso2.carbon.apimgt.api.model.Tier} in the system.
*
* @return Map<String, String>
*/
public Map<String,String> getTenantDomainMappings(String tenantDomain, String apiType) throws APIManagementException {
return APIUtil.getDomainMappings(tenantDomain, apiType);
}
public boolean isDuplicateContextTemplate(String contextTemplate) throws APIManagementException{
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
if (contextTemplate != null && contextTemplate.startsWith("/t/")) {
contextTemplate =
contextTemplate.replace("/t/" + MultitenantUtils.getTenantDomainFromUrl(contextTemplate), "");
}
contextTemplate = "/t/" + tenantDomain + contextTemplate;
}
return apiMgtDAO.isDuplicateContextTemplate(contextTemplate);
}
public Policy[] getPolicies(String username, String level) throws APIManagementException {
Policy[] policies = null;
int tenantID = APIUtil.getTenantId(username);
if(PolicyConstants.POLICY_LEVEL_API.equals(level)){
policies = apiMgtDAO.getAPIPolicies(tenantID);
} else if(PolicyConstants.POLICY_LEVEL_APP.equals(level)){
policies = apiMgtDAO.getApplicationPolicies(tenantID);
} else if(PolicyConstants.POLICY_LEVEL_SUB.equals(level)){
policies = apiMgtDAO.getSubscriptionPolicies(tenantID);
} else if(PolicyConstants.POLICY_LEVEL_GLOBAL.equals(level)){
policies = apiMgtDAO.getGlobalPolicies(tenantID);
}
return policies;
}
@Override
public Map<String,Object> searchPaginatedAPIs(String searchQuery, String requestedTenantDomain,
int start,int end, boolean isLazyLoad) throws APIManagementException {
Map<String,Object> result = new HashMap<String,Object>();
boolean isTenantFlowStarted = false;
try {
boolean isTenantMode=(requestedTenantDomain != null);
if (isTenantMode && !org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(requestedTenantDomain)) {
isTenantFlowStarted = true;
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(requestedTenantDomain, true);
} else {
requestedTenantDomain = org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
isTenantFlowStarted = true;
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(requestedTenantDomain, true);
}
Registry userRegistry;
int tenantIDLocal = 0;
String userNameLocal = this.username;
if ((isTenantMode && this.tenantDomain==null) || (isTenantMode && isTenantDomainNotMatching(requestedTenantDomain))) {//Tenant store anonymous mode
tenantIDLocal = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
.getTenantId(requestedTenantDomain);
userRegistry = ServiceReferenceHolder.getInstance().
getRegistryService().getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantIDLocal);
userNameLocal = CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME;
} else {
userRegistry = this.registry;
tenantIDLocal = tenantId;
}
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userNameLocal);
if (searchQuery.startsWith(APIConstants.DOCUMENTATION_SEARCH_TYPE_PREFIX)) {
Map<Documentation, API> apiDocMap =
APIUtil.searchAPIsByDoc(userRegistry, tenantIDLocal, userNameLocal, searchQuery.split("=")[1],
APIConstants.STORE_CLIENT);
result.put("apis", apiDocMap);
/*Pagination for Document search results is not supported yet, hence length is sent as end-start*/
if (apiDocMap.isEmpty()) {
result.put("length", 0);
} else {
result.put("length", end-start);
}
} else if (searchQuery.startsWith(APIConstants.SUBCONTEXT_SEARCH_TYPE_PREFIX)) {
result = APIUtil.searchAPIsByURLPattern(userRegistry, searchQuery.split("=")[1], start,end);
} else {
result = searchPaginatedAPIs(userRegistry, searchQuery, start, end, isLazyLoad);
}
} catch (Exception e) {
handleException("Failed to Search APIs", e);
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
return result;
}
/**
* Returns API Search result based on the provided query. This search method supports '&' based concatenate
* search in multiple fields.
* @param registry
* @param searchQuery. Ex: provider=*admin*&version=*1*
* @return API result
* @throws APIManagementException
*/
public Map<String,Object> searchPaginatedAPIs(Registry registry, String searchQuery, int start, int end,
boolean limitAttributes) throws APIManagementException {
SortedSet<API> apiSet = new TreeSet<API>(new APINameComparator());
List<API> apiList = new ArrayList<API>();
Map<String,Object> result=new HashMap<String, Object>();
int totalLength=0;
boolean isMore = false;
try {
String paginationLimit = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
.getAPIManagerConfiguration()
.getFirstProperty(APIConstants.API_STORE_APIS_PER_PAGE);
// If the Config exists use it to set the pagination limit
final int maxPaginationLimit;
if (paginationLimit != null) {
// The additional 1 added to the maxPaginationLimit is to help us determine if more
// APIs may exist so that we know that we are unable to determine the actual total
// API count. We will subtract this 1 later on so that it does not interfere with
// the logic of the rest of the application
int pagination = Integer.parseInt(paginationLimit);
// Because the store jaggery pagination logic is 10 results per a page we need to set pagination
// limit to at least 11 or the pagination done at this level will conflict with the store pagination
// leading to some of the APIs not being displayed
if (pagination < 11) {
pagination = 11;
log.warn("Value of '" + APIConstants.API_STORE_APIS_PER_PAGE + "' is too low, defaulting to 11");
}
maxPaginationLimit = start + pagination + 1;
}
// Else if the config is not specified we go with default functionality and load all
else {
maxPaginationLimit = Integer.MAX_VALUE;
}
PaginationContext.init(start, end, "ASC", APIConstants.API_OVERVIEW_NAME, maxPaginationLimit);
List<GovernanceArtifact> governanceArtifacts = GovernanceUtils.findGovernanceArtifacts(searchQuery,
registry, APIConstants.API_RXT_MEDIA_TYPE);
totalLength = PaginationContext.getInstance().getLength();
boolean isFound = true;
if (governanceArtifacts == null || governanceArtifacts.size() == 0) {
if (searchQuery.contains(APIConstants.API_OVERVIEW_PROVIDER)) {
searchQuery = searchQuery.replaceAll(APIConstants.API_OVERVIEW_PROVIDER, APIConstants.API_OVERVIEW_OWNER);
governanceArtifacts = GovernanceUtils.findGovernanceArtifacts(searchQuery,
registry, APIConstants.API_RXT_MEDIA_TYPE);
if (governanceArtifacts == null || governanceArtifacts.size() == 0) {
isFound = false;
}
} else {
isFound = false;
}
}
if (!isFound) {
result.put("apis", apiSet);
result.put("length", 0);
result.put("isMore", isMore);
return result;
}
// Check to see if we can speculate that there are more APIs to be loaded
if (maxPaginationLimit == totalLength) {
isMore = true; // More APIs exist, cannot determine total API count without incurring perf hit
--totalLength; // Remove the additional 1 added earlier when setting max pagination limit
}
int tempLength =0;
for (GovernanceArtifact artifact : governanceArtifacts) {
API resultAPI;
if (limitAttributes) {
resultAPI = APIUtil.getAPI(artifact);
} else {
resultAPI = APIUtil.getAPI(artifact, registry);
}
if (resultAPI != null) {
apiList.add(resultAPI);
}
String status = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
// Ensure the APIs returned matches the length, there could be an additional API
// returned due incrementing the pagination limit when getting from registry
tempLength++;
if (tempLength >= totalLength){
break;
}
}
apiSet.addAll(apiList);
} catch (RegistryException e) {
handleException("Failed to search APIs with type", e);
} finally {
PaginationContext.destroy();
}
result.put("apis",apiSet);
result.put("length",totalLength);
result.put("isMore", isMore);
return result;
}
}
| components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/AbstractAPIManager.java | /*
* Copyright (c) 2005-2011, 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.apimgt.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.apimgt.api.APIDefinition;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.APIManager;
import org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException;
import org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException;
import org.wso2.carbon.apimgt.api.BlockConditionNotFoundException;
import org.wso2.carbon.apimgt.api.PolicyNotFoundException;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.api.model.APIIdentifier;
import org.wso2.carbon.apimgt.api.model.APIKey;
import org.wso2.carbon.apimgt.api.model.Application;
import org.wso2.carbon.apimgt.api.model.Documentation;
import org.wso2.carbon.apimgt.api.model.DocumentationType;
import org.wso2.carbon.apimgt.api.model.ResourceFile;
import org.wso2.carbon.apimgt.api.model.SubscribedAPI;
import org.wso2.carbon.apimgt.api.model.Subscriber;
import org.wso2.carbon.apimgt.api.model.Tier;
import org.wso2.carbon.apimgt.api.model.policy.APIPolicy;
import org.wso2.carbon.apimgt.api.model.policy.BandwidthLimit;
import org.wso2.carbon.apimgt.api.model.policy.Limit;
import org.wso2.carbon.apimgt.api.model.policy.Policy;
import org.wso2.carbon.apimgt.api.model.policy.PolicyConstants;
import org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit;
import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO;
import org.wso2.carbon.apimgt.impl.definitions.APIDefinitionFromSwagger20;
import org.wso2.carbon.apimgt.impl.dto.ThrottleProperties;
import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder;
import org.wso2.carbon.apimgt.impl.utils.APINameComparator;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.apimgt.impl.utils.LRUCache;
import org.wso2.carbon.apimgt.impl.utils.TierNameComparator;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact;
import org.wso2.carbon.governance.api.generic.GenericArtifactManager;
import org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact;
import org.wso2.carbon.governance.api.util.GovernanceUtils;
import org.wso2.carbon.registry.core.ActionConstants;
import org.wso2.carbon.registry.core.Association;
import org.wso2.carbon.registry.core.Collection;
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.registry.core.config.RegistryContext;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager;
import org.wso2.carbon.registry.core.pagination.PaginationContext;
import org.wso2.carbon.registry.core.session.UserRegistry;
import org.wso2.carbon.registry.core.utils.RegistryUtils;
import org.wso2.carbon.user.api.AuthorizationManager;
import org.wso2.carbon.user.core.UserRealm;
import org.wso2.carbon.user.core.UserStoreException;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* The basic abstract implementation of the core APIManager interface. This implementation uses
* the governance system registry for storing APIs and related metadata.
*/
public abstract class AbstractAPIManager implements APIManager {
protected Log log = LogFactory.getLog(getClass());
protected Registry registry;
protected UserRegistry configRegistry;
protected ApiMgtDAO apiMgtDAO;
protected int tenantId = MultitenantConstants.INVALID_TENANT_ID; //-1 the issue does not occur.;
protected String tenantDomain;
protected String username;
private LRUCache<String, GenericArtifactManager> genericArtifactCache = new LRUCache<String, GenericArtifactManager>(
5);
// API definitions from swagger v2.0
protected static final APIDefinition definitionFromSwagger20 = new APIDefinitionFromSwagger20();
public AbstractAPIManager() throws APIManagementException {
}
public AbstractAPIManager(String username) throws APIManagementException {
apiMgtDAO = ApiMgtDAO.getInstance();
try {
if (username == null) {
this.registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceUserRegistry();
this.configRegistry = ServiceReferenceHolder.getInstance().getRegistryService().getConfigSystemRegistry();
this.username= CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME;
ServiceReferenceHolder.setUserRealm((ServiceReferenceHolder.getInstance().getRealmService().getBootstrapRealm()));
} else {
String tenantDomainName = MultitenantUtils.getTenantDomain(username);
String tenantUserName = MultitenantUtils.getTenantAwareUsername(username);
int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomainName);
this.tenantId=tenantId;
this.tenantDomain=tenantDomainName;
this.username=tenantUserName;
APIUtil.loadTenantRegistry(tenantId);
this.registry = ServiceReferenceHolder.getInstance().
getRegistryService().getGovernanceUserRegistry(tenantUserName, tenantId);
this.configRegistry = ServiceReferenceHolder.getInstance().getRegistryService().getConfigSystemRegistry(tenantId);
//load resources for each tenants.
APIUtil.loadloadTenantAPIRXT( tenantUserName, tenantId);
APIUtil.loadTenantAPIPolicy( tenantUserName, tenantId);
//Check whether GatewayType is "Synapse" before attempting to load Custom-Sequences into registry
APIManagerConfiguration configuration = ServiceReferenceHolder.getInstance()
.getAPIManagerConfigurationService().getAPIManagerConfiguration();
String gatewayType = configuration.getFirstProperty(APIConstants.API_GATEWAY_TYPE);
if (APIConstants.API_GATEWAY_TYPE_SYNAPSE.equalsIgnoreCase(gatewayType)) {
APIUtil.writeDefinedSequencesToTenantRegistry(tenantId);
}
ServiceReferenceHolder.setUserRealm((UserRealm) (ServiceReferenceHolder.getInstance().
getRealmService().getTenantUserRealm(tenantId)));
}
ServiceReferenceHolder.setUserRealm(ServiceReferenceHolder.getInstance().
getRegistryService().getConfigSystemRegistry().getUserRealm());
registerCustomQueries(configRegistry, username);
} catch (RegistryException e) {
handleException("Error while obtaining registry objects", e);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
handleException("Error while getting user registry for user:"+username, e);
}
}
/**
* method to register custom registry queries
* @param registry Registry instance to use
* @throws RegistryException n error
*/
private void registerCustomQueries(UserRegistry registry, String username)
throws RegistryException, APIManagementException {
String tagsQueryPath = RegistryConstants.QUERIES_COLLECTION_PATH + "/tag-summary";
String latestAPIsQueryPath = RegistryConstants.QUERIES_COLLECTION_PATH + "/latest-apis";
String resourcesByTag = RegistryConstants.QUERIES_COLLECTION_PATH + "/resource-by-tag";
String path = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(),
APIUtil.getMountedPath(RegistryContext.getBaseInstance(),
RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) +
APIConstants.GOVERNANCE_COMPONENT_REGISTRY_LOCATION);
if (username == null) {
try {
UserRealm realm = ServiceReferenceHolder.getUserRealm();
RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager(realm);
authorizationManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
} catch (UserStoreException e) {
handleException("Error while setting the permissions", e);
}
}else if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
int tenantId;
try {
tenantId = ServiceReferenceHolder.getInstance().getRealmService().
getTenantManager().getTenantId(tenantDomain);
AuthorizationManager authManager = ServiceReferenceHolder.getInstance().getRealmService().
getTenantUserRealm(tenantId).getAuthorizationManager();
authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
handleException("Error while setting the permissions", e);
}
}
if (!registry.resourceExists(tagsQueryPath)) {
Resource resource = registry.newResource();
//Tag Search Query
//'MOCK_PATH' used to bypass ChrootWrapper -> filterSearchResult. A valid registry path is
// a must for executeQuery results to be passed to client side
String sql1 =
"SELECT '" + APIUtil.getMountedPath(RegistryContext.getBaseInstance(),
RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) +
APIConstants.GOVERNANCE_COMPONENT_REGISTRY_LOCATION + "' AS MOCK_PATH, " +
" RT.REG_TAG_NAME AS TAG_NAME, " +
" COUNT(RT.REG_TAG_NAME) AS USED_COUNT " +
"FROM " +
" REG_RESOURCE_TAG RRT, " +
" REG_TAG RT, " +
" REG_RESOURCE R, " +
" REG_RESOURCE_PROPERTY RRP, " +
" REG_PROPERTY RP " +
"WHERE " +
" RT.REG_ID = RRT.REG_TAG_ID " +
" AND R.REG_MEDIA_TYPE = 'application/vnd.wso2-api+xml' " +
" AND RRT.REG_VERSION = R.REG_VERSION " +
" AND RRP.REG_VERSION = R.REG_VERSION " +
" AND RP.REG_NAME = 'STATUS' " +
" AND RRP.REG_PROPERTY_ID = RP.REG_ID " +
" AND (RP.REG_VALUE !='DEPRECATED' AND RP.REG_VALUE !='CREATED' AND RP.REG_VALUE !='BLOCKED' AND RP.REG_VALUE !='RETIRED') " +
"GROUP BY " +
" RT.REG_TAG_NAME";
resource.setContent(sql1);
resource.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
resource.addProperty(RegistryConstants.RESULT_TYPE_PROPERTY_NAME,
RegistryConstants.TAG_SUMMARY_RESULT_TYPE);
registry.put(tagsQueryPath, resource);
}
if (!registry.resourceExists(latestAPIsQueryPath)) {
//Recently added APIs
Resource resource = registry.newResource();
String sql =
"SELECT " +
" RR.REG_PATH_ID AS REG_PATH_ID, " +
" RR.REG_NAME AS REG_NAME " +
"FROM " +
" REG_RESOURCE RR, " +
" REG_RESOURCE_PROPERTY RRP, " +
" REG_PROPERTY RP " +
"WHERE " +
" RR.REG_MEDIA_TYPE = 'application/vnd.wso2-api+xml' " +
" AND RRP.REG_VERSION = RR.REG_VERSION " +
" AND RP.REG_NAME = 'STATUS' " +
" AND RRP.REG_PROPERTY_ID = RP.REG_ID " +
" AND (RP.REG_VALUE !='DEPRECATED' AND RP.REG_VALUE !='CREATED') " +
"ORDER BY " +
" RR.REG_LAST_UPDATED_TIME " +
"DESC ";
resource.setContent(sql);
resource.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
resource.addProperty(RegistryConstants.RESULT_TYPE_PROPERTY_NAME,
RegistryConstants.RESOURCES_RESULT_TYPE);
registry.put(latestAPIsQueryPath, resource);
}
if(!registry.resourceExists(resourcesByTag)){
Resource resource = registry.newResource();
String sql =
"SELECT '" + APIUtil.getMountedPath(RegistryContext.getBaseInstance(),
RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) +
APIConstants.GOVERNANCE_COMPONENT_REGISTRY_LOCATION + "' AS MOCK_PATH, " +
" R.REG_UUID AS REG_UUID " +
"FROM " +
" REG_RESOURCE_TAG RRT, " +
" REG_TAG RT, " +
" REG_RESOURCE R, " +
" REG_PATH RP " +
"WHERE " +
" RT.REG_TAG_NAME = ? " +
" AND R.REG_MEDIA_TYPE = 'application/vnd.wso2-api+xml' " +
" AND RP.REG_PATH_ID = R.REG_PATH_ID " +
" AND RT.REG_ID = RRT.REG_TAG_ID " +
" AND RRT.REG_VERSION = R.REG_VERSION ";
resource.setContent(sql);
resource.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
resource.addProperty(RegistryConstants.RESULT_TYPE_PROPERTY_NAME,
RegistryConstants.RESOURCE_UUID_RESULT_TYPE);
registry.put(resourcesByTag, resource);
}
}
public void cleanup() {
}
public List<API> getAllAPIs() throws APIManagementException {
List<API> apiSortedList = new ArrayList<API>();
boolean isTenantFlowStarted = false;
try {
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
isTenantFlowStarted = true;
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
}
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry,
APIConstants.API_KEY);
GenericArtifact[] artifacts = artifactManager.getAllGenericArtifacts();
for (GenericArtifact artifact : artifacts) {
API api = null;
try {
api = APIUtil.getAPI(artifact);
} catch (APIManagementException e) {
//log and continue since we want to load the rest of the APIs.
log.error("Error while loading API " + artifact.getAttribute(APIConstants.API_OVERVIEW_NAME), e);
}
if (api != null) {
apiSortedList.add(api);
}
}
} catch (RegistryException e) {
handleException("Failed to get APIs from the registry", e);
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
Collections.sort(apiSortedList, new APINameComparator());
return apiSortedList;
}
public API getAPI(APIIdentifier identifier) throws APIManagementException {
String apiPath = APIUtil.getAPIPath(identifier);
Registry registry;
try {
String apiTenantDomain = MultitenantUtils.getTenantDomain(
APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
int apiTenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
.getTenantId(apiTenantDomain);
if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(apiTenantDomain)) {
APIUtil.loadTenantRegistry(apiTenantId);
}
if (this.tenantDomain == null || !this.tenantDomain.equals(apiTenantDomain)) { //cross tenant scenario
registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceUserRegistry(
MultitenantUtils.getTenantAwareUsername(
APIUtil.replaceEmailDomainBack(identifier.getProviderName())), apiTenantId);
} else {
registry = this.registry;
}
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry,
APIConstants.API_KEY);
Resource apiResource = registry.get(apiPath);
String artifactId = apiResource.getUUID();
if (artifactId == null) {
throw new APIManagementException("artifact id is null for : " + apiPath);
}
GenericArtifact apiArtifact = artifactManager.getGenericArtifact(artifactId);
API api = APIUtil.getAPIForPublishing(apiArtifact, registry);
//check for API visibility
if (APIConstants.API_GLOBAL_VISIBILITY.equals(api.getVisibility())) { //global api
return api;
}
if (this.tenantDomain == null || !this.tenantDomain.equals(apiTenantDomain)) {
throw new APIManagementException("User " + username + " does not have permission to view API : "
+ api.getId().getApiName());
}
return api;
} catch (RegistryException e) {
handleException("Failed to get API from : " + apiPath, e);
return null;
} catch (org.wso2.carbon.user.api.UserStoreException e) {
handleException("Failed to get API from : " + apiPath, e);
return null;
}
}
/**
* Get API by registry artifact id
*
* @param uuid Registry artifact id
* @param requestedTenantDomain tenantDomain for the registry
* @return API of the provided artifact id
* @throws APIManagementException
*/
public API getAPIbyUUID(String uuid, String requestedTenantDomain) throws APIManagementException {
try {
Registry registry;
if (requestedTenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals
(requestedTenantDomain)) {
int id = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
.getTenantId(requestedTenantDomain);
registry = ServiceReferenceHolder.getInstance().
getRegistryService().getGovernanceSystemRegistry(id);
} else {
if (this.tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(this.tenantDomain)) {
// at this point, requested tenant = carbon.super but logged in user is anonymous or tenant
registry = ServiceReferenceHolder.getInstance().
getRegistryService().getGovernanceSystemRegistry(MultitenantConstants.SUPER_TENANT_ID);
} else {
// both requested tenant and logged in user's tenant are carbon.super
registry = this.registry;
}
}
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
GenericArtifact apiArtifact = artifactManager.getGenericArtifact(uuid);
if (apiArtifact != null) {
return APIUtil.getAPIForPublishing(apiArtifact, registry);
} else {
handleResourceNotFoundException(
"Failed to get API. API artifact corresponding to artifactId " + uuid + " does not exist");
return null;
}
} catch (RegistryException e) {
handleException("Failed to get API", e);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
handleException("Failed to get API", e);
return null;
}
return null;
}
/**
* Get minimal details of API by registry artifact id
*
* @param uuid Registry artifact id
* @return API of the provided artifact id
* @throws APIManagementException
*/
public API getLightweightAPIByUUID(String uuid, String requestedTenantDomain) throws APIManagementException {
try {
Registry registry;
if (requestedTenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals
(requestedTenantDomain)) {
int id = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
.getTenantId(requestedTenantDomain);
registry = ServiceReferenceHolder.getInstance().
getRegistryService().getGovernanceSystemRegistry(id);
} else {
if (this.tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(this.tenantDomain)) {
// at this point, requested tenant = carbon.super but logged in user is anonymous or tenant
registry = ServiceReferenceHolder.getInstance().
getRegistryService().getGovernanceSystemRegistry(MultitenantConstants.SUPER_TENANT_ID);
} else {
// both requested tenant and logged in user's tenant are carbon.super
registry = this.registry;
}
}
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
GenericArtifact apiArtifact = artifactManager.getGenericArtifact(uuid);
if (apiArtifact != null) {
return APIUtil.getAPIInformation(apiArtifact, registry);
} else {
handleResourceNotFoundException(
"Failed to get API. API artifact corresponding to artifactId " + uuid + " does not exist");
}
} catch (RegistryException e) {
handleException("Failed to get API with uuid " + uuid, e);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
handleException("Failed to get tenant Id while getting API with uuid " + uuid, e);
}
return null;
}
/**
* Get minimal details of API by API identifier
*
* @param identifier APIIdentifier object
* @return API of the provided APIIdentifier
* @throws APIManagementException
*/
public API getLightweightAPI(APIIdentifier identifier) throws APIManagementException {
String apiPath = APIUtil.getAPIPath(identifier);
boolean tenantFlowStarted = false;
try {
String tenantDomain = MultitenantUtils.getTenantDomain(
APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
tenantFlowStarted = true;
Registry registry = getRegistry(identifier, apiPath);
if (registry != null) {
Resource apiResource = registry.get(apiPath);
String artifactId = apiResource.getUUID();
if (artifactId == null) {
throw new APIManagementException("artifact id is null for : " + apiPath);
}
GenericArtifactManager artifactManager = getGenericArtifactManager(identifier, registry);
GovernanceArtifact apiArtifact = artifactManager.getGenericArtifact(artifactId);
return APIUtil.getAPIInformation(apiArtifact, registry);
} else {
handleException("Failed to get registry from api identifier: " + identifier);
return null;
}
} catch (RegistryException e) {
handleException("Failed to get API from : " + apiPath, e);
return null;
} finally {
if (tenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
private GenericArtifactManager getGenericArtifactManager(APIIdentifier identifier, Registry registry)
throws APIManagementException {
String tenantDomain = MultitenantUtils
.getTenantDomain(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
GenericArtifactManager manager = genericArtifactCache.get(tenantDomain);
if (manager != null) {
return manager;
}
manager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
genericArtifactCache.put(tenantDomain, manager);
return manager;
}
private Registry getRegistry(APIIdentifier identifier, String apiPath)
throws APIManagementException {
Registry passRegistry;
try {
String tenantDomain = MultitenantUtils
.getTenantDomain(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
int id = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
.getTenantId(tenantDomain);
// explicitly load the tenant's registry
APIUtil.loadTenantRegistry(id);
passRegistry = ServiceReferenceHolder.getInstance().getRegistryService()
.getGovernanceSystemRegistry(id);
} else {
if (this.tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(this.tenantDomain)) {
// explicitly load the tenant's registry
APIUtil.loadTenantRegistry(MultitenantConstants.SUPER_TENANT_ID);
passRegistry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceUserRegistry(
identifier.getProviderName(), MultitenantConstants.SUPER_TENANT_ID);
} else {
passRegistry = this.registry;
}
}
} catch (RegistryException e) {
handleException("Failed to get API from registry on path of : " + apiPath, e);
return null;
} catch (org.wso2.carbon.user.api.UserStoreException e) {
handleException("Failed to get API from registry on path of : " + apiPath, e);
return null;
}
return passRegistry;
}
public API getAPI(String apiPath) throws APIManagementException {
try {
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry,
APIConstants.API_KEY);
Resource apiResource = registry.get(apiPath);
String artifactId = apiResource.getUUID();
if (artifactId == null) {
throw new APIManagementException("artifact id is null for : " + apiPath);
}
GenericArtifact apiArtifact = artifactManager.getGenericArtifact(artifactId);
return APIUtil.getAPI(apiArtifact);
} catch (RegistryException e) {
handleException("Failed to get API from : " + apiPath, e);
return null;
}
}
public boolean isAPIAvailable(APIIdentifier identifier) throws APIManagementException {
String path = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR +
identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR +
identifier.getApiName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion();
try {
return registry.resourceExists(path);
} catch (RegistryException e) {
handleException("Failed to check availability of api :" + path, e);
return false;
}
}
public Set<String> getAPIVersions(String providerName, String apiName)
throws APIManagementException {
Set<String> versionSet = new HashSet<String>();
String apiPath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR +
providerName + RegistryConstants.PATH_SEPARATOR + apiName;
try {
Resource resource = registry.get(apiPath);
if (resource instanceof Collection) {
Collection collection = (Collection) resource;
String[] versionPaths = collection.getChildren();
if (versionPaths == null || versionPaths.length == 0) {
return versionSet;
}
for (String path : versionPaths) {
versionSet.add(path.substring(apiPath.length() + 1));
}
} else {
throw new APIManagementException("API version must be a collection " + apiName);
}
} catch (RegistryException e) {
handleException("Failed to get versions for API: " + apiName, e);
}
return versionSet;
}
/**
* Returns the swagger 2.0 definition of the given API
*
* @param apiId id of the APIIdentifier
* @return An String containing the swagger 2.0 definition
* @throws APIManagementException
*/
@Override
public String getSwagger20Definition(APIIdentifier apiId) throws APIManagementException {
String apiTenantDomain = MultitenantUtils.getTenantDomain(
APIUtil.replaceEmailDomainBack(apiId.getProviderName()));
String swaggerDoc = null;
try {
Registry registryType;
//Tenant store anonymous mode if current tenant and the required tenant is not matching
if (this.tenantDomain == null || isTenantDomainNotMatching(apiTenantDomain)) {
int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(
apiTenantDomain);
registryType = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceUserRegistry(
CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId);
} else {
registryType = registry;
}
swaggerDoc = definitionFromSwagger20.getAPIDefinition(apiId, registryType);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
handleException("Failed to get swagger documentation of API : " + apiId, e);
} catch (RegistryException e) {
handleException("Failed to get swagger documentation of API : " + apiId, e);
}
return swaggerDoc;
}
public String addResourceFile(String resourcePath, ResourceFile resourceFile) throws APIManagementException {
try {
Resource thumb = registry.newResource();
thumb.setContentStream(resourceFile.getContent());
thumb.setMediaType(resourceFile.getContentType());
registry.put(resourcePath, thumb);
if(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(tenantDomain)){
return RegistryConstants.PATH_SEPARATOR + "registry"
+ RegistryConstants.PATH_SEPARATOR + "resource"
+ RegistryConstants.PATH_SEPARATOR + "_system"
+ RegistryConstants.PATH_SEPARATOR + "governance"
+ resourcePath;
}
else{
return "/t/"+tenantDomain+ RegistryConstants.PATH_SEPARATOR + "registry"
+ RegistryConstants.PATH_SEPARATOR + "resource"
+ RegistryConstants.PATH_SEPARATOR + "_system"
+ RegistryConstants.PATH_SEPARATOR + "governance"
+ resourcePath;
}
} catch (RegistryException e) {
handleException("Error while adding the resource to the registry", e);
}
return null;
}
/**
* Checks whether the given document already exists for the given api
*
* @param identifier API Identifier
* @param docName Name of the document
* @return true if document already exists for the given api
* @throws APIManagementException if failed to check existence of the documentation
*/
public boolean isDocumentationExist(APIIdentifier identifier, String docName) throws APIManagementException {
String docPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR +
identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR +
identifier.getApiName() + RegistryConstants.PATH_SEPARATOR +
identifier.getVersion() + RegistryConstants.PATH_SEPARATOR +
APIConstants.DOC_DIR + RegistryConstants.PATH_SEPARATOR + docName;
try {
return registry.resourceExists(docPath);
} catch (RegistryException e) {
handleException("Failed to check existence of the document :" + docPath, e);
}
return false;
}
public List<Documentation> getAllDocumentation(APIIdentifier apiId) throws APIManagementException {
List<Documentation> documentationList = new ArrayList<Documentation>();
String apiResourcePath = APIUtil.getAPIPath(apiId);
try {
Association[] docAssociations = registry.getAssociations(apiResourcePath,
APIConstants.DOCUMENTATION_ASSOCIATION);
for (Association association : docAssociations) {
String docPath = association.getDestinationPath();
Resource docResource = registry.get(docPath);
GenericArtifactManager artifactManager = new GenericArtifactManager(registry,
APIConstants.DOCUMENTATION_KEY);
GenericArtifact docArtifact = artifactManager.getGenericArtifact(docResource.getUUID());
Documentation doc = APIUtil.getDocumentation(docArtifact);
Date contentLastModifiedDate;
Date docLastModifiedDate = docResource.getLastModified();
if (Documentation.DocumentSourceType.INLINE.equals(doc.getSourceType())) {
String contentPath = APIUtil.getAPIDocContentPath(apiId, doc.getName());
contentLastModifiedDate = registry.get(contentPath).getLastModified();
doc.setLastUpdated((contentLastModifiedDate.after(docLastModifiedDate) ?
contentLastModifiedDate : docLastModifiedDate));
} else {
doc.setLastUpdated(docLastModifiedDate);
}
documentationList.add(doc);
}
} catch (RegistryException e) {
handleException("Failed to get documentations for api " + apiId.getApiName(), e);
}
return documentationList;
}
public List<Documentation> getAllDocumentation(APIIdentifier apiId,String loggedUsername) throws APIManagementException {
List<Documentation> documentationList = new ArrayList<Documentation>();
String apiResourcePath = APIUtil.getAPIPath(apiId);
try {
String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(apiId.getProviderName()));
Registry registryType;
/* If the API provider is a tenant, load tenant registry*/
boolean isTenantMode=(tenantDomain != null);
if ((isTenantMode && this.tenantDomain==null) || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {//Tenant store anonymous mode
int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
.getTenantId(tenantDomain);
registryType = ServiceReferenceHolder.getInstance().
getRegistryService().getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId);
} else {
registryType = registry;
}
Association[] docAssociations = registryType.getAssociations(apiResourcePath,
APIConstants.DOCUMENTATION_ASSOCIATION);
for (Association association : docAssociations) {
String docPath = association.getDestinationPath();
Resource docResource = null;
try {
docResource = registryType.get(docPath);
} catch (org.wso2.carbon.registry.core.secure.AuthorizationFailedException e) {
//do nothing. Permission not allowed to access the doc.
}catch (RegistryException e){
handleException("Failed to get documentations for api " + apiId.getApiName(), e);
}
if (docResource != null) {
GenericArtifactManager artifactManager = new GenericArtifactManager(registryType,
APIConstants.DOCUMENTATION_KEY);
GenericArtifact docArtifact = artifactManager.getGenericArtifact(
docResource.getUUID());
Documentation doc = APIUtil.getDocumentation(docArtifact, apiId.getProviderName());
Date contentLastModifiedDate;
Date docLastModifiedDate = docResource.getLastModified();
if (Documentation.DocumentSourceType.INLINE.equals(doc.getSourceType())) {
String contentPath = APIUtil.getAPIDocContentPath(apiId, doc.getName());
try {
contentLastModifiedDate = registryType.get(contentPath).getLastModified();
doc.setLastUpdated((contentLastModifiedDate.after(docLastModifiedDate) ?
contentLastModifiedDate : docLastModifiedDate));
} catch (org.wso2.carbon.registry.core.secure.AuthorizationFailedException e) {
//do nothing. Permission not allowed to access the doc.
}
} else {
doc.setLastUpdated(docLastModifiedDate);
}
documentationList.add(doc);
}
}
} catch (RegistryException e) {
handleException("Failed to get documentations for api " + apiId.getApiName(), e);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
handleException("Failed to get documentations for api " + apiId.getApiName(), e);
}
return documentationList;
}
private boolean isTenantDomainNotMatching(String tenantDomain) {
if (this.tenantDomain != null) {
return !(this.tenantDomain.equals(tenantDomain));
}
return true;
}
public Documentation getDocumentation(APIIdentifier apiId, DocumentationType docType,
String docName) throws APIManagementException {
Documentation documentation = null;
String docPath = APIUtil.getAPIDocPath(apiId) + docName;
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry,
APIConstants.DOCUMENTATION_KEY);
try {
Resource docResource = registry.get(docPath);
GenericArtifact artifact = artifactManager.getGenericArtifact(docResource.getUUID());
documentation = APIUtil.getDocumentation(artifact);
} catch (RegistryException e) {
handleException("Failed to get documentation details", e);
}
return documentation;
}
/**
* Get a documentation by artifact Id
*
* @param docId artifact id of the document
* @param requestedTenantDomain tenant domain of the registry where the artifact is located
* @return Document object which represents the artifact id
* @throws APIManagementException
*/
public Documentation getDocumentation(String docId, String requestedTenantDomain) throws APIManagementException {
Documentation documentation = null;
try {
Registry registryType;
boolean isTenantMode = (requestedTenantDomain != null);
//Tenant store anonymous mode if current tenant and the required tenant is not matching
if ((isTenantMode && this.tenantDomain == null) || (isTenantMode && isTenantDomainNotMatching(
requestedTenantDomain))) {
int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
.getTenantId(requestedTenantDomain);
registryType = ServiceReferenceHolder.getInstance().
getRegistryService()
.getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId);
} else {
registryType = registry;
}
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registryType,
APIConstants.DOCUMENTATION_KEY);
GenericArtifact artifact = artifactManager.getGenericArtifact(docId);
if (null != artifact) {
documentation = APIUtil.getDocumentation(artifact);
}
} catch (RegistryException e) {
handleException("Failed to get documentation details", e);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
handleException("Failed to get documentation details", e);
}
return documentation;
}
public String getDocumentationContent(APIIdentifier identifier, String documentationName)
throws APIManagementException {
String contentPath = APIUtil.getAPIDocPath(identifier) +
APIConstants.INLINE_DOCUMENT_CONTENT_DIR + RegistryConstants.PATH_SEPARATOR +
documentationName;
String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
Registry registry;
boolean isTenantFlowStarted = false;
try {
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
PrivilegedCarbonContext.startTenantFlow();
isTenantFlowStarted = true;
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
}
/* If the API provider is a tenant, load tenant registry*/
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
int id = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
registry = ServiceReferenceHolder.getInstance().
getRegistryService().getGovernanceSystemRegistry(id);
} else {
if (this.tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(this.tenantDomain)) {
registry = ServiceReferenceHolder.getInstance().
getRegistryService().getGovernanceUserRegistry(identifier.getProviderName(), MultitenantConstants.SUPER_TENANT_ID);
} else {
registry = this.registry;
}
}
if (registry.resourceExists(contentPath)) {
Resource docContent = registry.get(contentPath);
Object content = docContent.getContent();
if (content != null) {
return new String((byte[]) docContent.getContent(), Charset.defaultCharset());
}
}
} catch (RegistryException e) {
String msg = "No document content found for documentation: "
+ documentationName + " of API: "+identifier.getApiName();
handleException(msg, e);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
handleException("Failed to get ddocument content found for documentation: "
+ documentationName + " of API: "+identifier.getApiName(), e);
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
return null;
}
public Subscriber getSubscriberById(String accessToken) throws APIManagementException {
return apiMgtDAO.getSubscriberById(accessToken);
}
public boolean isContextExist(String context) throws APIManagementException {
// Since we don't have tenant in the APIM table, we do the filtering using this hack
if(context!=null && context.startsWith("/t/"))
context = context.replace("/t/" + MultitenantUtils.getTenantDomainFromUrl(context),""); //removing prefix
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
context = "/t/" + tenantDomain + context;
}
return apiMgtDAO.isContextExist(context);
}
public boolean isScopeKeyExist(String scopeKey, int tenantid) throws APIManagementException {
return apiMgtDAO.isScopeKeyExist(scopeKey, tenantid);
}
public boolean isScopeKeyAssigned(APIIdentifier identifier, String scopeKey, int tenantid)
throws APIManagementException {
return apiMgtDAO.isScopeKeyAssigned(identifier, scopeKey, tenantid);
}
public boolean isApiNameExist(String apiName) throws APIManagementException {
String tenantName = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
tenantName = tenantDomain;
}
return apiMgtDAO.isApiNameExist(apiName, tenantName);
}
public void addSubscriber(String username, String groupingId)
throws APIManagementException {
Subscriber subscriber = new Subscriber(username);
subscriber.setSubscribedDate(new Date());
//TODO : need to set the proper email
subscriber.setEmail("");
try {
int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
.getTenantId(MultitenantUtils.getTenantDomain(username));
subscriber.setTenantId(tenantId);
apiMgtDAO.addSubscriber(subscriber, groupingId);
//Add a default application once subscriber is added
addDefaultApplicationForSubscriber(subscriber);
} catch (APIManagementException e) {
handleException("Error while adding the subscriber " + subscriber.getName(), e);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
handleException("Error while adding the subscriber " + subscriber.getName(), e);
}
}
/**
* Add default application on the first time a subscriber is added to the database
* @param subscriber Subscriber
*
* @throws APIManagementException if an error occurs while adding default application
*/
private void addDefaultApplicationForSubscriber (Subscriber subscriber) throws APIManagementException {
Application defaultApp = new Application(APIConstants.DEFAULT_APPLICATION_NAME, subscriber);
if (APIUtil.isEnabledUnlimitedTier()) {
defaultApp.setTier(APIConstants.UNLIMITED_TIER);
} else {
Map<String, Tier> throttlingTiers = APIUtil.getTiers(APIConstants.TIER_APPLICATION_TYPE,
MultitenantUtils.getTenantDomain(subscriber.getName()));
Set<Tier> tierValueList = new HashSet<Tier>(throttlingTiers.values());
List<Tier> sortedTierList = APIUtil.sortTiers(tierValueList);
defaultApp.setTier(sortedTierList.get(0).getName());
}
//application will not be shared within the group
defaultApp.setGroupId("");
apiMgtDAO.addApplication(defaultApp, subscriber.getName());
}
public void updateSubscriber(Subscriber subscriber)
throws APIManagementException {
apiMgtDAO.updateSubscriber(subscriber);
}
public Subscriber getSubscriber(int subscriberId)
throws APIManagementException {
return apiMgtDAO.getSubscriber(subscriberId);
}
public ResourceFile getIcon(APIIdentifier identifier) throws APIManagementException {
String artifactPath = APIConstants.API_IMAGE_LOCATION + RegistryConstants.PATH_SEPARATOR +
identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR +
identifier.getApiName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion();
String thumbPath = artifactPath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_ICON_IMAGE;
try {
if (registry.resourceExists(thumbPath)) {
Resource res = registry.get(thumbPath);
return new ResourceFile(res.getContentStream(), res.getMediaType());
}
} catch (RegistryException e) {
handleException("Error while loading API icon from the registry", e);
}
return null;
}
public Set<API> getSubscriberAPIs(Subscriber subscriber) throws APIManagementException {
SortedSet<API> apiSortedSet = new TreeSet<API>(new APINameComparator());
Set<SubscribedAPI> subscribedAPIs = apiMgtDAO.getSubscribedAPIs(subscriber, null);
boolean isTenantFlowStarted = false;
try {
if(tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)){
isTenantFlowStarted = true;
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
}
for (SubscribedAPI subscribedAPI : subscribedAPIs) {
String apiPath = APIUtil.getAPIPath(subscribedAPI.getApiId());
Resource resource;
try {
resource = registry.get(apiPath);
GenericArtifactManager artifactManager = new GenericArtifactManager(registry, APIConstants.API_KEY);
GenericArtifact artifact = artifactManager.getGenericArtifact(
resource.getUUID());
API api = APIUtil.getAPI(artifact, registry);
if (api != null) {
apiSortedSet.add(api);
}
} catch (RegistryException e) {
handleException("Failed to get APIs for subscriber: " + subscriber.getName(), e);
}
}
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
return apiSortedSet;
}
/**
* Returns the corresponding application given the uuid
* @param uuid uuid of the Application
* @return it will return Application corresponds to the uuid provided.
* @throws APIManagementException
*/
public Application getApplicationByUUID(String uuid) throws APIManagementException {
return apiMgtDAO.getApplicationByUUID(uuid);
}
/** returns the SubscribedAPI object which is related to the UUID
*
* @param uuid UUID of Subscription
* @return SubscribedAPI object which is related to the UUID
* @throws APIManagementException
*/
public SubscribedAPI getSubscriptionByUUID(String uuid) throws APIManagementException {
return apiMgtDAO.getSubscriptionByUUID(uuid);
}
protected final void handleException(String msg, Exception e) throws APIManagementException {
log.error(msg, e);
throw new APIManagementException(msg, e);
}
protected final void handleException(String msg) throws APIManagementException {
log.error(msg);
throw new APIManagementException(msg);
}
protected final void handleResourceAlreadyExistsException(String msg) throws APIMgtResourceAlreadyExistsException {
log.error(msg);
throw new APIMgtResourceAlreadyExistsException(msg);
}
protected final void handleResourceNotFoundException(String msg) throws APIMgtResourceNotFoundException {
log.error(msg);
throw new APIMgtResourceNotFoundException(msg);
}
protected final void handlePolicyNotFoundException(String msg) throws PolicyNotFoundException {
log.error(msg);
throw new PolicyNotFoundException(msg);
}
protected final void handleBlockConditionNotFoundException(String msg) throws BlockConditionNotFoundException {
log.error(msg);
throw new BlockConditionNotFoundException(msg);
}
public boolean isApplicationTokenExists(String accessToken) throws APIManagementException {
return apiMgtDAO.isAccessTokenExists(accessToken);
}
public boolean isApplicationTokenRevoked(String accessToken) throws APIManagementException {
return apiMgtDAO.isAccessTokenRevoked(accessToken);
}
public APIKey getAccessTokenData(String accessToken) throws APIManagementException {
return apiMgtDAO.getAccessTokenData(accessToken);
}
public Map<Integer, APIKey> searchAccessToken(String searchType, String searchTerm, String loggedInUser)
throws APIManagementException {
if (searchType == null) {
return apiMgtDAO.getAccessTokens(searchTerm);
} else {
if ("User".equalsIgnoreCase(searchType)) {
return apiMgtDAO.getAccessTokensByUser(searchTerm, loggedInUser);
} else if ("Before".equalsIgnoreCase(searchType)) {
return apiMgtDAO.getAccessTokensByDate(searchTerm, false, loggedInUser);
} else if ("After".equalsIgnoreCase(searchType)) {
return apiMgtDAO.getAccessTokensByDate(searchTerm, true, loggedInUser);
} else {
return apiMgtDAO.getAccessTokens(searchTerm);
}
}
}
public Set<APIIdentifier> getAPIByAccessToken(String accessToken) throws APIManagementException{
return apiMgtDAO.getAPIByAccessToken(accessToken);
}
public API getAPI(APIIdentifier identifier,APIIdentifier oldIdentifier, String oldContext) throws
APIManagementException {
String apiPath = APIUtil.getAPIPath(identifier);
try {
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry,
APIConstants.API_KEY);
Resource apiResource = registry.get(apiPath);
String artifactId = apiResource.getUUID();
if (artifactId == null) {
throw new APIManagementException("artifact id is null for : " + apiPath);
}
GenericArtifact apiArtifact = artifactManager.getGenericArtifact(artifactId);
return APIUtil.getAPI(apiArtifact, registry,oldIdentifier, oldContext);
} catch (RegistryException e) {
handleException("Failed to get API from : " + apiPath, e);
return null;
}
}
@Override
public Set<Tier> getAllTiers() throws APIManagementException {
Set<Tier> tiers = new TreeSet<Tier>(new TierNameComparator());
Map<String, Tier> tierMap;
if (tenantId == MultitenantConstants.INVALID_TENANT_ID) {
tierMap = APIUtil.getAllTiers();
} else {
boolean isTenantFlowStarted = false;
try {
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
PrivilegedCarbonContext.startTenantFlow();
isTenantFlowStarted = true;
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
}
tierMap = APIUtil.getAllTiers(tenantId);
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
tiers.addAll(tierMap.values());
return tiers;
}
@Override
public Set<Tier> getAllTiers(String tenantDomain) throws APIManagementException {
Set<Tier> tiers = new TreeSet<Tier>(new TierNameComparator());
Map<String, Tier> tierMap;
boolean isTenantFlowStarted = false;
try {
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
PrivilegedCarbonContext.startTenantFlow();
isTenantFlowStarted = true;
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
}
int requestedTenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
if (requestedTenantId == MultitenantConstants.SUPER_TENANT_ID
|| requestedTenantId == MultitenantConstants.INVALID_TENANT_ID) {
tierMap = APIUtil.getAllTiers();
} else {
tierMap = APIUtil.getAllTiers(requestedTenantId);
}
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
tiers.addAll(tierMap.values());
return tiers;
}
/**
* Returns a list of pre-defined # {@link org.wso2.carbon.apimgt.api.model.Tier} in the system.
*
* @return Set<Tier>
*/
public Set<Tier> getTiers() throws APIManagementException {
Set<Tier> tiers = new TreeSet<Tier>(new TierNameComparator());
Map<String, Tier> tierMap;
if(!APIUtil.isAdvanceThrottlingEnabled()) {
if (tenantId == MultitenantConstants.INVALID_TENANT_ID) {
tierMap = APIUtil.getTiers();
} else {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
tierMap = APIUtil.getTiers(tenantId);
PrivilegedCarbonContext.endTenantFlow();
}
tiers.addAll(tierMap.values());
} else {
tierMap = APIUtil.getTiersFromPolicies(PolicyConstants.POLICY_LEVEL_SUB, tenantId);
tiers.addAll(tierMap.values());
}
return tiers;
}
/**
* Returns a list of pre-defined # {@link org.wso2.carbon.apimgt.api.model.Tier} in the system.
*
* @return Set<Tier>
*/
public Set<Tier> getTiers(String tenantDomain) throws APIManagementException {
Set<Tier> tiers = new TreeSet<Tier>(new TierNameComparator());
Map<String, Tier> tierMap;
if(!APIUtil.isAdvanceThrottlingEnabled()) {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
int requestedTenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
if (requestedTenantId == MultitenantConstants.SUPER_TENANT_ID
|| requestedTenantId == MultitenantConstants.INVALID_TENANT_ID) {
tierMap = APIUtil.getTiers();
} else {
tierMap = APIUtil.getTiers(requestedTenantId);
}
tiers.addAll(tierMap.values());
PrivilegedCarbonContext.endTenantFlow();
} else {
tierMap = APIUtil.getTiersFromPolicies(PolicyConstants.POLICY_LEVEL_SUB, tenantId);
tiers.addAll(tierMap.values());
}
return tiers;
}
/**
* Returns a list of pre-defined # {@link org.wso2.carbon.apimgt.api.model.Tier} in the system.
*
* @param tierType type of the tiers (api,resource ot application)
* @param username current logged user
* @return Set<Tier> return list of tier names
* @throws APIManagementException APIManagementException if failed to get the predefined tiers
*/
public Set<Tier> getTiers(int tierType, String username) throws APIManagementException {
Set<Tier> tiers = new TreeSet<Tier>(new TierNameComparator());
String tenantDomain = MultitenantUtils.getTenantDomain(username);
Map<String, Tier> tierMap;
if(!APIUtil.isAdvanceThrottlingEnabled()) {
tierMap = APIUtil.getTiers(tierType, tenantDomain);
tiers.addAll(tierMap.values());
} else {
int tenantIdFromUsername = APIUtil.getTenantId(username);
if (tierType == APIConstants.TIER_API_TYPE) {
tierMap = APIUtil.getTiersFromPolicies(PolicyConstants.POLICY_LEVEL_SUB, tenantIdFromUsername);
} else if (tierType == APIConstants.TIER_RESOURCE_TYPE) {
tierMap = APIUtil.getTiersFromPolicies(PolicyConstants.POLICY_LEVEL_API, tenantIdFromUsername);
} else if (tierType == APIConstants.TIER_APPLICATION_TYPE) {
tierMap = APIUtil.getTiersFromPolicies(PolicyConstants.POLICY_LEVEL_APP, tenantIdFromUsername);
} else {
throw new APIManagementException("No such a tier type : " + tierType);
}
tiers.addAll(tierMap.values());
}
return tiers;
}
/**
* Returns a list of pre-defined # {@link org.wso2.carbon.apimgt.api.model.Tier} in the system.
*
* @return Map<String, String>
*/
public Map<String,String> getTenantDomainMappings(String tenantDomain, String apiType) throws APIManagementException {
return APIUtil.getDomainMappings(tenantDomain, apiType);
}
public boolean isDuplicateContextTemplate(String contextTemplate) throws APIManagementException{
if (contextTemplate != null && contextTemplate.startsWith("/t/"))
contextTemplate =
contextTemplate.replace("/t/" + MultitenantUtils.getTenantDomainFromUrl(contextTemplate), "");
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
contextTemplate = "/t/" + tenantDomain + contextTemplate;
}
return apiMgtDAO.isDuplicateContextTemplate(contextTemplate);
}
public Policy[] getPolicies(String username, String level) throws APIManagementException {
Policy[] policies = null;
int tenantID = APIUtil.getTenantId(username);
if(PolicyConstants.POLICY_LEVEL_API.equals(level)){
policies = apiMgtDAO.getAPIPolicies(tenantID);
} else if(PolicyConstants.POLICY_LEVEL_APP.equals(level)){
policies = apiMgtDAO.getApplicationPolicies(tenantID);
} else if(PolicyConstants.POLICY_LEVEL_SUB.equals(level)){
policies = apiMgtDAO.getSubscriptionPolicies(tenantID);
} else if(PolicyConstants.POLICY_LEVEL_GLOBAL.equals(level)){
policies = apiMgtDAO.getGlobalPolicies(tenantID);
}
return policies;
}
@Override
public Map<String,Object> searchPaginatedAPIs(String searchQuery, String requestedTenantDomain,
int start,int end, boolean isLazyLoad) throws APIManagementException {
Map<String,Object> result = new HashMap<String,Object>();
boolean isTenantFlowStarted = false;
try {
boolean isTenantMode=(requestedTenantDomain != null);
if (isTenantMode && !org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(requestedTenantDomain)) {
isTenantFlowStarted = true;
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(requestedTenantDomain, true);
} else {
requestedTenantDomain = org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
isTenantFlowStarted = true;
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(requestedTenantDomain, true);
}
Registry userRegistry;
int tenantIDLocal = 0;
String userNameLocal = this.username;
if ((isTenantMode && this.tenantDomain==null) || (isTenantMode && isTenantDomainNotMatching(requestedTenantDomain))) {//Tenant store anonymous mode
tenantIDLocal = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
.getTenantId(requestedTenantDomain);
userRegistry = ServiceReferenceHolder.getInstance().
getRegistryService().getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantIDLocal);
userNameLocal = CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME;
} else {
userRegistry = this.registry;
tenantIDLocal = tenantId;
}
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userNameLocal);
if (searchQuery.startsWith(APIConstants.DOCUMENTATION_SEARCH_TYPE_PREFIX)) {
Map<Documentation, API> apiDocMap =
APIUtil.searchAPIsByDoc(userRegistry, tenantIDLocal, userNameLocal, searchQuery.split("=")[1],
APIConstants.STORE_CLIENT);
result.put("apis", apiDocMap);
/*Pagination for Document search results is not supported yet, hence length is sent as end-start*/
if (apiDocMap.isEmpty()) {
result.put("length", 0);
} else {
result.put("length", end-start);
}
} else if (searchQuery.startsWith(APIConstants.SUBCONTEXT_SEARCH_TYPE_PREFIX)) {
result = APIUtil.searchAPIsByURLPattern(userRegistry, searchQuery.split("=")[1], start,end);
} else {
result = searchPaginatedAPIs(userRegistry, searchQuery, start, end, isLazyLoad);
}
} catch (Exception e) {
handleException("Failed to Search APIs", e);
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
return result;
}
/**
* Returns API Search result based on the provided query. This search method supports '&' based concatenate
* search in multiple fields.
* @param registry
* @param searchQuery. Ex: provider=*admin*&version=*1*
* @return API result
* @throws APIManagementException
*/
public Map<String,Object> searchPaginatedAPIs(Registry registry, String searchQuery, int start, int end,
boolean limitAttributes) throws APIManagementException {
SortedSet<API> apiSet = new TreeSet<API>(new APINameComparator());
List<API> apiList = new ArrayList<API>();
Map<String,Object> result=new HashMap<String, Object>();
int totalLength=0;
boolean isMore = false;
try {
String paginationLimit = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
.getAPIManagerConfiguration()
.getFirstProperty(APIConstants.API_STORE_APIS_PER_PAGE);
// If the Config exists use it to set the pagination limit
final int maxPaginationLimit;
if (paginationLimit != null) {
// The additional 1 added to the maxPaginationLimit is to help us determine if more
// APIs may exist so that we know that we are unable to determine the actual total
// API count. We will subtract this 1 later on so that it does not interfere with
// the logic of the rest of the application
int pagination = Integer.parseInt(paginationLimit);
// Because the store jaggery pagination logic is 10 results per a page we need to set pagination
// limit to at least 11 or the pagination done at this level will conflict with the store pagination
// leading to some of the APIs not being displayed
if (pagination < 11) {
pagination = 11;
log.warn("Value of '" + APIConstants.API_STORE_APIS_PER_PAGE + "' is too low, defaulting to 11");
}
maxPaginationLimit = start + pagination + 1;
}
// Else if the config is not specified we go with default functionality and load all
else {
maxPaginationLimit = Integer.MAX_VALUE;
}
PaginationContext.init(start, end, "ASC", APIConstants.API_OVERVIEW_NAME, maxPaginationLimit);
List<GovernanceArtifact> governanceArtifacts = GovernanceUtils.findGovernanceArtifacts(searchQuery,
registry, APIConstants.API_RXT_MEDIA_TYPE);
totalLength = PaginationContext.getInstance().getLength();
boolean isFound = true;
if (governanceArtifacts == null || governanceArtifacts.size() == 0) {
if (searchQuery.contains(APIConstants.API_OVERVIEW_PROVIDER)) {
searchQuery = searchQuery.replaceAll(APIConstants.API_OVERVIEW_PROVIDER, APIConstants.API_OVERVIEW_OWNER);
governanceArtifacts = GovernanceUtils.findGovernanceArtifacts(searchQuery,
registry, APIConstants.API_RXT_MEDIA_TYPE);
if (governanceArtifacts == null || governanceArtifacts.size() == 0) {
isFound = false;
}
} else {
isFound = false;
}
}
if (!isFound) {
result.put("apis", apiSet);
result.put("length", 0);
result.put("isMore", isMore);
return result;
}
// Check to see if we can speculate that there are more APIs to be loaded
if (maxPaginationLimit == totalLength) {
isMore = true; // More APIs exist, cannot determine total API count without incurring perf hit
--totalLength; // Remove the additional 1 added earlier when setting max pagination limit
}
int tempLength =0;
for (GovernanceArtifact artifact : governanceArtifacts) {
API resultAPI;
if (limitAttributes) {
resultAPI = APIUtil.getAPI(artifact);
} else {
resultAPI = APIUtil.getAPI(artifact, registry);
}
if (resultAPI != null) {
apiList.add(resultAPI);
}
String status = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
// Ensure the APIs returned matches the length, there could be an additional API
// returned due incrementing the pagination limit when getting from registry
tempLength++;
if (tempLength >= totalLength){
break;
}
}
apiSet.addAll(apiList);
} catch (RegistryException e) {
handleException("Failed to search APIs with type", e);
} finally {
PaginationContext.destroy();
}
result.put("apis",apiSet);
result.put("length",totalLength);
result.put("isMore", isMore);
return result;
}
}
| Fixing APIMANAGER-5370
| components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/AbstractAPIManager.java | Fixing APIMANAGER-5370 |
|
Java | apache-2.0 | 30c1ae53daa09674c3790d2fccb61c0038c16172 | 0 | RocketRaccoon/rest-assured,janusnic/rest-assured,rest-assured/rest-assured,BenSeverson/rest-assured,nishantkashyap/rest-assured-1,RocketRaccoon/rest-assured,suvarnaraju/rest-assured,lucamilanesio/rest-assured,rest-assured/rest-assured,eeichinger/rest-assured,paweld2/rest-assured,eeichinger/rest-assured,MattGong/rest-assured,MattGong/rest-assured,janusnic/rest-assured,jayway/rest-assured,Igor-Petrov/rest-assured,suvarnaraju/rest-assured,pxy0592/rest-assured,caravenase/rest-assured,Igor-Petrov/rest-assured,caravenase/rest-assured,dushmis/rest-assured,camunda-third-party/rest-assured,caravena-nisum-com/rest-assured,rest-assured/rest-assured,paweld2/rest-assured,Navrattan-Yadav/rest-assured,pxy0592/rest-assured,camunda-third-party/rest-assured,BenSeverson/rest-assured,nishantkashyap/rest-assured-1,jayway/rest-assured,dushmis/rest-assured,caravena-nisum-com/rest-assured,Navrattan-Yadav/rest-assured | /*
* Copyright 2011 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 com.jayway.restassured.itest.java;
import com.jayway.restassured.itest.java.support.WithJetty;
import com.jayway.restassured.path.json.JsonPath;
import com.jayway.restassured.path.xml.XmlPath;
import org.hamcrest.Matchers;
import org.junit.Test;
import static com.jayway.restassured.RestAssured.*;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
public class PresentationExamplesITest extends WithJetty {
@Test
public void simpleJsonValidation() throws Exception {
given().
param("firstName", "John").
param("lastName", "Doe").
expect().
body("greeting.firstName", equalTo("John")).
body("greeting.lastName", equalTo("Doe")).
when().
get("/greetJSON");
}
@Test
public void simpleXmlValidation() throws Exception {
given().
param("firstName", "John").
param("lastName", "Doe").
expect().
body("greeting.firstName", equalTo("John")).
body("greeting.lastName", equalTo("Doe")).
when().
get("/greetXML");
}
@Test
public void simpleJsonValidationWithJsonPath() throws Exception {
final String body = get("/greetJSON?firstName=John&lastName=Doe").asString();
final JsonPath json = new JsonPath(body).setRoot("greeting");
final String firstName = json.getString("firstName");
final String lastName = json.getString("lastName");
assertThat(firstName, equalTo("John"));
assertThat(lastName, equalTo("Doe"));
}
@Test
public void simpleXmlValidationWithXmlPath() throws Exception {
final String body = get("/greetXML?firstName=John&lastName=Doe").asString();
final XmlPath xml = new XmlPath(body).setRoot("greeting");
final String firstName = xml.getString("firstName");
final String lastName = xml.getString("lastName");
assertThat(firstName, equalTo("John"));
assertThat(lastName, equalTo("Doe"));
}
@Test
public void advancedJsonValidation() throws Exception {
expect().
statusCode(allOf(greaterThanOrEqualTo(200), lessThanOrEqualTo(300))).
root("store.book").
body("findAll { book -> book.price < 10 }.title", hasItems("Sayings of the Century", "Moby Dick")).
body("author.collect { it.length() }.sum()", Matchers.equalTo(53)).
when().
get("/jsonStore");
}
} | examples/rest-assured-itest-java/src/test/java/com/jayway/restassured/itest/java/PresentationExamplesITest.java | /*
* Copyright 2011 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 com.jayway.restassured.itest.java;
import com.jayway.restassured.itest.java.support.WithJetty;
import com.jayway.restassured.path.json.JsonPath;
import com.jayway.restassured.path.xml.XmlPath;
import org.junit.Test;
import static com.jayway.restassured.RestAssured.get;
import static com.jayway.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
public class PresentationExamplesITest extends WithJetty {
@Test
public void simpleJsonValidation() throws Exception {
given().
param("firstName", "John").
param("lastName", "Doe").
expect().
body("greeting.firstName", equalTo("John")).
body("greeting.lastName", equalTo("Doe")).
when().
get("/greetJSON");
}
@Test
public void simpleXmlValidation() throws Exception {
given().
param("firstName", "John").
param("lastName", "Doe").
expect().
body("greeting.firstName", equalTo("John")).
body("greeting.lastName", equalTo("Doe")).
when().
get("/greetXML");
}
@Test
public void simpleJsonValidationWithJsonPath() throws Exception {
final String body = get("/greetJSON?firstName=John&lastName=Doe").asString();
final JsonPath json = new JsonPath(body).setRoot("greeting");
final String firstName = json.getString("firstName");
final String lastName = json.getString("lastName");
assertThat(firstName, equalTo("John"));
assertThat(lastName, equalTo("Doe"));
}
@Test
public void simpleXmlValidationWithXmlPath() throws Exception {
final String body = get("/greetXML?firstName=John&lastName=Doe").asString();
final XmlPath xml = new XmlPath(body).setRoot("greeting");
final String firstName = xml.getString("firstName");
final String lastName = xml.getString("lastName");
assertThat(firstName, equalTo("John"));
assertThat(lastName, equalTo("Doe"));
}
} | Added new presentation example
| examples/rest-assured-itest-java/src/test/java/com/jayway/restassured/itest/java/PresentationExamplesITest.java | Added new presentation example |
|
Java | apache-2.0 | 5773ecc0f231c6dfa2172a277d8b742627c79e8b | 0 | Addepar/buck,facebook/buck,JoelMarcey/buck,JoelMarcey/buck,facebook/buck,JoelMarcey/buck,zpao/buck,nguyentruongtho/buck,facebook/buck,zpao/buck,Addepar/buck,zpao/buck,Addepar/buck,nguyentruongtho/buck,nguyentruongtho/buck,JoelMarcey/buck,facebook/buck,nguyentruongtho/buck,Addepar/buck,Addepar/buck,JoelMarcey/buck,JoelMarcey/buck,facebook/buck,JoelMarcey/buck,Addepar/buck,nguyentruongtho/buck,kageiit/buck,Addepar/buck,Addepar/buck,Addepar/buck,JoelMarcey/buck,zpao/buck,kageiit/buck,zpao/buck,kageiit/buck,JoelMarcey/buck,Addepar/buck,kageiit/buck,Addepar/buck,kageiit/buck,zpao/buck,JoelMarcey/buck,facebook/buck,kageiit/buck,nguyentruongtho/buck,Addepar/buck,JoelMarcey/buck,JoelMarcey/buck,Addepar/buck,facebook/buck,zpao/buck,kageiit/buck,nguyentruongtho/buck,JoelMarcey/buck | /*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.core.sourcepath.resolver.impl;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import com.facebook.buck.core.exceptions.HumanReadableException;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.BuildTargetFactory;
import com.facebook.buck.core.model.BuildTargetWithOutputs;
import com.facebook.buck.core.model.ImmutableBuildTargetWithOutputs;
import com.facebook.buck.core.model.OutputLabel;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.rules.BuildRule;
import com.facebook.buck.core.rules.BuildRuleResolver;
import com.facebook.buck.core.rules.TestBuildRuleParams;
import com.facebook.buck.core.rules.impl.FakeBuildRule;
import com.facebook.buck.core.rules.impl.PathReferenceRule;
import com.facebook.buck.core.rules.impl.PathReferenceRuleWithMultipleOutputs;
import com.facebook.buck.core.rules.resolver.impl.TestActionGraphBuilder;
import com.facebook.buck.core.sourcepath.ArchiveMemberSourcePath;
import com.facebook.buck.core.sourcepath.DefaultBuildTargetSourcePath;
import com.facebook.buck.core.sourcepath.ExplicitBuildTargetSourcePath;
import com.facebook.buck.core.sourcepath.FakeSourcePath;
import com.facebook.buck.core.sourcepath.ForwardingBuildTargetSourcePath;
import com.facebook.buck.core.sourcepath.PathSourcePath;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.core.sourcepath.resolver.SourcePathResolverAdapter;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.io.filesystem.impl.FakeProjectFilesystem;
import com.facebook.buck.shell.Genrule;
import com.facebook.buck.shell.GenruleBuilder;
import com.facebook.buck.testutil.MoreAsserts;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class SourcePathResolverTest {
@Rule public final ExpectedException exception = ExpectedException.none();
@Test
public void resolvePathSourcePath() {
ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(new TestActionGraphBuilder()));
Path expectedPath = Paths.get("foo");
SourcePath sourcePath = PathSourcePath.of(projectFilesystem, expectedPath);
assertEquals(expectedPath, pathResolver.getRelativePath(sourcePath));
}
@Test
public void resolveDefaultBuildTargetSourcePathWithNoOutputLabel() {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
Path expectedPath = Paths.get("foo");
BuildTarget buildTarget = BuildTargetFactory.newInstance("//:foo");
BuildRule rule = new PathReferenceRule(buildTarget, new FakeProjectFilesystem(), expectedPath);
graphBuilder.addToIndex(rule);
SourcePath sourcePath = DefaultBuildTargetSourcePath.of(rule.getBuildTarget());
assertEquals(expectedPath, pathResolver.getRelativePath(sourcePath));
}
@Test
public void resolveDefaultBuildTargetSourcePathWithOutputLabel() {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
BuildTarget buildTarget = BuildTargetFactory.newInstance("//:foo");
Path expectedPath = Paths.get("foo").resolve("bar");
BuildRule rule =
new PathReferenceRuleWithMultipleOutputs(
buildTarget,
new FakeProjectFilesystem(),
null,
ImmutableMap.of(new OutputLabel("bar"), expectedPath));
graphBuilder.addToIndex(rule);
BuildTargetWithOutputs buildTargetWithOutputs =
ImmutableBuildTargetWithOutputs.of(buildTarget, new OutputLabel("bar"));
SourcePath sourcePath = DefaultBuildTargetSourcePath.of(buildTargetWithOutputs);
assertEquals(expectedPath, pathResolver.getRelativePath(sourcePath));
}
@Test
public void shouldGetCorrectPathWhenMultipleOutputsAvailable() {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
BuildTarget buildTarget = BuildTargetFactory.newInstance("//:foo");
Path expectedPath = Paths.get("foo").resolve("bar");
BuildRule rule =
new PathReferenceRuleWithMultipleOutputs(
buildTarget,
new FakeProjectFilesystem(),
null,
ImmutableMap.of(
new OutputLabel("baz"),
Paths.get("foo").resolve("baz"),
new OutputLabel("bar"),
expectedPath,
new OutputLabel("qux"),
Paths.get("foo").resolve("qux")));
graphBuilder.addToIndex(rule);
BuildTargetWithOutputs buildTargetWithOutputs =
ImmutableBuildTargetWithOutputs.of(buildTarget, new OutputLabel("bar"));
SourcePath sourcePath = DefaultBuildTargetSourcePath.of(buildTargetWithOutputs);
assertEquals(expectedPath, pathResolver.getRelativePath(sourcePath));
}
@Test
public void cannotResolveBuildTargetWithNonExistentOutputLabel() {
exception.expect(HumanReadableException.class);
exception.expectMessage(containsString("No known output for: //:foo[baz]"));
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
Path path = Paths.get("foo").resolve("bar");
BuildTarget buildTarget = BuildTargetFactory.newInstance("//:foo");
BuildRule rule =
new PathReferenceRuleWithMultipleOutputs(
buildTarget,
new FakeProjectFilesystem(),
path,
ImmutableMap.of(new OutputLabel("bar"), path));
graphBuilder.addToIndex(rule);
BuildTargetWithOutputs buildTargetWithOutputs =
ImmutableBuildTargetWithOutputs.of(buildTarget, new OutputLabel("baz"));
SourcePath sourcePath = DefaultBuildTargetSourcePath.of(buildTargetWithOutputs);
pathResolver.getRelativePath(sourcePath);
}
@Test
public void throwsWhenRequestTargetWithOutputLabelFromRuleThatDoesNotSupportMultipleOutputs() {
exception.expect(IllegalStateException.class);
exception.expectMessage(
containsString(
"Multiple outputs not supported for path_reference_rule target //:foo[bar]"));
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
BuildTarget buildTarget = BuildTargetFactory.newInstance("//:foo");
BuildRule rule =
new PathReferenceRule(buildTarget, new FakeProjectFilesystem(), Paths.get("foo"));
graphBuilder.addToIndex(rule);
BuildTargetWithOutputs buildTargetWithOutputs =
ImmutableBuildTargetWithOutputs.of(buildTarget, new OutputLabel("bar"));
SourcePath sourcePath = DefaultBuildTargetSourcePath.of(buildTargetWithOutputs);
pathResolver.getRelativePath(sourcePath);
}
@Test
public void resolveExplicitBuildTargetSourcePath() {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
Path expectedPath = Paths.get("foo");
FakeBuildRule rule = new FakeBuildRule("//:foo");
rule.setOutputFile("notfoo");
graphBuilder.addToIndex(rule);
SourcePath sourcePath = ExplicitBuildTargetSourcePath.of(rule.getBuildTarget(), expectedPath);
assertEquals(expectedPath, pathResolver.getRelativePath(sourcePath));
}
@Test
public void getRelativePathCanGetRelativePathOfPathSourcePath() {
ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(new TestActionGraphBuilder()));
Path expectedPath = Paths.get("foo");
SourcePath sourcePath = PathSourcePath.of(projectFilesystem, expectedPath);
assertEquals(expectedPath, pathResolver.getRelativePath(sourcePath));
}
@Test
public void relativePathForADefaultBuildTargetSourcePathIsTheRulesOutputPath() {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
FakeBuildRule rule = new FakeBuildRule("//:foo");
rule.setOutputFile("foo");
graphBuilder.addToIndex(rule);
SourcePath sourcePath = DefaultBuildTargetSourcePath.of(rule.getBuildTarget());
assertEquals(rule.getOutputFile(), pathResolver.getRelativePath(sourcePath));
}
@Test
public void testEmptyListAsInputToFilterInputsToCompareToOutput() {
Iterable<SourcePath> sourcePaths = ImmutableList.of();
SourcePathResolverAdapter resolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(new TestActionGraphBuilder()));
Iterable<Path> inputs = resolver.filterInputsToCompareToOutput(sourcePaths);
MoreAsserts.assertIterablesEquals(ImmutableList.<String>of(), inputs);
}
@Test
public void testFilterInputsToCompareToOutputExcludesBuildTargetSourcePaths() {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
FakeBuildRule rule =
new FakeBuildRule(BuildTargetFactory.newInstance("//java/com/facebook:facebook"));
graphBuilder.addToIndex(rule);
Iterable<? extends SourcePath> sourcePaths =
ImmutableList.of(
FakeSourcePath.of("java/com/facebook/Main.java"),
FakeSourcePath.of("java/com/facebook/BuckConfig.java"),
DefaultBuildTargetSourcePath.of(rule.getBuildTarget()),
ExplicitBuildTargetSourcePath.of(rule.getBuildTarget(), Paths.get("foo")),
ForwardingBuildTargetSourcePath.of(rule.getBuildTarget(), FakeSourcePath.of("bar")));
Iterable<Path> inputs = pathResolver.filterInputsToCompareToOutput(sourcePaths);
MoreAsserts.assertIterablesEquals(
"Iteration order should be preserved: results should not be alpha-sorted.",
ImmutableList.of(
Paths.get("java/com/facebook/Main.java"),
Paths.get("java/com/facebook/BuckConfig.java")),
inputs);
}
@Test
public void getSourcePathNameOnPathSourcePath() {
ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
String path = Paths.get("hello/world.txt").toString();
// Test that constructing a PathSourcePath without an explicit name resolves to the
// string representation of the path.
PathSourcePath pathSourcePath1 = FakeSourcePath.of(projectFilesystem, path);
SourcePathResolverAdapter resolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(new TestActionGraphBuilder()));
String actual1 =
resolver.getSourcePathName(BuildTargetFactory.newInstance("//:test"), pathSourcePath1);
assertEquals(path, actual1);
}
@Test
public void getSourcePathNameOnDefaultBuildTargetSourcePath() {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
// Verify that wrapping a genrule in a BuildTargetSourcePath resolves to the output name of
// that genrule.
String out = "test/blah.txt";
Genrule genrule =
GenruleBuilder.newGenruleBuilder(BuildTargetFactory.newInstance("//:genrule"))
.setOut(out)
.build(graphBuilder);
DefaultBuildTargetSourcePath buildTargetSourcePath1 =
DefaultBuildTargetSourcePath.of(genrule.getBuildTarget());
String actual1 =
pathResolver.getSourcePathName(
BuildTargetFactory.newInstance("//:test"), buildTargetSourcePath1);
assertEquals(out, actual1);
// Test that using other BuildRule types resolves to the short name.
BuildTarget fakeBuildTarget = BuildTargetFactory.newInstance("//:fake");
FakeBuildRule fakeBuildRule =
new FakeBuildRule(
fakeBuildTarget, new FakeProjectFilesystem(), TestBuildRuleParams.create());
graphBuilder.addToIndex(fakeBuildRule);
DefaultBuildTargetSourcePath buildTargetSourcePath2 =
DefaultBuildTargetSourcePath.of(fakeBuildRule.getBuildTarget());
String actual2 =
pathResolver.getSourcePathName(
BuildTargetFactory.newInstance("//:test"), buildTargetSourcePath2);
assertEquals(fakeBuildTarget.getShortName(), actual2);
}
@Test
public void getSourcePathNameOnExplicitBuildTargetSourcePath() {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
// Verify that wrapping a genrule in a ExplicitBuildTargetSourcePath resolves to the output name
// of that genrule.
String out = "test/blah.txt";
Genrule genrule =
GenruleBuilder.newGenruleBuilder(BuildTargetFactory.newInstance("//:genrule"))
.setOut(out)
.build(graphBuilder);
ExplicitBuildTargetSourcePath buildTargetSourcePath1 =
ExplicitBuildTargetSourcePath.of(genrule.getBuildTarget(), Paths.get("foo"));
String actual1 =
pathResolver.getSourcePathName(
BuildTargetFactory.newInstance("//:test"), buildTargetSourcePath1);
assertEquals(out, actual1);
BuildTarget fakeBuildTarget = BuildTargetFactory.newInstance("//package:fake");
FakeBuildRule fakeBuildRule =
new FakeBuildRule(
fakeBuildTarget, new FakeProjectFilesystem(), TestBuildRuleParams.create());
graphBuilder.addToIndex(fakeBuildRule);
ExplicitBuildTargetSourcePath buildTargetSourcePath2 =
ExplicitBuildTargetSourcePath.of(
fakeBuildRule.getBuildTarget(),
fakeBuildRule
.getBuildTarget()
.getCellRelativeBasePath()
.getPath()
.toPathDefaultFileSystem()
.resolve("foo/bar"));
String actual2 =
pathResolver.getSourcePathName(
BuildTargetFactory.newInstance("//:test"), buildTargetSourcePath2);
assertEquals(Paths.get("foo", "bar").toString(), actual2);
BuildTarget otherFakeBuildTarget = BuildTargetFactory.newInstance("//package:fake2");
FakeBuildRule otherFakeBuildRule =
new FakeBuildRule(
otherFakeBuildTarget, new FakeProjectFilesystem(), TestBuildRuleParams.create());
graphBuilder.addToIndex(otherFakeBuildRule);
ExplicitBuildTargetSourcePath buildTargetSourcePath3 =
ExplicitBuildTargetSourcePath.of(
otherFakeBuildRule.getBuildTarget(), Paths.get("buck-out/gen/package/foo/bar"));
String actual3 =
pathResolver.getSourcePathName(
BuildTargetFactory.newInstance("//:test"), buildTargetSourcePath3);
assertEquals(Paths.get("foo", "bar").toString(), actual3);
}
@Test
public void getSourcePathNameOnForwardingBuildTargetSourcePath() {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
FakeBuildRule rule = new FakeBuildRule(BuildTargetFactory.newInstance("//package:baz"));
graphBuilder.addToIndex(rule);
// Verify that wrapping a genrule in a ForwardingBuildTargetSourcePath resolves to the output
// name of that genrule.
String out = "test/blah.txt";
Genrule genrule =
GenruleBuilder.newGenruleBuilder(BuildTargetFactory.newInstance("//:genrule"))
.setOut(out)
.build(graphBuilder);
ForwardingBuildTargetSourcePath buildTargetSourcePath1 =
ForwardingBuildTargetSourcePath.of(rule.getBuildTarget(), genrule.getSourcePathToOutput());
String actual1 =
pathResolver.getSourcePathName(
BuildTargetFactory.newInstance("//:test"), buildTargetSourcePath1);
assertEquals(out, actual1);
ForwardingBuildTargetSourcePath buildTargetSourcePath2 =
ForwardingBuildTargetSourcePath.of(rule.getBuildTarget(), FakeSourcePath.of("foo/bar"));
String actual2 =
pathResolver.getSourcePathName(
BuildTargetFactory.newInstance("//:test"), buildTargetSourcePath2);
assertEquals(Paths.get("foo", "bar").toString(), actual2);
BuildTarget otherFakeBuildTarget = BuildTargetFactory.newInstance("//package2:fake2");
FakeBuildRule otherFakeBuildRule =
new FakeBuildRule(
otherFakeBuildTarget, new FakeProjectFilesystem(), TestBuildRuleParams.create());
graphBuilder.addToIndex(otherFakeBuildRule);
ForwardingBuildTargetSourcePath buildTargetSourcePath3 =
ForwardingBuildTargetSourcePath.of(
otherFakeBuildRule.getBuildTarget(), buildTargetSourcePath2);
String actual3 =
pathResolver.getSourcePathName(
BuildTargetFactory.newInstance("//:test"), buildTargetSourcePath3);
assertEquals(Paths.get("foo", "bar").toString(), actual3);
}
@Test(expected = IllegalArgumentException.class)
public void getSourcePathNameOnArchiveMemberSourcePath() {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
String out = "test/blah.jar";
Genrule genrule =
GenruleBuilder.newGenruleBuilder(BuildTargetFactory.newInstance("//:genrule"))
.setOut(out)
.build(graphBuilder);
SourcePath archiveSourcePath = genrule.getSourcePathToOutput();
ArchiveMemberSourcePath archiveMemberSourcePath =
ArchiveMemberSourcePath.of(archiveSourcePath, Paths.get("member"));
pathResolver.getSourcePathName(null, archiveMemberSourcePath);
}
@Test
public void getSourcePathNamesThrowsOnDuplicates() {
ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
BuildTarget target = BuildTargetFactory.newInstance("//:test");
String parameter = "srcs";
PathSourcePath pathSourcePath1 = FakeSourcePath.of(projectFilesystem, "same_name");
PathSourcePath pathSourcePath2 = FakeSourcePath.of(projectFilesystem, "same_name");
exception.expect(HumanReadableException.class);
exception.expectMessage("duplicate entries");
// Try to resolve these source paths, with the same name, together and verify that an
// exception is thrown.
SourcePathResolverAdapter resolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(new TestActionGraphBuilder()));
resolver.getSourcePathNames(
target, parameter, ImmutableList.of(pathSourcePath1, pathSourcePath2));
}
@Test
public void getSourcePathNameExplicitPath() {
ProjectFilesystem filesystem = new FakeProjectFilesystem();
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
BuildRule rule = graphBuilder.addToIndex(new FakeBuildRule("//foo:bar"));
assertThat(
pathResolver.getSourcePathName(
rule.getBuildTarget(),
ExplicitBuildTargetSourcePath.of(
rule.getBuildTarget(),
filesystem.getBuckPaths().getGenDir().resolve("foo").resolve("something.cpp"))),
Matchers.equalTo("something.cpp"));
}
@Test
public void getSourcePathNamesWithExplicitPathsAvoidesDuplicates() {
ProjectFilesystem filesystem = new FakeProjectFilesystem();
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
BuildRule rule = graphBuilder.addToIndex(new FakeBuildRule("//foo:bar"));
SourcePath sourcePath1 =
ExplicitBuildTargetSourcePath.of(
rule.getBuildTarget(),
filesystem.getBuckPaths().getGenDir().resolve("foo").resolve("name1"));
SourcePath sourcePath2 =
ExplicitBuildTargetSourcePath.of(
rule.getBuildTarget(),
filesystem.getBuckPaths().getGenDir().resolve("foo").resolve("name2"));
pathResolver.getSourcePathNames(
rule.getBuildTarget(), "srcs", ImmutableList.of(sourcePath1, sourcePath2));
}
@Test(expected = IllegalStateException.class)
public void getRelativePathCanOnlyReturnARelativePath() {
BuildRuleResolver resolver = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(resolver));
PathSourcePath path =
FakeSourcePath.of(
new FakeProjectFilesystem(), Paths.get("cheese").toAbsolutePath().toString());
pathResolver.getRelativePath(path);
}
}
| test/com/facebook/buck/core/sourcepath/resolver/impl/SourcePathResolverTest.java | /*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.core.sourcepath.resolver.impl;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.facebook.buck.core.exceptions.HumanReadableException;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.BuildTargetFactory;
import com.facebook.buck.core.model.BuildTargetWithOutputs;
import com.facebook.buck.core.model.ImmutableBuildTargetWithOutputs;
import com.facebook.buck.core.model.OutputLabel;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.rules.BuildRule;
import com.facebook.buck.core.rules.BuildRuleResolver;
import com.facebook.buck.core.rules.TestBuildRuleParams;
import com.facebook.buck.core.rules.impl.FakeBuildRule;
import com.facebook.buck.core.rules.impl.PathReferenceRule;
import com.facebook.buck.core.rules.impl.PathReferenceRuleWithMultipleOutputs;
import com.facebook.buck.core.rules.resolver.impl.TestActionGraphBuilder;
import com.facebook.buck.core.sourcepath.ArchiveMemberSourcePath;
import com.facebook.buck.core.sourcepath.DefaultBuildTargetSourcePath;
import com.facebook.buck.core.sourcepath.ExplicitBuildTargetSourcePath;
import com.facebook.buck.core.sourcepath.FakeSourcePath;
import com.facebook.buck.core.sourcepath.ForwardingBuildTargetSourcePath;
import com.facebook.buck.core.sourcepath.PathSourcePath;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.core.sourcepath.resolver.SourcePathResolverAdapter;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.io.filesystem.impl.FakeProjectFilesystem;
import com.facebook.buck.shell.Genrule;
import com.facebook.buck.shell.GenruleBuilder;
import com.facebook.buck.testutil.MoreAsserts;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class SourcePathResolverTest {
@Rule public final ExpectedException exception = ExpectedException.none();
@Test
public void resolvePathSourcePath() {
ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(new TestActionGraphBuilder()));
Path expectedPath = Paths.get("foo");
SourcePath sourcePath = PathSourcePath.of(projectFilesystem, expectedPath);
assertEquals(expectedPath, pathResolver.getRelativePath(sourcePath));
}
@Test
public void resolveDefaultBuildTargetSourcePathWithNoOutputLabel() {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
Path expectedPath = Paths.get("foo");
BuildTarget buildTarget = BuildTargetFactory.newInstance("//:foo");
BuildRule rule = new PathReferenceRule(buildTarget, new FakeProjectFilesystem(), expectedPath);
graphBuilder.addToIndex(rule);
SourcePath sourcePath = DefaultBuildTargetSourcePath.of(rule.getBuildTarget());
assertEquals(expectedPath, pathResolver.getRelativePath(sourcePath));
}
@Test
public void resolveDefaultBuildTargetSourcePathWithOutputLabel() {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
BuildTarget buildTarget = BuildTargetFactory.newInstance("//:foo");
Path expectedPath = Paths.get("foo").resolve("bar");
BuildRule rule =
new PathReferenceRuleWithMultipleOutputs(
buildTarget,
new FakeProjectFilesystem(),
null,
ImmutableMap.of(new OutputLabel("bar"), expectedPath));
graphBuilder.addToIndex(rule);
BuildTargetWithOutputs buildTargetWithOutputs =
ImmutableBuildTargetWithOutputs.of(buildTarget, new OutputLabel("bar"));
SourcePath sourcePath = DefaultBuildTargetSourcePath.of(buildTargetWithOutputs);
assertEquals(expectedPath, pathResolver.getRelativePath(sourcePath));
}
@Test
public void shouldGetCorrectPathWhenMultipleOutputsAvailable() {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
BuildTarget buildTarget = BuildTargetFactory.newInstance("//:foo");
Path expectedPath = Paths.get("foo").resolve("bar");
BuildRule rule =
new PathReferenceRuleWithMultipleOutputs(
buildTarget,
new FakeProjectFilesystem(),
null,
ImmutableMap.of(
new OutputLabel("baz"),
Paths.get("foo").resolve("baz"),
new OutputLabel("bar"),
expectedPath,
new OutputLabel("qux"),
Paths.get("foo").resolve("qux")));
graphBuilder.addToIndex(rule);
BuildTargetWithOutputs buildTargetWithOutputs =
ImmutableBuildTargetWithOutputs.of(buildTarget, new OutputLabel("bar"));
SourcePath sourcePath = DefaultBuildTargetSourcePath.of(buildTargetWithOutputs);
assertEquals(expectedPath, pathResolver.getRelativePath(sourcePath));
}
@Test
public void cannotResolveBuildTargetWithNonExistentOutputLabel() {
exception.expect(HumanReadableException.class);
exception.expectMessage(containsString("No known output for: //:foo[baz]"));
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
Path path = Paths.get("foo").resolve("bar");
BuildTarget buildTarget = BuildTargetFactory.newInstance("//:foo");
BuildRule rule =
new PathReferenceRuleWithMultipleOutputs(
buildTarget,
new FakeProjectFilesystem(),
path,
ImmutableMap.of(new OutputLabel("bar"), path));
graphBuilder.addToIndex(rule);
BuildTargetWithOutputs buildTargetWithOutputs =
ImmutableBuildTargetWithOutputs.of(buildTarget, new OutputLabel("baz"));
SourcePath sourcePath = DefaultBuildTargetSourcePath.of(buildTargetWithOutputs);
pathResolver.getRelativePath(sourcePath);
}
@Test
public void throwsWhenRequestTargetWithOutputLabelFromRuleThatDoesNotSupportMultipleOutputs() {
exception.expect(IllegalStateException.class);
exception.expectMessage(
containsString(
"Multiple outputs not supported for path_reference_rule target //:foo[bar]"));
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
BuildTarget buildTarget = BuildTargetFactory.newInstance("//:foo");
BuildRule rule =
new PathReferenceRule(buildTarget, new FakeProjectFilesystem(), Paths.get("foo"));
graphBuilder.addToIndex(rule);
BuildTargetWithOutputs buildTargetWithOutputs =
ImmutableBuildTargetWithOutputs.of(buildTarget, new OutputLabel("bar"));
SourcePath sourcePath = DefaultBuildTargetSourcePath.of(buildTargetWithOutputs);
pathResolver.getRelativePath(sourcePath);
}
@Test
public void resolveExplicitBuildTargetSourcePath() {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
Path expectedPath = Paths.get("foo");
FakeBuildRule rule = new FakeBuildRule("//:foo");
rule.setOutputFile("notfoo");
graphBuilder.addToIndex(rule);
SourcePath sourcePath = ExplicitBuildTargetSourcePath.of(rule.getBuildTarget(), expectedPath);
assertEquals(expectedPath, pathResolver.getRelativePath(sourcePath));
}
@Test
public void getRelativePathCanGetRelativePathOfPathSourcePath() {
ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(new TestActionGraphBuilder()));
Path expectedPath = Paths.get("foo");
SourcePath sourcePath = PathSourcePath.of(projectFilesystem, expectedPath);
assertEquals(expectedPath, pathResolver.getRelativePath(sourcePath));
}
@Test
public void relativePathForADefaultBuildTargetSourcePathIsTheRulesOutputPath() {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
FakeBuildRule rule = new FakeBuildRule("//:foo");
rule.setOutputFile("foo");
graphBuilder.addToIndex(rule);
SourcePath sourcePath = DefaultBuildTargetSourcePath.of(rule.getBuildTarget());
assertEquals(rule.getOutputFile(), pathResolver.getRelativePath(sourcePath));
}
@Test
public void testEmptyListAsInputToFilterInputsToCompareToOutput() {
Iterable<SourcePath> sourcePaths = ImmutableList.of();
SourcePathResolverAdapter resolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(new TestActionGraphBuilder()));
Iterable<Path> inputs = resolver.filterInputsToCompareToOutput(sourcePaths);
MoreAsserts.assertIterablesEquals(ImmutableList.<String>of(), inputs);
}
@Test
public void testFilterInputsToCompareToOutputExcludesBuildTargetSourcePaths() {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
FakeBuildRule rule =
new FakeBuildRule(BuildTargetFactory.newInstance("//java/com/facebook:facebook"));
graphBuilder.addToIndex(rule);
Iterable<? extends SourcePath> sourcePaths =
ImmutableList.of(
FakeSourcePath.of("java/com/facebook/Main.java"),
FakeSourcePath.of("java/com/facebook/BuckConfig.java"),
DefaultBuildTargetSourcePath.of(rule.getBuildTarget()),
ExplicitBuildTargetSourcePath.of(rule.getBuildTarget(), Paths.get("foo")),
ForwardingBuildTargetSourcePath.of(rule.getBuildTarget(), FakeSourcePath.of("bar")));
Iterable<Path> inputs = pathResolver.filterInputsToCompareToOutput(sourcePaths);
MoreAsserts.assertIterablesEquals(
"Iteration order should be preserved: results should not be alpha-sorted.",
ImmutableList.of(
Paths.get("java/com/facebook/Main.java"),
Paths.get("java/com/facebook/BuckConfig.java")),
inputs);
}
@Test
public void getSourcePathNameOnPathSourcePath() {
ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
String path = Paths.get("hello/world.txt").toString();
// Test that constructing a PathSourcePath without an explicit name resolves to the
// string representation of the path.
PathSourcePath pathSourcePath1 = FakeSourcePath.of(projectFilesystem, path);
SourcePathResolverAdapter resolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(new TestActionGraphBuilder()));
String actual1 =
resolver.getSourcePathName(BuildTargetFactory.newInstance("//:test"), pathSourcePath1);
assertEquals(path, actual1);
}
@Test
public void getSourcePathNameOnDefaultBuildTargetSourcePath() {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
// Verify that wrapping a genrule in a BuildTargetSourcePath resolves to the output name of
// that genrule.
String out = "test/blah.txt";
Genrule genrule =
GenruleBuilder.newGenruleBuilder(BuildTargetFactory.newInstance("//:genrule"))
.setOut(out)
.build(graphBuilder);
DefaultBuildTargetSourcePath buildTargetSourcePath1 =
DefaultBuildTargetSourcePath.of(genrule.getBuildTarget());
String actual1 =
pathResolver.getSourcePathName(
BuildTargetFactory.newInstance("//:test"), buildTargetSourcePath1);
assertEquals(out, actual1);
// Test that using other BuildRule types resolves to the short name.
BuildTarget fakeBuildTarget = BuildTargetFactory.newInstance("//:fake");
FakeBuildRule fakeBuildRule =
new FakeBuildRule(
fakeBuildTarget, new FakeProjectFilesystem(), TestBuildRuleParams.create());
graphBuilder.addToIndex(fakeBuildRule);
DefaultBuildTargetSourcePath buildTargetSourcePath2 =
DefaultBuildTargetSourcePath.of(fakeBuildRule.getBuildTarget());
String actual2 =
pathResolver.getSourcePathName(
BuildTargetFactory.newInstance("//:test"), buildTargetSourcePath2);
assertEquals(fakeBuildTarget.getShortName(), actual2);
}
@Test
public void getSourcePathNameOnExplicitBuildTargetSourcePath() {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
// Verify that wrapping a genrule in a ExplicitBuildTargetSourcePath resolves to the output name
// of that genrule.
String out = "test/blah.txt";
Genrule genrule =
GenruleBuilder.newGenruleBuilder(BuildTargetFactory.newInstance("//:genrule"))
.setOut(out)
.build(graphBuilder);
ExplicitBuildTargetSourcePath buildTargetSourcePath1 =
ExplicitBuildTargetSourcePath.of(genrule.getBuildTarget(), Paths.get("foo"));
String actual1 =
pathResolver.getSourcePathName(
BuildTargetFactory.newInstance("//:test"), buildTargetSourcePath1);
assertEquals(out, actual1);
BuildTarget fakeBuildTarget = BuildTargetFactory.newInstance("//package:fake");
FakeBuildRule fakeBuildRule =
new FakeBuildRule(
fakeBuildTarget, new FakeProjectFilesystem(), TestBuildRuleParams.create());
graphBuilder.addToIndex(fakeBuildRule);
ExplicitBuildTargetSourcePath buildTargetSourcePath2 =
ExplicitBuildTargetSourcePath.of(
fakeBuildRule.getBuildTarget(),
fakeBuildRule
.getBuildTarget()
.getCellRelativeBasePath()
.getPath()
.toPathDefaultFileSystem()
.resolve("foo/bar"));
String actual2 =
pathResolver.getSourcePathName(
BuildTargetFactory.newInstance("//:test"), buildTargetSourcePath2);
assertEquals(Paths.get("foo", "bar").toString(), actual2);
BuildTarget otherFakeBuildTarget = BuildTargetFactory.newInstance("//package:fake2");
FakeBuildRule otherFakeBuildRule =
new FakeBuildRule(
otherFakeBuildTarget, new FakeProjectFilesystem(), TestBuildRuleParams.create());
graphBuilder.addToIndex(otherFakeBuildRule);
ExplicitBuildTargetSourcePath buildTargetSourcePath3 =
ExplicitBuildTargetSourcePath.of(
otherFakeBuildRule.getBuildTarget(), Paths.get("buck-out/gen/package/foo/bar"));
String actual3 =
pathResolver.getSourcePathName(
BuildTargetFactory.newInstance("//:test"), buildTargetSourcePath3);
assertEquals(Paths.get("foo", "bar").toString(), actual3);
}
@Test
public void getSourcePathNameOnForwardingBuildTargetSourcePath() {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
FakeBuildRule rule = new FakeBuildRule(BuildTargetFactory.newInstance("//package:baz"));
graphBuilder.addToIndex(rule);
// Verify that wrapping a genrule in a ForwardingBuildTargetSourcePath resolves to the output
// name of that genrule.
String out = "test/blah.txt";
Genrule genrule =
GenruleBuilder.newGenruleBuilder(BuildTargetFactory.newInstance("//:genrule"))
.setOut(out)
.build(graphBuilder);
ForwardingBuildTargetSourcePath buildTargetSourcePath1 =
ForwardingBuildTargetSourcePath.of(rule.getBuildTarget(), genrule.getSourcePathToOutput());
String actual1 =
pathResolver.getSourcePathName(
BuildTargetFactory.newInstance("//:test"), buildTargetSourcePath1);
assertEquals(out, actual1);
ForwardingBuildTargetSourcePath buildTargetSourcePath2 =
ForwardingBuildTargetSourcePath.of(rule.getBuildTarget(), FakeSourcePath.of("foo/bar"));
String actual2 =
pathResolver.getSourcePathName(
BuildTargetFactory.newInstance("//:test"), buildTargetSourcePath2);
assertEquals(Paths.get("foo", "bar").toString(), actual2);
BuildTarget otherFakeBuildTarget = BuildTargetFactory.newInstance("//package2:fake2");
FakeBuildRule otherFakeBuildRule =
new FakeBuildRule(
otherFakeBuildTarget, new FakeProjectFilesystem(), TestBuildRuleParams.create());
graphBuilder.addToIndex(otherFakeBuildRule);
ForwardingBuildTargetSourcePath buildTargetSourcePath3 =
ForwardingBuildTargetSourcePath.of(
otherFakeBuildRule.getBuildTarget(), buildTargetSourcePath2);
String actual3 =
pathResolver.getSourcePathName(
BuildTargetFactory.newInstance("//:test"), buildTargetSourcePath3);
assertEquals(Paths.get("foo", "bar").toString(), actual3);
}
@Test(expected = IllegalArgumentException.class)
public void getSourcePathNameOnArchiveMemberSourcePath() {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
String out = "test/blah.jar";
Genrule genrule =
GenruleBuilder.newGenruleBuilder(BuildTargetFactory.newInstance("//:genrule"))
.setOut(out)
.build(graphBuilder);
SourcePath archiveSourcePath = genrule.getSourcePathToOutput();
ArchiveMemberSourcePath archiveMemberSourcePath =
ArchiveMemberSourcePath.of(archiveSourcePath, Paths.get("member"));
pathResolver.getSourcePathName(null, archiveMemberSourcePath);
}
@Test
public void getSourcePathNamesThrowsOnDuplicates() {
ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
BuildTarget target = BuildTargetFactory.newInstance("//:test");
String parameter = "srcs";
PathSourcePath pathSourcePath1 = FakeSourcePath.of(projectFilesystem, "same_name");
PathSourcePath pathSourcePath2 = FakeSourcePath.of(projectFilesystem, "same_name");
// Try to resolve these source paths, with the same name, together and verify that an
// exception is thrown.
try {
SourcePathResolverAdapter resolver =
new SourcePathResolverAdapter(
DefaultSourcePathResolver.from(new TestActionGraphBuilder()));
resolver.getSourcePathNames(
target, parameter, ImmutableList.of(pathSourcePath1, pathSourcePath2));
fail("expected to throw");
} catch (HumanReadableException e) {
assertTrue(e.getMessage().contains("duplicate entries"));
}
}
@Test
public void getSourcePathNameExplicitPath() {
ProjectFilesystem filesystem = new FakeProjectFilesystem();
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
BuildRule rule = graphBuilder.addToIndex(new FakeBuildRule("//foo:bar"));
assertThat(
pathResolver.getSourcePathName(
rule.getBuildTarget(),
ExplicitBuildTargetSourcePath.of(
rule.getBuildTarget(),
filesystem.getBuckPaths().getGenDir().resolve("foo").resolve("something.cpp"))),
Matchers.equalTo("something.cpp"));
}
@Test
public void getSourcePathNamesWithExplicitPathsAvoidesDuplicates() {
ProjectFilesystem filesystem = new FakeProjectFilesystem();
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(graphBuilder));
BuildRule rule = graphBuilder.addToIndex(new FakeBuildRule("//foo:bar"));
SourcePath sourcePath1 =
ExplicitBuildTargetSourcePath.of(
rule.getBuildTarget(),
filesystem.getBuckPaths().getGenDir().resolve("foo").resolve("name1"));
SourcePath sourcePath2 =
ExplicitBuildTargetSourcePath.of(
rule.getBuildTarget(),
filesystem.getBuckPaths().getGenDir().resolve("foo").resolve("name2"));
pathResolver.getSourcePathNames(
rule.getBuildTarget(), "srcs", ImmutableList.of(sourcePath1, sourcePath2));
}
@Test(expected = IllegalStateException.class)
public void getRelativePathCanOnlyReturnARelativePath() {
BuildRuleResolver resolver = new TestActionGraphBuilder();
SourcePathResolverAdapter pathResolver =
new SourcePathResolverAdapter(DefaultSourcePathResolver.from(resolver));
PathSourcePath path =
FakeSourcePath.of(
new FakeProjectFilesystem(), Paths.get("cheese").toAbsolutePath().toString());
pathResolver.getRelativePath(path);
}
}
| Use expectedException
Reviewed By: irenewchen
shipit-source-id: 1c439ea836
| test/com/facebook/buck/core/sourcepath/resolver/impl/SourcePathResolverTest.java | Use expectedException |
|
Java | bsd-2-clause | 031f9176ba5d65de68dc7f5f4a731cc32b725d1a | 0 | motech-implementations/nms-reporting-fix | package org.motechproject.nms.reportfix.kilkari.constants;
/**
* Constants used by kilkari fixer
*/
public final class KilkariConstants {
/**
* Queries for kilkari reporting lookup
*/
public static final String getCallCountSql = "SELECT count(*) as monthlyCount FROM date_dimension as dd " +
"join subscriber_call_measure as scm on scm.Start_Date_ID = dd.ID " +
"where DimMonth = '%s' and DimYear = '%d'";
public static final String getTimeCacheSql = "SELECT ID, FullTime FROM time_dimension";
public static final String getDateCacheSql = "SELECT ID, FullDate from date_dimension";
public static final String getOperatorCacheSql = "SELECT operator_code, ID FROM operator_dimension";
public static final String getMessageDurationCacheSql = "SELECT Campaign_ID, Message_Duration FROM campaign_dimension";
public static final String getCampaignMessageCacheSql = "SELECT Campaign_ID, ID FROM campaign_dimension";
public static final String getSubscriptionPackCacheSql = "SELECT Subscription_Pack, Subscription_Pack_ID FROM subscription_pack_dimension";
public static final String getChannelCacheSql = "SELECT Channel, ID FROM channel_dimension;";
public static final String getSubscriptionInfoSql = "select Subscription_ID, Subscriber_Pack_ID, Start_Date from subscriptions where SubscriptionId = '%s'";
/**
* Query for data insert
*/
public static final String insertCdrRowSql = "INSERT INTO subscriber_call_measure\n"+
"(Subscription_ID, Operator_ID, Subscription_Pack_ID, Campaign_ID, \n"+
"Start_Date_ID, End_Date_ID, Start_Time_ID, End_Time_ID, State_ID, \n"+
"Call_Status, Duration, Service_Option, Percentage_Listened, Call_Source, \n"+
"Subscription_Status, Duration_In_Pulse, Call_Start_Time, Call_End_Time, \n"+
"Attempt_Number, Subscription_Start_Date, msg_duration, modificationDate)\n"+
"VALUES\n"+
"(%d, %d, %d, %d," +
" %d, %d, %d, %d, %s," +
" '%s', %d, %s, %d, '%s'," +
" '%s', %d, '%s', '%s'," +
" %d, '%s', %d, '%s');";
/**
* Query to check if subscription with id exists in reporting already
*/
public static final String getSubscriptionRow = "SELECT count(*) FROM subscriptions WHERE SubscriptionId = '%s'";
/**
* Toggle safe updates on the db (like delete without using primary key) *
* This is currently being used for deleting all call measures for a day while loading CDRs
*/
public static final String setSafeUpdates = "SET SQL_SAFE_UPDATES = %d";
/**
* Used to clear out existing subscriber call records for the day when we process CDR files
*/
public static final String deleteRecordsForDay = "DELETE FROM subscriber_call_measure WHERE Call_Source = 'IVR' AND Start_Date_ID = %d";
/**
* used to get missing subscription info from production db
*/
public static final String fetchSubscription = "SELECT * FROM nms_subscriptions WHERE subscriptionId = '%s'";
/**
* This is used to backfill the missing subscription info from CDR & prod
*/
public static final String fetchMissingSubscriptionInfo = "SELECT \n" +
"\ts.id as Subscriber_ID,\n" +
"\tIF (sp.type = 'PREGNANCY', m.name, c.name) as Name,\n" +
"\tl.name as Language,\n" +
"\tm.dateOfBirth as Date_Of_Birth,\n" +
"\tIF (sp.type = 'PREGNANCY', m.state_id_OID, c.state_id_OID) as State_ID,\n" +
"\tIF (sp.type = 'PREGNANCY', m.district_id_OID, c.district_id_OID) as District_ID,\n" +
"\tIF (sp.type = 'PREGNANCY', m.taluka_id_OID, c.taluka_id_OID) as Taluka_ID,\n" +
"\tIF (sp.type = 'PREGNANCY', m.village_id_OID, c.village_id_OID) as Village_ID,\n" +
"\tIF (sp.type = 'PREGNANCY', m.healthBlock_id_OID, c.healthBlock_id_OID) as HBlock_ID,\n" +
"\tIF (sp.type = 'PREGNANCY', m.healthFacility_id_OID, c.healthFacility_id_OID) as HFacility_ID,\n" +
"\tIF (sp.type = 'PREGNANCY', m.healthSubFacility_id_OID, c.healthSubFacility_id_OID) as HSub_Facility_ID,\n" +
"\ts.lastMenstrualPeriod as Lmp,\n" +
" ss.id as Subscription_ID,\n" +
" sp.type as PackType,\n" +
" ss.origin as Channel,\n" +
" null as Operator,\n" +
" ss.status as Subscription_Status,\n" +
" ss.startDate as Start_Date,\n" +
" null as Old_Subscription_ID,\n" +
" s.callingNumber as MS_ISDN,\n" +
" ss.creationDate as Creation_Time,\n" +
" null as Old_Start_Date,\n" +
" ss.activationDate as Activation_Date\n" +
"from nms_subscriptions as ss\n" +
"join nms_subscription_packs as sp on sp.id = ss.subscriptionPack_id_OID\n" +
"join nms_subscribers as s on s.id = ss.subscriber_id_OID\n" +
"left join nms_languages as l on l.id = s.language_id_OID\n" +
"left join nms_mcts_mothers as m on m.id = s.mother_id_OID\n" +
"left join nms_mcts_children as c on c.id = s.child_id_OID\n" +
"where subscriptionId = '%s'";
/**
* Used to insert missing subscriber in the db. Note that we use insert ignore because of terrible ETL logic
* combined with terrible bugs in how subscriber id is managed in reporting. All that we care about here is the
* location info contained and nothing else probably matters...except when it does #fml
*/
public static final String insertMissingSubscriber = "INSERT IGNORE INTO subscribers\n" +
"(Subscriber_ID, Name, Language, Age_Of_Beneficiary, Date_Of_Birth, " +
"State_ID, District_ID, Taluka_ID, Village_ID, HBlock_ID, HFacility_ID, HSub_Facility_ID, " +
"Last_Modified_Time, Lmp)\n" +
"VALUES\n" +
"(%d, '%s', '%s', %s, '%s', " +
"%d, %d, %d, %d, %d, %d, %d, " +
"'%s', '%s');";
/**
* Used to insert missing subscriptions in the reporting db.
* In an ideal world wih intelligent life, we wouldn't use ignore in the insert but we got swindled.
* Fool me once, can't get fooled again!
*/
public static final String insertMissingSubscription = "INSERT IGNORE INTO subscriptions\n" +
"(Subscription_ID, Subscriber_ID, Subscriber_Pack_ID, Channel_ID, Operator_ID, " +
"Last_Modified_Time, Subscription_Status, Start_Date, Old_Subscription_ID, MS_ISDN, SubscriptionId, " +
"Creation_Time, Old_Start_Date, Activation_Date)\n" +
"VALUES\n" +
"(%d, %d, %d, %d, %d, " +
"'%s', '%s', '%s', '%s', %d, '%s', " +
"'%s', %s, '%s')";
}
| src/main/java/org/motechproject/nms/reportfix/kilkari/constants/KilkariConstants.java | package org.motechproject.nms.reportfix.kilkari.constants;
/**
* Constants used by kilkari fixer
*/
public final class KilkariConstants {
/**
* Queries for kilkari reporting lookup
*/
public static final String getCallCountSql = "SELECT count(*) as monthlyCount FROM date_dimension as dd " +
"join subscriber_call_measure as scm on scm.Start_Date_ID = dd.ID " +
"where DimMonth = '%s' and DimYear = '%d'";
public static final String getTimeCacheSql = "SELECT ID, FullTime FROM time_dimension";
public static final String getDateCacheSql = "SELECT ID, FullDate from date_dimension";
public static final String getOperatorCacheSql = "SELECT operator_code, ID FROM operator_dimension";
public static final String getMessageDurationCacheSql = "SELECT Campaign_ID, Message_Duration FROM campaign_dimension";
public static final String getCampaignMessageCacheSql = "SELECT Campaign_ID, ID FROM campaign_dimension";
public static final String getSubscriptionPackCacheSql = "SELECT Subscription_Pack, Subscription_Pack_ID FROM subscription_pack_dimension";
public static final String getChannelCacheSql = "SELECT Channel, ID FROM channel_dimension;";
public static final String getSubscriptionInfoSql = "select Subscription_ID, Subscriber_Pack_ID, Start_Date from subscriptions where SubscriptionId = '%s'";
/**
* Query for data insert
*/
public static final String insertCdrRowSql = "INSERT INTO subscriber_call_measure\n"+
"(Subscription_ID, Operator_ID, Subscription_Pack_ID, Campaign_ID, \n"+
"Start_Date_ID, End_Date_ID, Start_Time_ID, End_Time_ID, State_ID, \n"+
"Call_Status, Duration, Service_Option, Percentage_Listened, Call_Source, \n"+
"Subscription_Status, Duration_In_Pulse, Call_Start_Time, Call_End_Time, \n"+
"Attempt_Number, Subscription_Start_Date, msg_duration, modificationDate)\n"+
"VALUES\n"+
"(%d, %d, %d, %d," +
" %d, %d, %d, %d, %s," +
" '%s', %d, %s, %d, '%s'," +
" '%s', %d, '%s', '%s'," +
" %d, '%s', %d, '%s');";
/**
* Query to check if subscription with id exists in reporting already
*/
public static final String getSubscriptionRow = "SELECT count(*) FROM subscriptions WHERE SubscriptionId = '%s'";
/**
* Toggle safe updates on the db (like delete without using primary key) *
* This is currently being used for deleting all call measures for a day while loading CDRs
*/
public static final String setSafeUpdates = "SET SQL_SAFE_UPDATES = %d";
/**
* Used to clear out existing subscriber call records for the day when we process CDR files
*/
public static final String deleteRecordsForDay = "DELETE FROM subscriber_call_measure WHERE Start_Date_ID = %d";
/**
* used to get missing subscription info from production db
*/
public static final String fetchSubscription = "SELECT * FROM nms_subscriptions WHERE subscriptionId = '%s'";
/**
* This is used to backfill the missing subscription info from CDR & prod
*/
public static final String fetchMissingSubscriptionInfo = "SELECT \n" +
"\ts.id as Subscriber_ID,\n" +
"\tIF (sp.type = 'PREGNANCY', m.name, c.name) as Name,\n" +
"\tl.name as Language,\n" +
"\tm.dateOfBirth as Date_Of_Birth,\n" +
"\tIF (sp.type = 'PREGNANCY', m.state_id_OID, c.state_id_OID) as State_ID,\n" +
"\tIF (sp.type = 'PREGNANCY', m.district_id_OID, c.district_id_OID) as District_ID,\n" +
"\tIF (sp.type = 'PREGNANCY', m.taluka_id_OID, c.taluka_id_OID) as Taluka_ID,\n" +
"\tIF (sp.type = 'PREGNANCY', m.village_id_OID, c.village_id_OID) as Village_ID,\n" +
"\tIF (sp.type = 'PREGNANCY', m.healthBlock_id_OID, c.healthBlock_id_OID) as HBlock_ID,\n" +
"\tIF (sp.type = 'PREGNANCY', m.healthFacility_id_OID, c.healthFacility_id_OID) as HFacility_ID,\n" +
"\tIF (sp.type = 'PREGNANCY', m.healthSubFacility_id_OID, c.healthSubFacility_id_OID) as HSub_Facility_ID,\n" +
"\ts.lastMenstrualPeriod as Lmp,\n" +
" ss.id as Subscription_ID,\n" +
" sp.type as PackType,\n" +
" ss.origin as Channel,\n" +
" null as Operator,\n" +
" ss.status as Subscription_Status,\n" +
" ss.startDate as Start_Date,\n" +
" null as Old_Subscription_ID,\n" +
" s.callingNumber as MS_ISDN,\n" +
" ss.creationDate as Creation_Time,\n" +
" null as Old_Start_Date,\n" +
" ss.activationDate as Activation_Date\n" +
"from nms_subscriptions as ss\n" +
"join nms_subscription_packs as sp on sp.id = ss.subscriptionPack_id_OID\n" +
"join nms_subscribers as s on s.id = ss.subscriber_id_OID\n" +
"left join nms_languages as l on l.id = s.language_id_OID\n" +
"left join nms_mcts_mothers as m on m.id = s.mother_id_OID\n" +
"left join nms_mcts_children as c on c.id = s.child_id_OID\n" +
"where subscriptionId = '%s'";
/**
* Used to insert missing subscriber in the db. Note that we use insert ignore because of terrible ETL logic
* combined with terrible bugs in how subscriber id is managed in reporting. All that we care about here is the
* location info contained and nothing else probably matters...except when it does #fml
*/
public static final String insertMissingSubscriber = "INSERT IGNORE INTO subscribers\n" +
"(Subscriber_ID, Name, Language, Age_Of_Beneficiary, Date_Of_Birth, " +
"State_ID, District_ID, Taluka_ID, Village_ID, HBlock_ID, HFacility_ID, HSub_Facility_ID, " +
"Last_Modified_Time, Lmp)\n" +
"VALUES\n" +
"(%d, '%s', '%s', %s, '%s', " +
"%d, %d, %d, %d, %d, %d, %d, " +
"'%s', '%s');";
/**
* Used to insert missing subscriptions in the reporting db.
* In an ideal world wih intelligent life, we wouldn't use ignore in the insert but we got swindled.
* Fool me once, can't get fooled again!
*/
public static final String insertMissingSubscription = "INSERT IGNORE INTO subscriptions\n" +
"(Subscription_ID, Subscriber_ID, Subscriber_Pack_ID, Channel_ID, Operator_ID, " +
"Last_Modified_Time, Subscription_Status, Start_Date, Old_Subscription_ID, MS_ISDN, SubscriptionId, " +
"Creation_Time, Old_Start_Date, Activation_Date)\n" +
"VALUES\n" +
"(%d, %d, %d, %d, %d, " +
"'%s', '%s', '%s', '%s', %d, '%s', " +
"'%s', %s, '%s')";
}
| Adding IVR call source to delete records for day clause
| src/main/java/org/motechproject/nms/reportfix/kilkari/constants/KilkariConstants.java | Adding IVR call source to delete records for day clause |
|
Java | bsd-3-clause | 35f7395c46d515542dce2a230cef112dd79b7b79 | 0 | bigdawg-istc/bigdawg,bigdawg-istc/bigdawg,bigdawg-istc/bigdawg,bigdawg-istc/bigdawg,bigdawg-istc/bigdawg,bigdawg-istc/bigdawg,bigdawg-istc/bigdawg,bigdawg-istc/bigdawg | package istc.bigdawg.stream;
import istc.bigdawg.exceptions.AlertException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;
import javax.json.JsonException;
import org.apache.commons.lang.StringUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
* @author aelmore A dead simple in memory class for storing stream data
* objects.
*/
public class MemStreamDAO extends StreamDAO {
private List<ClientAlert> clientAlerts;
private List<DBAlert> dbAlerts;
private List<AlertEvent> events;
private AtomicInteger clientCounter = new AtomicInteger();
private AtomicInteger dbCounter = new AtomicInteger();
private AtomicInteger eventCounter = new AtomicInteger();
public static final MemStreamDAO INSTANCE = new MemStreamDAO();
public static StreamDAO getStreamDAO() {
return INSTANCE;
}
private MemStreamDAO() {
clientAlerts = new Vector<ClientAlert>();
dbAlerts = new Vector<DBAlert>();
events = new Vector<AlertEvent>();
clientCounter = new AtomicInteger();
dbCounter = new AtomicInteger();
eventCounter = new AtomicInteger();
}
public void reset() {
clientAlerts = new Vector<ClientAlert>();
dbAlerts = new Vector<DBAlert>();
events = new Vector<AlertEvent>();
clientCounter = new AtomicInteger();
dbCounter = new AtomicInteger();
eventCounter = new AtomicInteger();
}
@Override
public DBAlert createOrGetDBAlert(String storedProc, boolean oneTime) {
for (DBAlert a : this.dbAlerts) {
if (a.stroredProc.equalsIgnoreCase(storedProc)) {
return a;
}
}
DBAlert a = new DBAlert(dbCounter.getAndIncrement(), storedProc,
oneTime, "null");
dbAlerts.add(a);
return a;
}
@Override
public ClientAlert createClientAlert(int dbAlertId, boolean push,
boolean oneTime, String pushURL) throws AlertException {
DBAlert dbAlert = null;
for (DBAlert a : this.dbAlerts) {
if (a.dbAlertID == dbAlertId) {
dbAlert = a;
}
}
if (dbAlert == null) {
throw new AlertException("Missing DB alert " + dbAlertId);
}
for (ClientAlert a : this.clientAlerts) {
if ((a.pushURL != null && a.pushURL.equalsIgnoreCase(pushURL))
&& a.active) {
a.push = push;
a.oneTime = oneTime;
return a;
}
}
ClientAlert alert = new ClientAlert(clientCounter.getAndIncrement(),
dbAlertId, push, oneTime, true, false, pushURL);
clientAlerts.add(alert);
return alert;
}
@Override
public List<AlertEvent> addAlertEvent(int dbAlertId, String body) {
AlertEvent event = new AlertEvent(eventCounter.getAndIncrement(),
dbAlertId, body);
events.add(event);
List<AlertEvent> clientsToNotify = new ArrayList<AlertEvent>();
for (ClientAlert a : this.clientAlerts) {
if (a.dbAlertID == dbAlertId && a.active) {
// found a match
clientsToNotify.add(new AlertEvent(a.clientAlertID, dbAlertId, body));
}
}
return clientsToNotify;
}
@Override
public List<PushNotify> updatePullsAndGetPushURLS(List<AlertEvent> alerts) {
List<PushNotify> urls = new ArrayList<PushNotify>();
for (AlertEvent event : alerts) {
for (ClientAlert a: this.clientAlerts)
if (a.clientAlertID == event.alertID) {
// found a match
if (a.push) {
urls.add(new PushNotify(a.pushURL, event.body));
if (a.oneTime) {
a.active = false;
}
} else {
// pull
a.unseenPulls.add(event.body);
a.lastPullTime = new Date();
}
}
}
return urls;
}
@Override
public String checkForNewPull(int clientAlertId) {
for (ClientAlert a : this.clientAlerts) {
if (a.clientAlertID == clientAlertId && a.active && !a.push
&& !a.unseenPulls.isEmpty()) {
// disable if onetime
if (a.oneTime)
a.active = false;
// We have seen it
String ret = null;
if (a.unseenPulls.size()==1)
ret = a.unseenPulls.toString();
else if (a.unseenPulls.size()>1){
JSONArray data = null;
for (String e : a.unseenPulls){
try{
if (data == null){
data = (JSONArray)new JSONParser().parse(e);
} else {
data.addAll((JSONArray)new JSONParser().parse(e));
}
} catch (ParseException e1) {
e1.printStackTrace();
return e1.toString();
}
}
JSONObject obj = new JSONObject();
obj.put("data", data);
ret =obj.toString();
}
a.unseenPulls.clear();
return ret;
}
}
return "None";
}
@Override
public List<DBAlert> getDBAlerts() {
return dbAlerts;
}
@Override
public List<ClientAlert> getActiveClientAlerts() {
List<ClientAlert> cas = new ArrayList<ClientAlert>();
for (ClientAlert a : this.clientAlerts) {
if (a.active) {
cas.add(a);
}
}
return cas;
}
}
| src/main/java/istc/bigdawg/stream/MemStreamDAO.java | package istc.bigdawg.stream;
import istc.bigdawg.exceptions.AlertException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;
import javax.json.JsonException;
import org.apache.commons.lang.StringUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
* @author aelmore A dead simple in memory class for storing stream data
* objects.
*/
public class MemStreamDAO extends StreamDAO {
private List<ClientAlert> clientAlerts;
private List<DBAlert> dbAlerts;
private List<AlertEvent> events;
private AtomicInteger clientCounter = new AtomicInteger();
private AtomicInteger dbCounter = new AtomicInteger();
private AtomicInteger eventCounter = new AtomicInteger();
public static final MemStreamDAO INSTANCE = new MemStreamDAO();
public static StreamDAO getStreamDAO() {
return INSTANCE;
}
private MemStreamDAO() {
clientAlerts = new Vector<ClientAlert>();
dbAlerts = new Vector<DBAlert>();
events = new Vector<AlertEvent>();
clientCounter = new AtomicInteger();
dbCounter = new AtomicInteger();
eventCounter = new AtomicInteger();
}
public void reset() {
clientAlerts = new Vector<ClientAlert>();
dbAlerts = new Vector<DBAlert>();
events = new Vector<AlertEvent>();
clientCounter = new AtomicInteger();
dbCounter = new AtomicInteger();
eventCounter = new AtomicInteger();
}
@Override
public DBAlert createOrGetDBAlert(String storedProc, boolean oneTime) {
for (DBAlert a : this.dbAlerts) {
if (a.stroredProc.equalsIgnoreCase(storedProc)) {
return a;
}
}
DBAlert a = new DBAlert(dbCounter.getAndIncrement(), storedProc,
oneTime, "null");
dbAlerts.add(a);
return a;
}
@Override
public ClientAlert createClientAlert(int dbAlertId, boolean push,
boolean oneTime, String pushURL) throws AlertException {
DBAlert dbAlert = null;
for (DBAlert a : this.dbAlerts) {
if (a.dbAlertID == dbAlertId) {
dbAlert = a;
}
}
if (dbAlert == null) {
throw new AlertException("Missing DB alert " + dbAlertId);
}
for (ClientAlert a : this.clientAlerts) {
if ((a.pushURL != null && a.pushURL.equalsIgnoreCase(pushURL))
&& a.active) {
a.push = push;
a.oneTime = oneTime;
return a;
}
}
ClientAlert alert = new ClientAlert(clientCounter.getAndIncrement(),
dbAlertId, push, oneTime, true, false, pushURL);
clientAlerts.add(alert);
return alert;
}
@Override
public List<AlertEvent> addAlertEvent(int dbAlertId, String body) {
AlertEvent event = new AlertEvent(eventCounter.getAndIncrement(),
dbAlertId, body);
events.add(event);
List<AlertEvent> clientsToNotify = new ArrayList<AlertEvent>();
for (ClientAlert a : this.clientAlerts) {
if (a.dbAlertID == dbAlertId && a.active) {
// found a match
clientsToNotify.add(new AlertEvent(a.clientAlertID, dbAlertId, body));
}
}
return clientsToNotify;
}
@Override
public List<PushNotify> updatePullsAndGetPushURLS(List<AlertEvent> alerts) {
List<PushNotify> urls = new ArrayList<PushNotify>();
for (AlertEvent event : alerts) {
for (ClientAlert a: this.clientAlerts)
if (a.clientAlertID == event.alertID) {
// found a match
if (a.push) {
urls.add(new PushNotify(a.pushURL, event.body));
if (a.oneTime) {
a.active = false;
}
} else {
// pull
System.out.println("TODO merge requests");
//TODO two arrays that should be joined
a.unseenPulls.add(event.body);
System.out.println(StringUtils.join(a.unseenPulls,","));
a.lastPullTime = new Date();
}
}
}
return urls;
}
@Override
public String checkForNewPull(int clientAlertId) {
for (ClientAlert a : this.clientAlerts) {
if (a.clientAlertID == clientAlertId && a.active && !a.push
&& !a.unseenPulls.isEmpty()) {
// disable if onetime
if (a.oneTime)
a.active = false;
// We have seen it
String ret = null;
if (a.unseenPulls.size()==1)
ret = a.unseenPulls.toString();
else if (a.unseenPulls.size()>1){
JSONArray data = null;
for (String e : a.unseenPulls){
try{
if (data == null){
data = (JSONArray)new JSONParser().parse(e);
} else {
data.addAll((JSONArray)new JSONParser().parse(e));
}
} catch (ParseException e1) {
e1.printStackTrace();
return e1.toString();
}
}
JSONObject obj = new JSONObject();
obj.put("data", data);
ret =obj.toString();
}
a.unseenPulls.clear();
return ret;
}
}
return "None";
}
@Override
public List<DBAlert> getDBAlerts() {
return dbAlerts;
}
@Override
public List<ClientAlert> getActiveClientAlerts() {
List<ClientAlert> cas = new ArrayList<ClientAlert>();
for (ClientAlert a : this.clientAlerts) {
if (a.active) {
cas.add(a);
}
}
return cas;
}
}
| more quiet
| src/main/java/istc/bigdawg/stream/MemStreamDAO.java | more quiet |
|
Java | bsd-3-clause | fbcc752e1e8b83302d778b5e96ab3b428eb93b00 | 0 | mokoka/grassroot-platform,PaballoDitshego/grassroot-platform,PaballoDitshego/grassroot-platform,mokoka/grassroot-platform,grassrootza/grassroot-platform,mokoka/grassroot-platform,grassrootza/grassroot-platform,PaballoDitshego/grassroot-platform,mokoka/grassroot-platform,PaballoDitshego/grassroot-platform,grassrootza/grassroot-platform | package za.org.grassroot.core.domain;
public interface UidIdentifiable {
JpaEntityType getJpaEntityType();
String getUid();
Long getId();
/**
* Returns group this entity belongs to, which can be this very entity if it is group itself.
* @return group itself, or group this entity belongs to
*/
default Group resolveGroup() {
UidIdentifiable currentEntity = this;
while (!currentEntity.getJpaEntityType().equals(JpaEntityType.GROUP)) {
switch (currentEntity.getJpaEntityType()) {
case LOGBOOK:
currentEntity = ((LogBook) currentEntity).getParent();
break;
case MEETING:
currentEntity = ((Meeting) currentEntity).getParent();
break;
case VOTE:
currentEntity = ((Vote) currentEntity).getParent();
break;
default:
throw new UnsupportedOperationException("Invalid " + JpaEntityType.class.getSimpleName() +
" " + currentEntity.getJpaEntityType() + "; " + currentEntity);
}
}
return (Group) currentEntity;
};
}
| grassroot-core/src/main/java/za/org/grassroot/core/domain/UidIdentifiable.java | package za.org.grassroot.core.domain;
public interface UidIdentifiable {
JpaEntityType getJpaEntityType();
String getUid();
Long getId();
/**
* Returns group this entity belongs to, which can be this very entity if it is group itself.
* @return group itself, or group this entity belongs to
*/
default Group resolveGroup() {
UidIdentifiable currentEntity = this;
while (!currentEntity.getJpaEntityType().equals(JpaEntityType.GROUP)) {
switch (currentEntity.getJpaEntityType()) {
case LOGBOOK:
currentEntity = ((LogBook) currentEntity).getParent();
break;
case MEETING:
currentEntity = ((Meeting) currentEntity).getParent();
break;
case VOTE:
currentEntity = ((Meeting) currentEntity).getParent();
break;
default:
throw new UnsupportedOperationException("Invalid " + JpaEntityType.class.getSimpleName() +
" " + currentEntity.getJpaEntityType() + "; " + currentEntity);
}
}
return (Group) currentEntity;
};
}
| small casting fix
| grassroot-core/src/main/java/za/org/grassroot/core/domain/UidIdentifiable.java | small casting fix |
|
Java | bsd-3-clause | 3ed872902e102f818603d17ca8502ca0b9dfbf10 | 0 | dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk | /*
* Copyright (c) 2004-2019, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project 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.hisp.dhis.android.core.trackedentity;
import org.hisp.dhis.android.core.arch.api.executors.RxAPICallExecutor;
import org.hisp.dhis.android.core.arch.call.D2CallWithProgress;
import org.hisp.dhis.android.core.arch.call.D2Progress;
import org.hisp.dhis.android.core.arch.call.D2ProgressManager;
import org.hisp.dhis.android.core.arch.repositories.collection.ReadOnlyWithDownloadObjectRepository;
import org.hisp.dhis.android.core.data.api.OuMode;
import org.hisp.dhis.android.core.organisationunit.OrganisationUnit;
import org.hisp.dhis.android.core.resource.Resource;
import org.hisp.dhis.android.core.resource.ResourceHandler;
import org.hisp.dhis.android.core.systeminfo.DHISVersionManager;
import org.hisp.dhis.android.core.systeminfo.SystemInfo;
import org.hisp.dhis.android.core.user.UserOrganisationUnitLink;
import org.hisp.dhis.android.core.user.UserOrganisationUnitLinkStore;
import org.hisp.dhis.android.core.utils.services.ApiPagingEngine;
import org.hisp.dhis.android.core.utils.services.Paging;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.inject.Inject;
import dagger.Reusable;
import io.reactivex.Observable;
import io.reactivex.Single;
@Reusable
public final class TrackedEntityInstanceWithLimitCallFactory {
private final Resource.Type resourceType = Resource.Type.TRACKED_ENTITY_INSTANCE;
private final RxAPICallExecutor rxCallExecutor;
private final ResourceHandler resourceHandler;
private final UserOrganisationUnitLinkStore userOrganisationUnitLinkStore;
private final ReadOnlyWithDownloadObjectRepository<SystemInfo> systemInfoRepository;
private final DHISVersionManager versionManager;
private final TrackedEntityInstanceRelationshipDownloadAndPersistCallFactory relationshipDownloadCallFactory;
private final TrackedEntityInstancePersistenceCallFactory persistenceCallFactory;
private final TrackedEntityInstancesEndpointCallFactory endpointCallFactory;
// TODO use scheduler for parallel download
// private final Scheduler teiDownloadScheduler = Schedulers.from(Executors.newFixedThreadPool(6));
@Inject
TrackedEntityInstanceWithLimitCallFactory(
RxAPICallExecutor rxCallExecutor,
ResourceHandler resourceHandler,
UserOrganisationUnitLinkStore userOrganisationUnitLinkStore,
ReadOnlyWithDownloadObjectRepository<SystemInfo> systemInfoRepository,
TrackedEntityInstanceRelationshipDownloadAndPersistCallFactory relationshipDownloadCallFactory,
TrackedEntityInstancePersistenceCallFactory persistenceCallFactory,
DHISVersionManager versionManager,
TrackedEntityInstancesEndpointCallFactory endpointCallFactory) {
this.rxCallExecutor = rxCallExecutor;
this.resourceHandler = resourceHandler;
this.userOrganisationUnitLinkStore = userOrganisationUnitLinkStore;
this.systemInfoRepository = systemInfoRepository;
this.versionManager = versionManager;
this.relationshipDownloadCallFactory = relationshipDownloadCallFactory;
this.persistenceCallFactory = persistenceCallFactory;
this.endpointCallFactory = endpointCallFactory;
}
public D2CallWithProgress getCall(final int teiLimit, final boolean limitByOrgUnit) {
D2ProgressManager progressManager = new D2ProgressManager(null);
Observable<D2Progress> concatObservable = Observable.concat(
downloadSystemInfo(progressManager),
downloadTeis(progressManager, teiLimit, limitByOrgUnit),
downloadRelationshipTeis(progressManager),
updateResource(progressManager)
);
return rxCallExecutor.wrapObservableTransactionally(concatObservable, true);
}
private Observable<D2Progress> downloadSystemInfo(D2ProgressManager progressManager) {
return systemInfoRepository.download()
.toSingle(() -> progressManager.increaseProgress(SystemInfo.class, false))
.toObservable();
}
private Observable<D2Progress> downloadTeis(D2ProgressManager progressManager,
int teiLimit,
boolean limitByOrgUnit) {
int pageSize = TeiQuery.builder().build().pageSize();
List<Paging> pagingList = ApiPagingEngine.getPaginationList(pageSize, teiLimit);
String lastUpdated = resourceHandler.getLastUpdated(resourceType);
Observable<List<TrackedEntityInstance>> teiDownloadObservable = limitByOrgUnit
? getTrackedEntityInstancesWithLimitByOrgUnit(lastUpdated, pagingList)
: getTrackedEntityInstancesWithoutLimits(lastUpdated, pagingList);
return teiDownloadObservable.map(
teiList -> {
persistenceCallFactory.getCall(teiList).call();
return progressManager.increaseProgress(TrackedEntityInstance.class, false);
});
}
private Observable<D2Progress> downloadRelationshipTeis(D2ProgressManager progressManager) {
Observable<List<TrackedEntityInstance>> observable = versionManager.is2_29()
? Observable.just(Collections.emptyList())
: relationshipDownloadCallFactory.getCall().toObservable();
return observable.map(
trackedEntityInstances -> progressManager.increaseProgress(TrackedEntityInstance.class, true));
}
private Observable<List<TrackedEntityInstance>> getTrackedEntityInstancesWithLimitByOrgUnit(
String lastUpdated, List<Paging> pagingList) {
return Observable.fromIterable(getOrgUnitUids())
.flatMap(orgUnitUid -> {
TeiQuery.Builder teiQueryBuilder = TeiQuery.builder()
.lastUpdatedStartDate(lastUpdated)
.orgUnits(Collections.singleton(orgUnitUid));
return getTrackedEntityInstancesWithPaging(teiQueryBuilder, pagingList);
// TODO .subscribeOn(teiDownloadScheduler);
});
}
private Observable<List<TrackedEntityInstance>> getTrackedEntityInstancesWithoutLimits(
String lastUpdated, List<Paging> pagingList) {
TeiQuery.Builder teiQueryBuilder = TeiQuery.builder()
.lastUpdatedStartDate(lastUpdated)
.orgUnits(userOrganisationUnitLinkStore.queryRootCaptureOrganisationUnitUids())
.ouMode(OuMode.DESCENDANTS);
return getTrackedEntityInstancesWithPaging(teiQueryBuilder, pagingList);
// TODO .subscribeOn(teiDownloadScheduler);
}
private Observable<List<TrackedEntityInstance>> getTrackedEntityInstancesWithPaging(
TeiQuery.Builder teiQueryBuilder, List<Paging> pagingList) {
Observable<Paging> pagingObservable = Observable.fromIterable(pagingList);
return pagingObservable
.flatMapSingle(paging -> {
teiQueryBuilder.page(paging.page()).pageSize(paging.pageSize());
return endpointCallFactory.getCall(teiQueryBuilder.build()).map(payload ->
new TeiListWithPaging(true, limitTeisForPage(payload.items(), paging), paging))
.onErrorResumeNext((err) ->
Single.just(new TeiListWithPaging(false, Collections.emptyList(), paging)));
})
.takeUntil(res -> res.isSuccess && (res.paging.isLastPage() ||
(!res.paging.isLastPage() && res.teiList.size() < res.paging.pageSize())))
.map(tuple -> tuple.teiList);
}
private List<TrackedEntityInstance> limitTeisForPage(List<TrackedEntityInstance> pageTrackedEntityInstances,
Paging paging) {
if (paging.isLastPage()
&& pageTrackedEntityInstances.size() > paging.previousItemsToSkipCount()) {
int toIndex = pageTrackedEntityInstances.size() <
paging.pageSize() - paging.posteriorItemsToSkipCount() ?
pageTrackedEntityInstances.size() :
paging.pageSize() - paging.posteriorItemsToSkipCount();
return pageTrackedEntityInstances.subList(paging.previousItemsToSkipCount(), toIndex);
} else {
return pageTrackedEntityInstances;
}
}
private Set<String> getOrgUnitUids() {
List<UserOrganisationUnitLink> userOrganisationUnitLinks = userOrganisationUnitLinkStore.selectAll();
Set<String> organisationUnitUids = new HashSet<>();
for (UserOrganisationUnitLink userOrganisationUnitLink : userOrganisationUnitLinks) {
if (userOrganisationUnitLink.organisationUnitScope().equals(
OrganisationUnit.Scope.SCOPE_DATA_CAPTURE.name())) {
organisationUnitUids.add(userOrganisationUnitLink.organisationUnit());
}
}
return organisationUnitUids;
}
private Observable<D2Progress> updateResource(D2ProgressManager progressManager) {
return Observable.fromCallable(() -> {
resourceHandler.handleResource(resourceType);
return progressManager.increaseProgress(TrackedEntityInstance.class, true);
});
}
private static class TeiListWithPaging {
final boolean isSuccess;
final List<TrackedEntityInstance> teiList;
public final Paging paging;
private TeiListWithPaging(boolean isSuccess, List<TrackedEntityInstance> teiList, Paging paging) {
this.isSuccess = isSuccess;
this.teiList = teiList;
this.paging = paging;
}
}
} | core/src/main/java/org/hisp/dhis/android/core/trackedentity/TrackedEntityInstanceWithLimitCallFactory.java | /*
* Copyright (c) 2004-2019, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project 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.hisp.dhis.android.core.trackedentity;
import org.hisp.dhis.android.core.arch.api.executors.RxAPICallExecutor;
import org.hisp.dhis.android.core.arch.call.D2CallWithProgress;
import org.hisp.dhis.android.core.arch.call.D2Progress;
import org.hisp.dhis.android.core.arch.call.D2ProgressManager;
import org.hisp.dhis.android.core.arch.repositories.collection.ReadOnlyWithDownloadObjectRepository;
import org.hisp.dhis.android.core.data.api.OuMode;
import org.hisp.dhis.android.core.organisationunit.OrganisationUnit;
import org.hisp.dhis.android.core.resource.Resource;
import org.hisp.dhis.android.core.resource.ResourceHandler;
import org.hisp.dhis.android.core.systeminfo.DHISVersionManager;
import org.hisp.dhis.android.core.systeminfo.SystemInfo;
import org.hisp.dhis.android.core.user.UserOrganisationUnitLink;
import org.hisp.dhis.android.core.user.UserOrganisationUnitLinkStore;
import org.hisp.dhis.android.core.utils.services.ApiPagingEngine;
import org.hisp.dhis.android.core.utils.services.Paging;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.inject.Inject;
import dagger.Reusable;
import io.reactivex.Observable;
import io.reactivex.Single;
@Reusable
public final class TrackedEntityInstanceWithLimitCallFactory {
private final Resource.Type resourceType = Resource.Type.TRACKED_ENTITY_INSTANCE;
private final RxAPICallExecutor rxCallExecutor;
private final ResourceHandler resourceHandler;
private final UserOrganisationUnitLinkStore userOrganisationUnitLinkStore;
private final ReadOnlyWithDownloadObjectRepository<SystemInfo> systemInfoRepository;
private final DHISVersionManager versionManager;
private final TrackedEntityInstanceRelationshipDownloadAndPersistCallFactory relationshipDownloadCallFactory;
private final TrackedEntityInstancePersistenceCallFactory persistenceCallFactory;
private final TrackedEntityInstancesEndpointCallFactory endpointCallFactory;
// TODO use scheduler for parallel download
// private final Scheduler teiDownloadScheduler = Schedulers.from(Executors.newFixedThreadPool(6));
@Inject
TrackedEntityInstanceWithLimitCallFactory(
RxAPICallExecutor rxCallExecutor,
ResourceHandler resourceHandler,
UserOrganisationUnitLinkStore userOrganisationUnitLinkStore,
ReadOnlyWithDownloadObjectRepository<SystemInfo> systemInfoRepository,
TrackedEntityInstanceRelationshipDownloadAndPersistCallFactory relationshipDownloadCallFactory,
TrackedEntityInstancePersistenceCallFactory persistenceCallFactory,
DHISVersionManager versionManager,
TrackedEntityInstancesEndpointCallFactory endpointCallFactory) {
this.rxCallExecutor = rxCallExecutor;
this.resourceHandler = resourceHandler;
this.userOrganisationUnitLinkStore = userOrganisationUnitLinkStore;
this.systemInfoRepository = systemInfoRepository;
this.versionManager = versionManager;
this.relationshipDownloadCallFactory = relationshipDownloadCallFactory;
this.persistenceCallFactory = persistenceCallFactory;
this.endpointCallFactory = endpointCallFactory;
}
public D2CallWithProgress getCall(final int teiLimit, final boolean limitByOrgUnit) {
D2ProgressManager progressManager = new D2ProgressManager(null);
Observable<D2Progress> concatObservable = Observable.concat(
downloadSystemInfo(progressManager),
downloadTeis(progressManager, teiLimit, limitByOrgUnit),
downloadRelationshipTeis(progressManager),
updateResource(progressManager)
);
return rxCallExecutor.wrapObservableTransactionally(concatObservable, true);
}
private Observable<D2Progress> downloadSystemInfo(D2ProgressManager progressManager) {
return systemInfoRepository.download()
.toSingle(() -> progressManager.increaseProgress(SystemInfo.class, false))
.toObservable();
}
private Observable<D2Progress> downloadTeis(D2ProgressManager progressManager,
int teiLimit,
boolean limitByOrgUnit) {
int pageSize = TeiQuery.builder().build().pageSize();
List<Paging> pagingList = ApiPagingEngine.getPaginationList(pageSize, teiLimit);
String lastUpdated = resourceHandler.getLastUpdated(resourceType);
Observable<List<TrackedEntityInstance>> teiDownloadObservable = limitByOrgUnit
? getTrackedEntityInstancesWithLimitByOrgUnit(lastUpdated, pagingList)
: getTrackedEntityInstancesWithoutLimits(lastUpdated, pagingList);
return teiDownloadObservable.map(
teiList -> {
persistenceCallFactory.getCall(teiList).call();
return progressManager.increaseProgress(TrackedEntityInstance.class, false);
});
}
private Observable<D2Progress> downloadRelationshipTeis(D2ProgressManager progressManager) {
Observable<List<TrackedEntityInstance>> observable = versionManager.is2_29()
? Observable.just(Collections.emptyList())
: relationshipDownloadCallFactory.getCall().toObservable();
return observable.map(
trackedEntityInstances -> progressManager.increaseProgress(TrackedEntityInstance.class, true));
}
private Observable<List<TrackedEntityInstance>> getTrackedEntityInstancesWithLimitByOrgUnit(
String lastUpdated, List<Paging> pagingList) {
return Observable.fromIterable(getOrgUnitUids())
.flatMap(orgUnitUid -> {
TeiQuery.Builder teiQueryBuilder = TeiQuery.builder()
.lastUpdatedStartDate(lastUpdated)
.orgUnits(Collections.singleton(orgUnitUid));
return getTrackedEntityInstancesWithPaging(teiQueryBuilder, pagingList);
// TODO .subscribeOn(teiDownloadScheduler);
});
}
private Observable<List<TrackedEntityInstance>> getTrackedEntityInstancesWithoutLimits(
String lastUpdated, List<Paging> pagingList) {
TeiQuery.Builder teiQueryBuilder = TeiQuery.builder()
.lastUpdatedStartDate(lastUpdated)
.orgUnits(userOrganisationUnitLinkStore.queryRootCaptureOrganisationUnitUids())
.ouMode(OuMode.DESCENDANTS);
return getTrackedEntityInstancesWithPaging(teiQueryBuilder, pagingList);
// TODO .subscribeOn(teiDownloadScheduler);
}
private Observable<List<TrackedEntityInstance>> getTrackedEntityInstancesWithPaging(
TeiQuery.Builder teiQueryBuilder, List<Paging> pagingList) {
Observable<Paging> pagingObservable = Observable.fromIterable(pagingList);
return pagingObservable
.flatMapSingle(paging -> {
teiQueryBuilder.page(paging.page()).pageSize(paging.pageSize());
return endpointCallFactory.getCall(teiQueryBuilder.build()).map(payload ->
new TeiListWithPaging(true, limitTeisForPage(payload.items(), paging), paging))
.onErrorResumeNext((err) ->
Single.just(new TeiListWithPaging(false, Collections.emptyList(), paging)));
})
.takeUntil(res -> res.isSuccess && (res.paging.isLastPage() ||
(!res.paging.isLastPage() && res.teiList.size() < res.paging.pageSize())))
.map(tuple -> tuple.teiList);
}
private List<TrackedEntityInstance> limitTeisForPage(List<TrackedEntityInstance> pageTrackedEntityInstances,
Paging paging) {
if (paging.isLastPage()
&& pageTrackedEntityInstances.size() > paging.previousItemsToSkipCount()) {
int toIndex = pageTrackedEntityInstances.size() <
paging.pageSize() - paging.posteriorItemsToSkipCount() ?
pageTrackedEntityInstances.size() :
paging.pageSize() - paging.posteriorItemsToSkipCount();
return pageTrackedEntityInstances.subList(paging.previousItemsToSkipCount(), toIndex);
} else {
return pageTrackedEntityInstances;
}
}
private Set<String> getOrgUnitUids() {
List<UserOrganisationUnitLink> userOrganisationUnitLinks = userOrganisationUnitLinkStore.selectAll();
Set<String> organisationUnitUids = new HashSet<>();
for (UserOrganisationUnitLink userOrganisationUnitLink : userOrganisationUnitLinks) {
if (userOrganisationUnitLink.organisationUnitScope().equals(
OrganisationUnit.Scope.SCOPE_DATA_CAPTURE.name())) {
organisationUnitUids.add(userOrganisationUnitLink.organisationUnit());
}
}
return organisationUnitUids;
}
private Observable<D2Progress> updateResource(D2ProgressManager progressManager) {
return Observable.fromCallable(() -> {
resourceHandler.handleResource(resourceType);
return progressManager.increaseProgress(TrackedEntityInstance.class, true);
});
}
private class TeiListWithPaging {
final boolean isSuccess;
final List<TrackedEntityInstance> teiList;
public final Paging paging;
private TeiListWithPaging(boolean isSuccess, List<TrackedEntityInstance> teiList, Paging paging) {
this.isSuccess = isSuccess;
this.teiList = teiList;
this.paging = paging;
}
}
} | [ANDROSDK-811] Findbugs
| core/src/main/java/org/hisp/dhis/android/core/trackedentity/TrackedEntityInstanceWithLimitCallFactory.java | [ANDROSDK-811] Findbugs |
|
Java | mit | dbccbfac40f383b1788535570dfd5977851748f1 | 0 | bric3/mockito,bric3/mockito,mockito/mockito,ze-pequeno/mockito,mockito/mockito,bric3/mockito,mockito/mockito,ze-pequeno/mockito | /*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito;
import org.mockito.internal.MockitoCore;
import org.mockito.internal.creation.MockSettingsImpl;
import org.mockito.internal.debugging.MockitoDebuggerImpl;
import org.mockito.internal.framework.DefaultMockitoFramework;
import org.mockito.internal.session.DefaultMockitoSessionBuilder;
import org.mockito.internal.verification.VerificationModeFactory;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.MockitoRule;
import org.mockito.mock.SerializableMode;
import org.mockito.quality.MockitoHint;
import org.mockito.quality.Strictness;
import org.mockito.session.MockitoSessionBuilder;
import org.mockito.stubbing.*;
import org.mockito.verification.*;
/**
* <p align="left"><img src="logo.png" srcset="[email protected] 2x" alt="Mockito logo"/></p>
* The Mockito library enables mock creation, verification and stubbing.
*
* <p>
* This javadoc content is also available on the <a href="http://mockito.org">http://mockito.org</a> web page.
* All documentation is kept in javadocs because it guarantees consistency between what's on the web and what's in the source code.
* It allows access to documentation straight from the IDE even if you work offline.
* It motivates Mockito developers to keep documentation up-to-date with the code that they write,
* every day, with every commit.
*
* <h1>Contents</h1>
*
* <b>
* <a href="#0">0. Migrating to Mockito 2</a><br/>
* <a href="#0.1">0.1 Mockito Android support</a></br/>
* <a href="#0.2">0.2 Configuration-free inline mock making</a></br/>
* <a href="#1">1. Let's verify some behaviour! </a><br/>
* <a href="#2">2. How about some stubbing? </a><br/>
* <a href="#3">3. Argument matchers </a><br/>
* <a href="#4">4. Verifying exact number of invocations / at least once / never </a><br/>
* <a href="#5">5. Stubbing void methods with exceptions </a><br/>
* <a href="#6">6. Verification in order </a><br/>
* <a href="#7">7. Making sure interaction(s) never happened on mock </a><br/>
* <a href="#8">8. Finding redundant invocations </a><br/>
* <a href="#9">9. Shorthand for mocks creation - <code>@Mock</code> annotation </a><br/>
* <a href="#10">10. Stubbing consecutive calls (iterator-style stubbing) </a><br/>
* <a href="#11">11. Stubbing with callbacks </a><br/>
* <a href="#12">12. <code>doReturn()</code>|<code>doThrow()</code>|<code>doAnswer()</code>|<code>doNothing()</code>|<code>doCallRealMethod()</code> family of methods</a><br/>
* <a href="#13">13. Spying on real objects </a><br/>
* <a href="#14">14. Changing default return values of unstubbed invocations (Since 1.7) </a><br/>
* <a href="#15">15. Capturing arguments for further assertions (Since 1.8.0) </a><br/>
* <a href="#16">16. Real partial mocks (Since 1.8.0) </a><br/>
* <a href="#17">17. Resetting mocks (Since 1.8.0) </a><br/>
* <a href="#18">18. Troubleshooting & validating framework usage (Since 1.8.0) </a><br/>
* <a href="#19">19. Aliases for behavior driven development (Since 1.8.0) </a><br/>
* <a href="#20">20. Serializable mocks (Since 1.8.1) </a><br/>
* <a href="#21">21. New annotations: <code>@Captor</code>, <code>@Spy</code>, <code>@InjectMocks</code> (Since 1.8.3) </a><br/>
* <a href="#22">22. Verification with timeout (Since 1.8.5) </a><br/>
* <a href="#23">23. Automatic instantiation of <code>@Spies</code>, <code>@InjectMocks</code> and constructor injection goodness (Since 1.9.0)</a><br/>
* <a href="#24">24. One-liner stubs (Since 1.9.0)</a><br/>
* <a href="#25">25. Verification ignoring stubs (Since 1.9.0)</a><br/>
* <a href="#26">26. Mocking details (Improved in 2.2.x)</a><br/>
* <a href="#27">27. Delegate calls to real instance (Since 1.9.5)</a><br/>
* <a href="#28">28. <code>MockMaker</code> API (Since 1.9.5)</a><br/>
* <a href="#29">29. BDD style verification (Since 1.10.0)</a><br/>
* <a href="#30">30. Spying or mocking abstract classes (Since 1.10.12, further enhanced in 2.7.13 and 2.7.14)</a><br/>
* <a href="#31">31. Mockito mocks can be <em>serialized</em> / <em>deserialized</em> across classloaders (Since 1.10.0)</a></h3><br/>
* <a href="#32">32. Better generic support with deep stubs (Since 1.10.0)</a></h3><br/>
* <a href="#32">33. Mockito JUnit rule (Since 1.10.17)</a><br/>
* <a href="#34">34. Switch <em>on</em> or <em>off</em> plugins (Since 1.10.15)</a><br/>
* <a href="#35">35. Custom verification failure message (Since 2.1.0)</a><br/>
* <a href="#36">36. Java 8 Lambda Matcher Support (Since 2.1.0)</a><br/>
* <a href="#37">37. Java 8 Custom Answer Support (Since 2.1.0)</a><br/>
* <a href="#38">38. Meta data and generic type retention (Since 2.1.0)</a><br/>
* <a href="#39">39. Mocking final types, enums and final methods (Since 2.1.0)</a><br/>
* <a href="#40">40. (**new**) Improved productivity and cleaner tests with "stricter" Mockito (Since 2.+)</a><br/>
* </b>
*
* <h3 id="0">0. <a class="meaningful_link" href="#mockito2" name="mockito2">Migrating to Mockito 2</a></h3>
*
* In order to continue improving Mockito and further improve the unit testing experience, we want you to upgrade to 2.1.0!
* Mockito follows <a href="http://semver.org/">semantic versioning</a> and contains breaking changes only on major version upgrades.
* In the lifecycle of a library, breaking changes are necessary
* to roll out a set of brand new features that alter the existing behavior or even change the API.
* For a comprehensive guide on the new release including incompatible changes,
* see '<a href="https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2">What's new in Mockito 2</a>' wiki page.
* We hope that you enjoy Mockito 2!
*
* <h3 id="0.1">0.1. <a class="meaningful_link" href="#mockito" name="mockito-android">Mockito Android support</a></h3>
*
* With Mockito version 2.6.1 we ship "native" Android support. To enable Android support, add the `mockito-android` library as dependency
* to your project. This artifact is published to the same Mockito organization and can be imported for Android as follows:
*
* <pre class="code"><code>
* repositories {
* jcenter()
* }
* dependencies {
* testCompile "org.mockito:mockito-core:+"
* androidTestCompile "org.mockito:mockito-android:+"
* }
* </code></pre>
*
* You can continue to run the same unit tests on a regular VM by using the `mockito-core` artifact in your "testCompile" scope as shown
* above. Be aware that you cannot use the <a href="#39">inline mock maker</a> on Android due to limitations in the Android VM.
*
* If you encounter issues with mocking on Android, please open an issue
* <a href="https://github.com/mockito/mockito/issues/new">on the official issue tracker</a>.
* Do provide the version of Android you are working on and dependencies of your project.
*
* <h3 id="0.2">0.2. <a class="meaningful_link" href="#mockito-inline" name="mockito-inline">Configuration-free inline mock making</a></h3>
*
* Starting with version 2.7.6, we offer the 'mockito-inline' artifact that enables <a href="#39">inline mock making</a> without configuring
* the MockMaker extension file. To use this, add the `mockito-inline` instead of the `mockito-core` artifact as follows:
*
* <pre class="code"><code>
* repositories {
* jcenter()
* }
* dependencies {
* testCompile "org.mockito:mockito-inline:+"
* }
* </code></pre>
*
* Be aware that this artifact may be abolished when the inline mock making feature is integrated into the default mock maker.
*
* <p>
* For more information about inline mock making, see <a href="#39">section 39</a>.
*
* <h3 id="1">1. <a class="meaningful_link" href="#verification" name="verification">Let's verify some behaviour!</a></h3>
*
* The following examples mock a List, because most people are familiar with the interface (such as the
* <code>add()</code>, <code>get()</code>, <code>clear()</code> methods). <br>
* In reality, please don't mock the List class. Use a real instance instead.
*
* <pre class="code"><code class="java">
* //Let's import Mockito statically so that the code looks clearer
* import static org.mockito.Mockito.*;
*
* //mock creation
* List mockedList = mock(List.class);
*
* //using mock object
* mockedList.add("one");
* mockedList.clear();
*
* //verification
* verify(mockedList).add("one");
* verify(mockedList).clear();
* </code></pre>
*
* <p>
* Once created, a mock will remember all interactions. Then you can selectively
* verify whatever interactions you are interested in.
*
*
*
*
* <h3 id="2">2. <a class="meaningful_link" href="#stubbing" name="stubbing">How about some stubbing?</a></h3>
*
* <pre class="code"><code class="java">
* //You can mock concrete classes, not just interfaces
* LinkedList mockedList = mock(LinkedList.class);
*
* //stubbing
* when(mockedList.get(0)).thenReturn("first");
* when(mockedList.get(1)).thenThrow(new RuntimeException());
*
* //following prints "first"
* System.out.println(mockedList.get(0));
*
* //following throws runtime exception
* System.out.println(mockedList.get(1));
*
* //following prints "null" because get(999) was not stubbed
* System.out.println(mockedList.get(999));
*
* //Although it is possible to verify a stubbed invocation, usually <b>it's just redundant</b>
* //If your code cares what get(0) returns, then something else breaks (often even before verify() gets executed).
* //If your code doesn't care what get(0) returns, then it should not be stubbed. Not convinced? See <a href="http://monkeyisland.pl/2008/04/26/asking-and-telling">here</a>.
* verify(mockedList).get(0);
* </code></pre>
*
* <ul>
* <li> By default, for all methods that return a value, a mock will return either null, a
* a primitive/primitive wrapper value, or an empty collection, as appropriate.
* For example 0 for an int/Integer and false for a boolean/Boolean. </li>
*
* <li> Stubbing can be overridden: for example common stubbing can go to
* fixture setup but the test methods can override it.
* Please note that overridding stubbing is a potential code smell that points out too much stubbing</li>
*
* <li> Once stubbed, the method will always return a stubbed value, regardless
* of how many times it is called. </li>
*
* <li> Last stubbing is more important - when you stubbed the same method with
* the same arguments many times.
* Other words: <b>the order of stubbing matters</b> but it is only meaningful rarely,
* e.g. when stubbing exactly the same method calls or sometimes when argument matchers are used, etc.</li>
*
* </ul>
*
*
*
* <h3 id="3">3. <a class="meaningful_link" href="#argument_matchers" name="argument_matchers">Argument matchers</a></h3>
*
* Mockito verifies argument values in natural java style: by using an <code>equals()</code> method.
* Sometimes, when extra flexibility is required then you might use argument matchers:
*
* <pre class="code"><code class="java">
* //stubbing using built-in anyInt() argument matcher
* when(mockedList.get(anyInt())).thenReturn("element");
*
* //stubbing using custom matcher (let's say isValid() returns your own matcher implementation):
* when(mockedList.contains(argThat(isValid()))).thenReturn("element");
*
* //following prints "element"
* System.out.println(mockedList.get(999));
*
* //<b>you can also verify using an argument matcher</b>
* verify(mockedList).get(anyInt());
*
* //<b>argument matchers can also be written as Java 8 Lambdas</b>
* verify(mockedList).add(argThat(someString -> someString.length() > 5));
*
* </code></pre>
*
* <p>
* Argument matchers allow flexible verification or stubbing.
* {@link ArgumentMatchers Click here} {@link org.mockito.hamcrest.MockitoHamcrest or here} to see more built-in matchers
* and examples of <b>custom argument matchers / hamcrest matchers</b>.
* <p>
* For information solely on <b>custom argument matchers</b> check out javadoc for {@link ArgumentMatcher} class.
* <p>
* Be reasonable with using complicated argument matching.
* The natural matching style using <code>equals()</code> with occasional <code>anyX()</code> matchers tend to give clean & simple tests.
* Sometimes it's just better to refactor the code to allow <code>equals()</code> matching or even implement <code>equals()</code> method to help out with testing.
* <p>
* Also, read <a href="#15">section 15</a> or javadoc for {@link ArgumentCaptor} class.
* {@link ArgumentCaptor} is a special implementation of an argument matcher that captures argument values for further assertions.
* <p>
* <b>Warning on argument matchers:</b>
* <p>
* If you are using argument matchers, <b>all arguments</b> have to be provided
* by matchers.
* <p>
The following example shows verification but the same applies to stubbing:
*
* <pre class="code"><code class="java">
* verify(mock).someMethod(anyInt(), anyString(), <b>eq("third argument")</b>);
* //above is correct - eq() is also an argument matcher
*
* verify(mock).someMethod(anyInt(), anyString(), <b>"third argument"</b>);
* //above is incorrect - exception will be thrown because third argument is given without an argument matcher.
* </code></pre>
*
* <p>
* Matcher methods like <code>anyObject()</code>, <code>eq()</code> <b>do not</b> return matchers.
* Internally, they record a matcher on a stack and return a dummy value (usually null).
* This implementation is due to static type safety imposed by the java compiler.
* The consequence is that you cannot use <code>anyObject()</code>, <code>eq()</code> methods outside of verified/stubbed method.
*
*
*
*
* <h3 id="4">4. <a class="meaningful_link" href="#exact_verification" name="exact_verification">Verifying exact number of invocations</a> /
* <a class="meaningful_link" href="#at_least_verification" name="at_least_verification">at least x</a> / never</h3>
*
* <pre class="code"><code class="java">
* //using mock
* mockedList.add("once");
*
* mockedList.add("twice");
* mockedList.add("twice");
*
* mockedList.add("three times");
* mockedList.add("three times");
* mockedList.add("three times");
*
* //following two verifications work exactly the same - times(1) is used by default
* verify(mockedList).add("once");
* verify(mockedList, times(1)).add("once");
*
* //exact number of invocations verification
* verify(mockedList, times(2)).add("twice");
* verify(mockedList, times(3)).add("three times");
*
* //verification using never(). never() is an alias to times(0)
* verify(mockedList, never()).add("never happened");
*
* //verification using atLeast()/atMost()
* verify(mockedList, atLeastOnce()).add("three times");
* verify(mockedList, atLeast(2)).add("five times");
* verify(mockedList, atMost(5)).add("three times");
*
* </code></pre>
*
* <p>
* <b>times(1) is the default.</b> Therefore using times(1) explicitly can be
* omitted.
*
*
*
*
* <h3 id="5">5. <a class="meaningful_link" href="#stubbing_with_exceptions" name="stubbing_with_exceptions">Stubbing void methods with exceptions</a></h3>
*
* <pre class="code"><code class="java">
* doThrow(new RuntimeException()).when(mockedList).clear();
*
* //following throws RuntimeException:
* mockedList.clear();
* </code></pre>
*
* Read more about <code>doThrow()</code>|<code>doAnswer()</code> family of methods in <a href="#12">section 12</a>.
* <p>
*
* <h3 id="6">6. <a class="meaningful_link" href="#in_order_verification" name="in_order_verification">Verification in order</a></h3>
*
* <pre class="code"><code class="java">
* // A. Single mock whose methods must be invoked in a particular order
* List singleMock = mock(List.class);
*
* //using a single mock
* singleMock.add("was added first");
* singleMock.add("was added second");
*
* //create an inOrder verifier for a single mock
* InOrder inOrder = inOrder(singleMock);
*
* //following will make sure that add is first called with "was added first, then with "was added second"
* inOrder.verify(singleMock).add("was added first");
* inOrder.verify(singleMock).add("was added second");
*
* // B. Multiple mocks that must be used in a particular order
* List firstMock = mock(List.class);
* List secondMock = mock(List.class);
*
* //using mocks
* firstMock.add("was called first");
* secondMock.add("was called second");
*
* //create inOrder object passing any mocks that need to be verified in order
* InOrder inOrder = inOrder(firstMock, secondMock);
*
* //following will make sure that firstMock was called before secondMock
* inOrder.verify(firstMock).add("was called first");
* inOrder.verify(secondMock).add("was called second");
*
* // Oh, and A + B can be mixed together at will
* </code></pre>
*
* Verification in order is flexible - <b>you don't have to verify all
* interactions</b> one-by-one but only those that you are interested in
* testing in order.
* <p>
* Also, you can create an InOrder object passing only the mocks that are relevant for
* in-order verification.
*
*
*
*
* <h3 id="7">7. <a class="meaningful_link" href="#never_verification" name="never_verification">Making sure interaction(s) never happened on mock</a></h3>
*
* <pre class="code"><code class="java">
* //using mocks - only mockOne is interacted
* mockOne.add("one");
*
* //ordinary verification
* verify(mockOne).add("one");
*
* //verify that method was never called on a mock
* verify(mockOne, never()).add("two");
*
* //verify that other mocks were not interacted
* verifyZeroInteractions(mockTwo, mockThree);
*
* </code></pre>
*
*
*
*
* <h3 id="8">8. <a class="meaningful_link" href="#finding_redundant_invocations" name="finding_redundant_invocations">Finding redundant invocations</a></h3>
*
* <pre class="code"><code class="java">
* //using mocks
* mockedList.add("one");
* mockedList.add("two");
*
* verify(mockedList).add("one");
*
* //following verification will fail
* verifyNoMoreInteractions(mockedList);
* </code></pre>
*
* A word of <b>warning</b>:
* Some users who did a lot of classic, expect-run-verify mocking tend to use <code>verifyNoMoreInteractions()</code> very often, even in every test method.
* <code>verifyNoMoreInteractions()</code> is not recommended to use in every test method.
* <code>verifyNoMoreInteractions()</code> is a handy assertion from the interaction testing toolkit. Use it only when it's relevant.
* Abusing it leads to <strong>overspecified</strong>, <strong>less maintainable</strong> tests. You can find further reading
* <a href="http://monkeyisland.pl/2008/07/12/should-i-worry-about-the-unexpected/">here</a>.
*
* <p>
* See also {@link Mockito#never()} - it is more explicit and
* communicates the intent well.
* <p>
*
*
*
*
* <h3 id="9">9. <a class="meaningful_link" href="#mock_annotation" name="mock_annotation">Shorthand for mocks creation - <code>@Mock</code> annotation</a></h3>
*
* <ul>
* <li>Minimizes repetitive mock creation code.</li>
* <li>Makes the test class more readable.</li>
* <li>Makes the verification error easier to read because the <b>field name</b>
* is used to identify the mock.</li>
* </ul>
*
* <pre class="code"><code class="java">
* public class ArticleManagerTest {
*
* @Mock private ArticleCalculator calculator;
* @Mock private ArticleDatabase database;
* @Mock private UserProvider userProvider;
*
* private ArticleManager manager;
* </code></pre>
*
* <b>Important!</b> This needs to be somewhere in the base class or a test
* runner:
*
* <pre class="code"><code class="java">
* MockitoAnnotations.initMocks(testClass);
* </code></pre>
*
* You can use built-in runner: {@link MockitoJUnitRunner} or a rule: {@link MockitoRule}.
* <p>
* Read more here: {@link MockitoAnnotations}
*
*
*
*
* <h3 id="10">10. <a class="meaningful_link" href="#stubbing_consecutive_calls" name="stubbing_consecutive_calls">Stubbing consecutive calls</a> (iterator-style stubbing)</h3>
*
* Sometimes we need to stub with different return value/exception for the same
* method call. Typical use case could be mocking iterators.
* Original version of Mockito did not have this feature to promote simple mocking.
* For example, instead of iterators one could use {@link Iterable} or simply
* collections. Those offer natural ways of stubbing (e.g. using real
* collections). In rare scenarios stubbing consecutive calls could be useful,
* though:
* <p>
*
* <pre class="code"><code class="java">
* when(mock.someMethod("some arg"))
* .thenThrow(new RuntimeException())
* .thenReturn("foo");
*
* //First call: throws runtime exception:
* mock.someMethod("some arg");
*
* //Second call: prints "foo"
* System.out.println(mock.someMethod("some arg"));
*
* //Any consecutive call: prints "foo" as well (last stubbing wins).
* System.out.println(mock.someMethod("some arg"));
* </code></pre>
*
* Alternative, shorter version of consecutive stubbing:
*
* <pre class="code"><code class="java">
* when(mock.someMethod("some arg"))
* .thenReturn("one", "two", "three");
* </code></pre>
*
* <strong>Warning</strong> : if instead of chaining {@code .thenReturn()} calls, multiple stubbing with the same matchers or arguments
* is used, then each stubbing will override the previous one:
*
* <pre class="code"><code class="java">
* //All mock.someMethod("some arg") calls will return "two"
* when(mock.someMethod("some arg"))
* .thenReturn("one")
* when(mock.someMethod("some arg"))
* .thenReturn("two")
* </code></pre>
*
*
*
* <h3 id="11">11. <a class="meaningful_link" href="#answer_stubs" name="answer_stubs">Stubbing with callbacks</a></h3>
*
* Allows stubbing with generic {@link Answer} interface.
* <p>
* Yet another controversial feature which was not included in Mockito
* originally. We recommend simply stubbing with <code>thenReturn()</code> or
* <code>thenThrow()</code>, which should be enough to test/test-drive
* any clean & simple code. However, if you do have a need to stub with the generic Answer interface, here is an example:
*
* <pre class="code"><code class="java">
* when(mock.someMethod(anyString())).thenAnswer(new Answer() {
* Object answer(InvocationOnMock invocation) {
* Object[] args = invocation.getArguments();
* Object mock = invocation.getMock();
* return "called with arguments: " + args;
* }
* });
*
* //the following prints "called with arguments: foo"
* System.out.println(mock.someMethod("foo"));
* </code></pre>
*
*
*
*
* <h3 id="12">12. <a class="meaningful_link" href="#do_family_methods_stubs" name="do_family_methods_stubs"><code>doReturn()</code>|<code>doThrow()</code>|
* <code>doAnswer()</code>|<code>doNothing()</code>|<code>doCallRealMethod()</code> family of methods</a></h3>
*
* Stubbing void methods requires a different approach from {@link Mockito#when(Object)} because the compiler does not
* like void methods inside brackets...
* <p>
* Use <code>doThrow()</code> when you want to stub a void method with an exception:
* <pre class="code"><code class="java">
* doThrow(new RuntimeException()).when(mockedList).clear();
*
* //following throws RuntimeException:
* mockedList.clear();
* </code></pre>
* </p>
*
* <p>
* You can use <code>doThrow()</code>, <code>doAnswer()</code>, <code>doNothing()</code>, <code>doReturn()</code>
* and <code>doCallRealMethod()</code> in place of the corresponding call with <code>when()</code>, for any method.
* It is necessary when you
* <ul>
* <li>stub void methods</li>
* <li>stub methods on spy objects (see below)</li>
* <li>stub the same method more than once, to change the behaviour of a mock in the middle of a test.</li>
* </ul>
* but you may prefer to use these methods in place of the alternative with <code>when()</code>, for all of your stubbing calls.
* <p>
* Read more about these methods:
* <p>
* {@link Mockito#doReturn(Object)}
* <p>
* {@link Mockito#doThrow(Throwable...)}
* <p>
* {@link Mockito#doThrow(Class)}
* <p>
* {@link Mockito#doAnswer(Answer)}
* <p>
* {@link Mockito#doNothing()}
* <p>
* {@link Mockito#doCallRealMethod()}
*
*
*
*
* <h3 id="13">13. <a class="meaningful_link" href="#spy" name="spy">Spying on real objects</a></h3>
*
* You can create spies of real objects. When you use the spy then the <b>real</b> methods are called
* (unless a method was stubbed).
* <p>
* Real spies should be used <b>carefully and occasionally</b>, for example when dealing with legacy code.
*
* <p>
* Spying on real objects can be associated with "partial mocking" concept.
* <b>Before the release 1.8</b>, Mockito spies were not real partial mocks.
* The reason was we thought partial mock is a code smell.
* At some point we found legitimate use cases for partial mocks
* (3rd party interfaces, interim refactoring of legacy code, the full article is
* <a href="http://monkeyisland.pl/2009/01/13/subclass-and-override-vs-partial-mocking-vs-refactoring">here</a>)
* <p>
*
* <pre class="code"><code class="java">
* List list = new LinkedList();
* List spy = spy(list);
*
* //optionally, you can stub out some methods:
* when(spy.size()).thenReturn(100);
*
* //using the spy calls <b>*real*</b> methods
* spy.add("one");
* spy.add("two");
*
* //prints "one" - the first element of a list
* System.out.println(spy.get(0));
*
* //size() method was stubbed - 100 is printed
* System.out.println(spy.size());
*
* //optionally, you can verify
* verify(spy).add("one");
* verify(spy).add("two");
* </code></pre>
*
* <h4>Important gotcha on spying real objects!</h4>
* <ol>
* <li>Sometimes it's impossible or impractical to use {@link Mockito#when(Object)} for stubbing spies.
* Therefore when using spies please consider <code>doReturn</code>|<code>Answer</code>|<code>Throw()</code> family of
* methods for stubbing. Example:
*
* <pre class="code"><code class="java">
* List list = new LinkedList();
* List spy = spy(list);
*
* //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
* when(spy.get(0)).thenReturn("foo");
*
* //You have to use doReturn() for stubbing
* doReturn("foo").when(spy).get(0);
* </code></pre>
* </li>
*
* <li>Mockito <b>*does not*</b> delegate calls to the passed real instance, instead it actually creates a copy of it.
* So if you keep the real instance and interact with it, don't expect the spied to be aware of those interaction
* and their effect on real instance state.
* The corollary is that when an <b>*unstubbed*</b> method is called <b>*on the spy*</b> but <b>*not on the real instance*</b>,
* you won't see any effects on the real instance.
* </li>
*
* <li>Watch out for final methods.
* Mockito doesn't mock final methods so the bottom line is: when you spy on real objects + you try to stub a final method = trouble.
* Also you won't be able to verify those method as well.
* </li>
* </ol>
*
*
*
*
* <h3 id="14">14. Changing <a class="meaningful_link" href="#defaultreturn" name="defaultreturn">default return values of unstubbed invocations</a> (Since 1.7)</h3>
*
* You can create a mock with specified strategy for its return values.
* It's quite an advanced feature and typically you don't need it to write decent tests.
* However, it can be helpful for working with <b>legacy systems</b>.
* <p>
* It is the default answer so it will be used <b>only when you don't</b> stub the method call.
*
* <pre class="code"><code class="java">
* Foo mock = mock(Foo.class, Mockito.RETURNS_SMART_NULLS);
* Foo mockTwo = mock(Foo.class, new YourOwnAnswer());
* </code></pre>
*
* <p>
* Read more about this interesting implementation of <i>Answer</i>: {@link Mockito#RETURNS_SMART_NULLS}
*
*
*
*
* <h3 id="15">15. <a class="meaningful_link" href="#captors" name="captors">Capturing arguments</a> for further assertions (Since 1.8.0)</h3>
*
* Mockito verifies argument values in natural java style: by using an <code>equals()</code> method.
* This is also the recommended way of matching arguments because it makes tests clean & simple.
* In some situations though, it is helpful to assert on certain arguments after the actual verification.
* For example:
* <pre class="code"><code class="java">
* ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
* verify(mock).doSomething(argument.capture());
* assertEquals("John", argument.getValue().getName());
* </code></pre>
*
* <b>Warning:</b> it is recommended to use ArgumentCaptor with verification <b>but not</b> with stubbing.
* Using ArgumentCaptor with stubbing may decrease test readability because captor is created outside of assert (aka verify or 'then') block.
* Also it may reduce defect localization because if stubbed method was not called then no argument is captured.
* <p>
* In a way ArgumentCaptor is related to custom argument matchers (see javadoc for {@link ArgumentMatcher} class).
* Both techniques can be used for making sure certain arguments where passed to mocks.
* However, ArgumentCaptor may be a better fit if:
* <ul>
* <li>custom argument matcher is not likely to be reused</li>
* <li>you just need it to assert on argument values to complete verification</li>
* </ul>
* Custom argument matchers via {@link ArgumentMatcher} are usually better for stubbing.
*
*
*
*
* <h3 id="16">16. <a class="meaningful_link" href="#partial_mocks" name="partial_mocks">Real partial mocks</a> (Since 1.8.0)</h3>
*
* Finally, after many internal debates & discussions on the mailing list, partial mock support was added to Mockito.
* Previously we considered partial mocks as code smells. However, we found a legitimate use case for partial mocks - more reading:
* <a href="http://monkeyisland.pl/2009/01/13/subclass-and-override-vs-partial-mocking-vs-refactoring">here</a>
* <p>
* <b>Before release 1.8</b> <code>spy()</code> was not producing real partial mocks and it was confusing for some users.
* Read more about spying: <a href="#13">here</a> or in javadoc for {@link Mockito#spy(Object)} method.
* <p>
* <pre class="code"><code class="java">
* //you can create partial mock with spy() method:
* List list = spy(new LinkedList());
*
* //you can enable partial mock capabilities selectively on mocks:
* Foo mock = mock(Foo.class);
* //Be sure the real implementation is 'safe'.
* //If real implementation throws exceptions or depends on specific state of the object then you're in trouble.
* when(mock.someMethod()).thenCallRealMethod();
* </code></pre>
*
* As usual you are going to read <b>the partial mock warning</b>:
* Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
* How does partial mock fit into this paradigm? Well, it just doesn't...
* Partial mock usually means that the complexity has been moved to a different method on the same object.
* In most cases, this is not the way you want to design your application.
* <p>
* However, there are rare cases when partial mocks come handy:
* dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
* However, I wouldn't use partial mocks for new, test-driven & well-designed code.
*
*
*
*
* <h3 id="17">17. <a class="meaningful_link" href="#resetting_mocks" name="resetting_mocks">Resetting mocks</a> (Since 1.8.0)</h3>
*
* Smart Mockito users hardly use this feature because they know it could be a sign of poor tests.
* Normally, you don't need to reset your mocks, just create new mocks for each test method.
* <p>
* Instead of <code>reset()</code> please consider writing simple, small and focused test methods over lengthy, over-specified tests.
* <b>First potential code smell is <code>reset()</code> in the middle of the test method.</b> This probably means you're testing too much.
* Follow the whisper of your test methods: "Please keep us small & focused on single behavior".
* There are several threads about it on mockito mailing list.
* <p>
* The only reason we added <code>reset()</code> method is to
* make it possible to work with container-injected mocks.
* For more information see FAQ (<a href="https://github.com/mockito/mockito/wiki/FAQ">here</a>).
* <p>
* <b>Don't harm yourself.</b> <code>reset()</code> in the middle of the test method is a code smell (you're probably testing too much).
* <pre class="code"><code class="java">
* List mock = mock(List.class);
* when(mock.size()).thenReturn(10);
* mock.add(1);
*
* reset(mock);
* //at this point the mock forgot any interactions & stubbing
* </code></pre>
*
*
*
*
* <h3 id="18">18. <a class="meaningful_link" href="#framework_validation" name="framework_validation">Troubleshooting & validating framework usage</a> (Since 1.8.0)</h3>
*
* First of all, in case of any trouble, I encourage you to read the Mockito FAQ:
* <a href="https://github.com/mockito/mockito/wiki/FAQ">https://github.com/mockito/mockito/wiki/FAQ</a>
* <p>
* In case of questions you may also post to mockito mailing list:
* <a href="http://groups.google.com/group/mockito">http://groups.google.com/group/mockito</a>
* <p>
* Next, you should know that Mockito validates if you use it correctly <b>all the time</b>.
* However, there's a gotcha so please read the javadoc for {@link Mockito#validateMockitoUsage()}
*
*
*
*
* <h3 id="19">19. <a class="meaningful_link" href="#bdd_mockito" name="bdd_mockito">Aliases for behavior driven development</a> (Since 1.8.0)</h3>
*
* Behavior Driven Development style of writing tests uses <b>//given //when //then</b> comments as fundamental parts of your test methods.
* This is exactly how we write our tests and we warmly encourage you to do so!
* <p>
* Start learning about BDD here: <a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development">http://en.wikipedia.org/wiki/Behavior_Driven_Development</a>
* <p>
* The problem is that current stubbing api with canonical role of <b>when</b> word does not integrate nicely with <b>//given //when //then</b> comments.
* It's because stubbing belongs to <b>given</b> component of the test and not to the <b>when</b> component of the test.
* Hence {@link BDDMockito} class introduces an alias so that you stub method calls with {@link BDDMockito#given(Object)} method.
* Now it really nicely integrates with the <b>given</b> component of a BDD style test!
* <p>
* Here is how the test might look like:
* <pre class="code"><code class="java">
* import static org.mockito.BDDMockito.*;
*
* Seller seller = mock(Seller.class);
* Shop shop = new Shop(seller);
*
* public void shouldBuyBread() throws Exception {
* //given
* given(seller.askForBread()).willReturn(new Bread());
*
* //when
* Goods goods = shop.buyBread();
*
* //then
* assertThat(goods, containBread());
* }
* </code></pre>
*
*
*
*
* <h3 id="20">20. <a class="meaningful_link" href="#serializable_mocks" name="serializable_mocks">Serializable mocks</a> (Since 1.8.1)</h3>
*
* Mocks can be made serializable. With this feature you can use a mock in a place that requires dependencies to be serializable.
* <p>
* WARNING: This should be rarely used in unit testing.
* <p>
* The behaviour was implemented for a specific use case of a BDD spec that had an unreliable external dependency. This
* was in a web environment and the objects from the external dependency were being serialized to pass between layers.
* <p>
* To create serializable mock use {@link MockSettings#serializable()}:
* <pre class="code"><code class="java">
* List serializableMock = mock(List.class, withSettings().serializable());
* </code></pre>
* <p>
* The mock can be serialized assuming all the normal <a href='http://java.sun.com/j2se/1.5.0/docs/api/java/io/Serializable.html'>
* serialization requirements</a> are met by the class.
* <p>
* Making a real object spy serializable is a bit more effort as the spy(...) method does not have an overloaded version
* which accepts MockSettings. No worries, you will hardly ever use it.
*
* <pre class="code"><code class="java">
* List<Object> list = new ArrayList<Object>();
* List<Object> spy = mock(ArrayList.class, withSettings()
* .spiedInstance(list)
* .defaultAnswer(CALLS_REAL_METHODS)
* .serializable());
* </code></pre>
*
*
*
*
* <h3 id="21">21. New annotations: <a class="meaningful_link" href="#captor_annotation" name="captor_annotation"><code>@Captor</code></a>,
* <a class="meaningful_link" href="#spy_annotation" name="spy_annotation"><code>@Spy</code></a>,
* <a class="meaningful_link" href="#injectmocks_annotation" name="injectmocks_annotation"><code>@InjectMocks</code></a> (Since 1.8.3)</h3>
*
* <p>
* Release 1.8.3 brings new annotations that may be helpful on occasion:
*
* <ul>
* <li>@{@link Captor} simplifies creation of {@link ArgumentCaptor}
* - useful when the argument to capture is a nasty generic class and you want to avoid compiler warnings
* <li>@{@link Spy} - you can use it instead {@link Mockito#spy(Object)}.
* <li>@{@link InjectMocks} - injects mock or spy fields into tested object automatically.
* </ul>
*
* <p>
* Note that @{@link InjectMocks} can also be used in combination with the @{@link Spy} annotation, it means
* that Mockito will inject mocks into the partial mock under test. This complexity is another good reason why you
* should only use partial mocks as a last resort. See point 16 about partial mocks.
*
* <p>
* All new annotations are <b>*only*</b> processed on {@link MockitoAnnotations#initMocks(Object)}.
* Just like for @{@link Mock} annotation you can use the built-in runner: {@link MockitoJUnitRunner} or rule:
* {@link MockitoRule}.
* <p>
*
*
*
*
* <h3 id="22">22. <a class="meaningful_link" href="#verification_timeout" name="verification_timeout">Verification with timeout</a> (Since 1.8.5)</h3>
* <p>
* Allows verifying with timeout. It causes a verify to wait for a specified period of time for a desired
* interaction rather than fails immediately if had not already happened. May be useful for testing in concurrent
* conditions.
* <p>
* This feature should be used rarely - figure out a better way of testing your multi-threaded system.
* <p>
* Not yet implemented to work with InOrder verification.
* <p>
* Examples:
* <p>
* <pre class="code"><code class="java">
* //passes when someMethod() is called within given time span
* verify(mock, timeout(100)).someMethod();
* //above is an alias to:
* verify(mock, timeout(100).times(1)).someMethod();
*
* //passes when someMethod() is called <b>*exactly*</b> 2 times within given time span
* verify(mock, timeout(100).times(2)).someMethod();
*
* //passes when someMethod() is called <b>*at least*</b> 2 times within given time span
* verify(mock, timeout(100).atLeast(2)).someMethod();
*
* //verifies someMethod() within given time span using given verification mode
* //useful only if you have your own custom verification modes.
* verify(mock, new Timeout(100, yourOwnVerificationMode)).someMethod();
* </code></pre>
*
*
*
*
* <h3 id="23">23. <a class="meaningful_link" href="#automatic_instantiation" name="automatic_instantiation">Automatic instantiation of <code>@Spies</code>,
* <code>@InjectMocks</code></a> and <a class="meaningful_link" href="#constructor_injection" name="constructor_injection">constructor injection goodness</a> (Since 1.9.0)</h3>
*
* <p>
* Mockito will now try to instantiate @{@link Spy} and will instantiate @{@link InjectMocks} fields
* using <b>constructor</b> injection, <b>setter</b> injection, or <b>field</b> injection.
* <p>
* To take advantage of this feature you need to use {@link MockitoAnnotations#initMocks(Object)}, {@link MockitoJUnitRunner}
* or {@link MockitoRule}.
* <p>
* Read more about available tricks and the rules of injection in the javadoc for {@link InjectMocks}
* <pre class="code"><code class="java">
* //instead:
* @Spy BeerDrinker drinker = new BeerDrinker();
* //you can write:
* @Spy BeerDrinker drinker;
*
* //same applies to @InjectMocks annotation:
* @InjectMocks LocalPub;
* </code></pre>
*
*
*
*
* <h3 id="24">24. <a class="meaningful_link" href="#one_liner_stub" name="one_liner_stub">One-liner stubs</a> (Since 1.9.0)</h3>
* <p>
* Mockito will now allow you to create mocks when stubbing.
* Basically, it allows to create a stub in one line of code.
* This can be helpful to keep test code clean.
* For example, some boring stub can be created & stubbed at field initialization in a test:
* <pre class="code"><code class="java">
* public class CarTest {
* Car boringStubbedCar = when(mock(Car.class).shiftGear()).thenThrow(EngineNotStarted.class).getMock();
*
* @Test public void should... {}
* </code></pre>
*
*
*
*
* <h3 id="25">25. <a class="meaningful_link" href="#ignore_stubs_verification" name="ignore_stubs_verification">Verification ignoring stubs</a> (Since 1.9.0)</h3>
* <p>
* Mockito will now allow to ignore stubbing for the sake of verification.
* Sometimes useful when coupled with <code>verifyNoMoreInteractions()</code> or verification <code>inOrder()</code>.
* Helps avoiding redundant verification of stubbed calls - typically we're not interested in verifying stubs.
* <p>
* <b>Warning</b>, <code>ignoreStubs()</code> might lead to overuse of verifyNoMoreInteractions(ignoreStubs(...));
* Bear in mind that Mockito does not recommend bombarding every test with <code>verifyNoMoreInteractions()</code>
* for the reasons outlined in javadoc for {@link Mockito#verifyNoMoreInteractions(Object...)}
* <p>Some examples:
* <pre class="code"><code class="java">
* verify(mock).foo();
* verify(mockTwo).bar();
*
* //ignores all stubbed methods:
* verifyNoMoreInteractions(ignoreStubs(mock, mockTwo));
*
* //creates InOrder that will ignore stubbed
* InOrder inOrder = inOrder(ignoreStubs(mock, mockTwo));
* inOrder.verify(mock).foo();
* inOrder.verify(mockTwo).bar();
* inOrder.verifyNoMoreInteractions();
* </code></pre>
* <p>
* Advanced examples and more details can be found in javadoc for {@link Mockito#ignoreStubs(Object...)}
*
*
*
*
* <h3 id="26">26. <a class="meaningful_link" href="#mocking_details" name="mocking_details">Mocking details</a> (Improved in 2.2.x)</h3>
* <p>
*
* Mockito offers API to inspect the details of a mock object.
* This API is useful for advanced users and mocking framework integrators.
*
* <pre class="code"><code class="java">
* //To identify whether a particular object is a mock or a spy:
* Mockito.mockingDetails(someObject).isMock();
* Mockito.mockingDetails(someObject).isSpy();
*
* //Getting details like type to mock or default answer:
* MockingDetails details = mockingDetails(mock);
* details.getMockCreationSettings().getTypeToMock();
* details.getMockCreationSettings().getDefaultAnswer();
*
* //Getting interactions and stubbings of the mock:
* MockingDetails details = mockingDetails(mock);
* details.getInteractions();
* details.getStubbings();
*
* //Printing all interactions (including stubbing, unused stubs)
* System.out.println(mockingDetails(mock).printInvocations());
* </code></pre>
*
* For more information see javadoc for {@link MockingDetails}.
*
* <h3 id="27">27. <a class="meaningful_link" href="#delegating_call_to_real_instance" name="delegating_call_to_real_instance">Delegate calls to real instance</a> (Since 1.9.5)</h3>
*
* <p>Useful for spies or partial mocks of objects <strong>that are difficult to mock or spy</strong> using the usual spy API.
* Since Mockito 1.10.11, the delegate may or may not be of the same type as the mock.
* If the type is different, a matching method needs to be found on delegate type otherwise an exception is thrown.
*
* Possible use cases for this feature:
* <ul>
* <li>Final classes but with an interface</li>
* <li>Already custom proxied object</li>
* <li>Special objects with a finalize method, i.e. to avoid executing it 2 times</li>
* </ul>
*
* <p>The difference with the regular spy:
* <ul>
* <li>
* The regular spy ({@link #spy(Object)}) contains <strong>all</strong> state from the spied instance
* and the methods are invoked on the spy. The spied instance is only used at mock creation to copy the state from.
* If you call a method on a regular spy and it internally calls other methods on this spy, those calls are remembered
* for verifications, and they can be effectively stubbed.
* </li>
* <li>
* The mock that delegates simply delegates all methods to the delegate.
* The delegate is used all the time as methods are delegated onto it.
* If you call a method on a mock that delegates and it internally calls other methods on this mock,
* those calls are <strong>not</strong> remembered for verifications, stubbing does not have effect on them, too.
* Mock that delegates is less powerful than the regular spy but it is useful when the regular spy cannot be created.
* </li>
* </ul>
*
* <p>
* See more information in docs for {@link AdditionalAnswers#delegatesTo(Object)}.
*
*
*
*
* <h3 id="28">28. <a class="meaningful_link" href="#mock_maker_plugin" name="mock_maker_plugin"><code>MockMaker</code> API</a> (Since 1.9.5)</h3>
* <p>Driven by requirements and patches from Google Android guys Mockito now offers an extension point
* that allows replacing the proxy generation engine. By default, Mockito uses <a href="https://github.com/raphw/byte-buddy">Byte Buddy</a>
* to create dynamic proxies.
* <p>The extension point is for advanced users that want to extend Mockito. For example, it is now possible
* to use Mockito for Android testing with a help of <a href="https://github.com/crittercism/dexmaker">dexmaker</a>.
* <p>For more details, motivations and examples please refer to
* the docs for {@link org.mockito.plugins.MockMaker}.
*
*
*
*
* <h3 id="29">29. <a class="meaningful_link" href="#BDD_behavior_verification" name="BDD_behavior_verification">BDD style verification</a> (Since 1.10.0)</h3>
*
* Enables Behavior Driven Development (BDD) style verification by starting verification with the BDD <b>then</b> keyword.
*
* <pre class="code"><code class="java">
* given(dog.bark()).willReturn(2);
*
* // when
* ...
*
* then(person).should(times(2)).ride(bike);
* </code></pre>
*
* For more information and an example see {@link BDDMockito#then(Object)}}
*
*
*
*
* <h3 id="30">30. <a class="meaningful_link" href="#spying_abstract_classes" name="spying_abstract_classes">Spying or mocking abstract classes (Since 1.10.12, further enhanced in 2.7.13 and 2.7.14)</a></h3>
*
* It is now possible to conveniently spy on abstract classes. Note that overusing spies hints at code design smells (see {@link #spy(Object)}).
* <p>
* Previously, spying was only possible on instances of objects.
* New API makes it possible to use constructor when creating an instance of the mock.
* This is particularly useful for mocking abstract classes because the user is no longer required to provide an instance of the abstract class.
* At the moment, only parameter-less constructor is supported, let us know if it is not enough.
*
* <pre class="code"><code class="java">
* //convenience API, new overloaded spy() method:
* SomeAbstract spy = spy(SomeAbstract.class);
*
* //Mocking abstract methods, spying default methods of an interface (only avilable since 2.7.13)
* Function<Foo, Bar> function = spy(Function.class);
*
* //Robust API, via settings builder:
* OtherAbstract spy = mock(OtherAbstract.class, withSettings()
* .useConstructor().defaultAnswer(CALLS_REAL_METHODS));
*
* //Mocking an abstract class with constructor arguments (only available since 2.7.14)
* SomeAbstract spy = mock(SomeAbstract.class, withSettings()
* .useConstructor("arg1", 123).defaultAnswer(CALLS_REAL_METHODS));
*
* //Mocking a non-static inner abstract class:
* InnerAbstract spy = mock(InnerAbstract.class, withSettings()
* .useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS));
* </code></pre>
*
* For more information please see {@link MockSettings#useConstructor(Object...)}.
*
*
*
*
* <h3 id="31">31. <a class="meaningful_link" href="#serilization_across_classloader" name="serilization_across_classloader">Mockito mocks can be <em>serialized</em> / <em>deserialized</em> across classloaders (Since 1.10.0)</a></h3>
*
* Mockito introduces serialization across classloader.
*
* Like with any other form of serialization, all types in the mock hierarchy have to serializable, inclusing answers.
* As this serialization mode require considerably more work, this is an opt-in setting.
*
* <pre class="code"><code class="java">
* // use regular serialization
* mock(Book.class, withSettings().serializable());
*
* // use serialization across classloaders
* mock(Book.class, withSettings().serializable(ACROSS_CLASSLOADERS));
* </code></pre>
*
* For more details see {@link MockSettings#serializable(SerializableMode)}.
*
*
*
*
* <h3 id="32">32. <a class="meaningful_link" href="#better_generic_support_with_deep_stubs" name="better_generic_support_with_deep_stubs">Better generic support with deep stubs (Since 1.10.0)</a></h3>
*
* Deep stubbing has been improved to find generic information if available in the class.
* That means that classes like this can be used without having to mock the behavior.
*
* <pre class="code"><code class="java">
* class Lines extends List<Line> {
* // ...
* }
*
* lines = mock(Lines.class, RETURNS_DEEP_STUBS);
*
* // Now Mockito understand this is not an Object but a Line
* Line line = lines.iterator().next();
* </code></pre>
*
* Please note that in most scenarios a mock returning a mock is wrong.
*
*
*
*
* <h3 id="33">33. <a class="meaningful_link" href="#mockito_junit_rule" name="mockito_junit_rule">Mockito JUnit rule (Since 1.10.17)</a></h3>
*
* Mockito now offers a JUnit rule. Until now in JUnit there were two ways to initialize fields annotated by Mockito annotations
* such as <code>@{@link Mock}</code>, <code>@{@link Spy}</code>, <code>@{@link InjectMocks}</code>, etc.
*
* <ul>
* <li>Annotating the JUnit test class with a <code>@{@link org.junit.runner.RunWith}({@link MockitoJUnitRunner}.class)</code></li>
* <li>Invoking <code>{@link MockitoAnnotations#initMocks(Object)}</code> in the <code>@{@link org.junit.Before}</code> method</li>
* </ul>
*
* Now you can choose to use a rule :
*
* <pre class="code"><code class="java">
* @RunWith(YetAnotherRunner.class)
* public class TheTest {
* @Rule public MockitoRule mockito = MockitoJUnit.rule();
* // ...
* }
* </code></pre>
*
* For more information see {@link MockitoJUnit#rule()}.
*
*
*
*
* <h3 id="34">34. <a class="meaningful_link" href="#plugin_switch" name="plugin_switch">Switch <em>on</em> or <em>off</em> plugins (Since 1.10.15)</a></h3>
*
* An incubating feature made it's way in mockito that will allow to toggle a mockito-plugin.
*
* More information here {@link org.mockito.plugins.PluginSwitch}.
*
*
* <h3 id="35">35. <a class="meaningful_link" href="#BDD_behavior_verification" name="BDD_behavior_verification">Custom verification failure message</a> (Since 2.1.0)</h3>
* <p>
* Allows specifying a custom message to be printed if verification fails.
* <p>
* Examples:
* <p>
* <pre class="code"><code class="java">
*
* // will print a custom message on verification failure
* verify(mock, description("This will print on failure")).someMethod();
*
* // will work with any verification mode
* verify(mock, times(2).description("someMethod should be called twice")).someMethod();
* </code></pre>
*
* <h3 id="36">36. <a class="meaningful_link" href="#Java_8_Lambda_Matching" name="Java_8_Lambda_Matching">Java 8 Lambda Matcher Support</a> (Since 2.1.0)</h3>
* <p>
* You can use Java 8 lambda expressions with {@link ArgumentMatcher} to reduce the dependency on {@link ArgumentCaptor}.
* If you need to verify that the input to a function call on a mock was correct, then you would normally
* use the {@link ArgumentCaptor} to find the operands used and then do subsequent assertions on them. While
* for complex examples this can be useful, it's also long-winded.<p>
* Writing a lambda to express the match is quite easy. The argument to your function, when used in conjunction
* with argThat, will be passed to the ArgumentMatcher as a strongly typed object, so it is possible
* to do anything with it.
* <p>
* Examples:
* <p>
* <pre class="code"><code class="java">
*
* // verify a list only had strings of a certain length added to it
* // note - this will only compile under Java 8
* verify(list, times(2)).add(argThat(string -> string.length() < 5));
*
* // Java 7 equivalent - not as neat
* verify(list, times(2)).add(argThat(new ArgumentMatcher<String>(){
* public boolean matches(String arg) {
* return arg.length() < 5;
* }
* }));
*
* // more complex Java 8 example - where you can specify complex verification behaviour functionally
* verify(target, times(1)).receiveComplexObject(argThat(obj -> obj.getSubObject().get(0).equals("expected")));
*
* // this can also be used when defining the behaviour of a mock under different inputs
* // in this case if the input list was fewer than 3 items the mock returns null
* when(mock.someMethod(argThat(list -> list.size()<3))).willReturn(null);
* </code></pre>
*
* <h3 id="37">37. <a class="meaningful_link" href="#Java_8_Custom_Answers" name="Java_8_Custom_Answers">Java 8 Custom Answer Support</a> (Since 2.1.0)</h3>
* <p>
* As the {@link Answer} interface has just one method it is already possible to implement it in Java 8 using
* a lambda expression for very simple situations. The more you need to use the parameters of the method call,
* the more you need to typecast the arguments from {@link org.mockito.invocation.InvocationOnMock}.
*
* <p>
* Examples:
* <p>
* <pre class="code"><code class="java">
* // answer by returning 12 every time
* doAnswer(invocation -> 12).when(mock).doSomething();
*
* // answer by using one of the parameters - converting into the right
* // type as your go - in this case, returning the length of the second string parameter
* // as the answer. This gets long-winded quickly, with casting of parameters.
* doAnswer(invocation -> ((String)invocation.getArgument(1)).length())
* .when(mock).doSomething(anyString(), anyString(), anyString());
* </code></pre>
*
* For convenience it is possible to write custom answers/actions, which use the parameters to the method call,
* as Java 8 lambdas. Even in Java 7 and lower these custom answers based on a typed interface can reduce boilerplate.
* In particular, this approach will make it easier to test functions which use callbacks.
*
* The methods {@link AdditionalAnswers#answer(Answer1) answer} and {@link AdditionalAnswers#answerVoid(VoidAnswer1) answerVoid}
* can be used to create the answer. They rely on the related answer interfaces in {@link org.mockito.stubbing} that
* support answers up to 5 parameters.
*
* <p>
* Examples:
* <p>
* <pre class="code"><code class="java">
*
* // Example interface to be mocked has a function like:
* void execute(String operand, Callback callback);
*
* // the example callback has a function and the class under test
* // will depend on the callback being invoked
* void receive(String item);
*
* // Java 8 - style 1
* doAnswer(AdditionalAnswers.<String,Callback>answerVoid((operand, callback) -> callback.receive("dummy"))
* .when(mock).execute(anyString(), any(Callback.class));
*
* // Java 8 - style 2 - assuming static import of AdditionalAnswers
* doAnswer(answerVoid((String operand, Callback callback) -> callback.receive("dummy"))
* .when(mock).execute(anyString(), any(Callback.class));
*
* // Java 8 - style 3 - where mocking function to is a static member of test class
* private static void dummyCallbackImpl(String operation, Callback callback) {
* callback.receive("dummy");
* }
*
* doAnswer(answerVoid(TestClass::dummyCallbackImpl)
* .when(mock).execute(anyString(), any(Callback.class));
*
* // Java 7
* doAnswer(answerVoid(new VoidAnswer2<String, Callback>() {
* public void answer(String operation, Callback callback) {
* callback.receive("dummy");
* }})).when(mock).execute(anyString(), any(Callback.class));
*
* // returning a value is possible with the answer() function
* // and the non-void version of the functional interfaces
* // so if the mock interface had a method like
* boolean isSameString(String input1, String input2);
*
* // this could be mocked
* // Java 8
* doAnswer(AdditionalAnswers.<Boolean,String,String>answer((input1, input2) -> input1.equals(input2))))
* .when(mock).execute(anyString(), anyString());
*
* // Java 7
* doAnswer(answer(new Answer2<String, String, String>() {
* public String answer(String input1, String input2) {
* return input1 + input2;
* }})).when(mock).execute(anyString(), anyString());
* </code></pre>
*
* <h3 id="38">38. <a class="meaningful_link" href="#Meta_Data_And_Generics" name="Meta_Data_And_Generics">Meta data and generic type retention</a> (Since 2.1.0)</h3>
*
* <p>
* Mockito now preserves annotations on mocked methods and types as well as generic meta data. Previously, a mock type did not preserve
* annotations on types unless they were explicitly inherited and never retained annotations on methods. As a consequence, the following
* conditions now hold true:
*
* <pre class="code"><code class="java">
* {@literal @}{@code MyAnnotation
* class Foo {
* List<String> bar() { ... }
* }
*
* Class<?> mockType = mock(Foo.class).getClass();
* assert mockType.isAnnotationPresent(MyAnnotation.class);
* assert mockType.getDeclaredMethod("bar").getGenericReturnType() instanceof ParameterizedType;
* }</code></pre>
*
* <p>
* When using Java 8, Mockito now also preserves type annotations. This is default behavior and might not hold <a href="#28">if an
* alternative {@link org.mockito.plugins.MockMaker} is used</a>.
*
* <h3 id="39">39. <a class="meaningful_link" href="#Mocking_Final" name="Mocking_Final">Mocking final types, enums and final methods</a> (Since 2.1.0)</h3>
*
* Mockito now offers an {@link Incubating}, optional support for mocking final classes and methods.
* This is a fantastic improvement that demonstrates Mockito's everlasting quest for improving testing experience.
* Our ambition is that Mockito "just works" with final classes and methods.
* Previously they were considered <em>unmockable</em>, preventing the user from mocking.
* We already started discussing how to make this feature enabled by default.
* Currently, the feature is still optional as we wait for more feedback from the community.
*
* <p>
* This feature is turned off by default because it is based on completely different mocking mechanism
* that requires more feedback from the community.
*
* <p>
* This alternative mock maker which uses
* a combination of both Java instrumentation API and sub-classing rather than creating a new class to represent
* a mock. This way, it becomes possible to mock final types and methods.
*
* <p>
* This mock maker is <strong>turned off by default</strong> because it is based on completely different mocking mechanism
* that requires more feedback from the community. It can be activated explicitly by the mockito extension mechanism,
* just create in the classpath a file <code>/mockito-extensions/org.mockito.plugins.MockMaker</code>
* containing the value <code>mock-maker-inline</code>.
*
* <p>
* As a convenience, the Mockito team provides an artifact where this mock maker is preconfigured. Instead of using the
* <i>mockito-core</i> artifact, include the <i>mockito-inline</i> artifact in your project. Note that this artifact is
* likely to be discontinued once mocking of final classes and methods gets integrated into the default mock maker.
*
* <p>
* Some noteworthy notes about this mock maker:
* <ul>
* <li>Mocking final types and enums is incompatible with mock settings like :
* <ul>
* <li>explicitly serialization support <code>withSettings().serializable()</code></li>
* <li>extra-interfaces <code>withSettings().extraInterfaces()</code></li>
* </ul>
* </li>
* <li>Some methods cannot be mocked
* <ul>
* <li>Package-visible methods of <code>java.*</code></li>
* <li><code>native</code> methods</li>
* </ul>
* </li>
* <li>This mock maker has been designed around Java Agent runtime attachment ; this require a compatible JVM,
* that is part of the JDK (or Java 9 VM). When running on a non-JDK VM prior to Java 9, it is however possible to
* manually add the <a href="http://bytebuddy.net">Byte Buddy Java agent jar</a> using the <code>-javaagent</code>
* parameter upon starting the JVM.
* </li>
* </ul>
*
* <p>
* If you are interested in more details of this feature please read the javadoc of
* <code>org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker</code>
*
* <h3 id="40">40. <a class="meaningful_link" href="#strict_mockito" name="strict_mockito">
* (**new**) Improved productivity and cleaner tests with "stricter" Mockito</a> (Since 2.+)</h3>
*
* To quickly find out how "stricter" Mockito can make you more productive and get your tests cleaner, see:
* <ul>
* <li>Strict stubbing with JUnit Rules - {@link MockitoRule#strictness(Strictness)} with {@link Strictness#STRICT_STUBS}</li>
* <li>Strict stubbing with JUnit Runner - {@link MockitoJUnitRunner.StrictStubs.class}</li>
* <li>Strict stubbing if you cannot use runner/rule (like TestNG) - {@link MockitoSession}</li>
* <li>Unnecessary stubbing detection with {@link MockitoJUnitRunner}</li>
* <li>Stubbing argument mismatch warnings, documented in {@link MockitoHint}</li>
* </ul>
*
* Mockito is a "loose" mocking framework by default.
* Mocks can be interacted with without setting any expectations beforehand.
* This is intentional and it improves the quality of tests by forcing users to be explicit about what they want to stub / verify.
* It is also very intuitive, easy to use and blends nicely with "given", "when", "then" template of clean test code.
* This is also different from the classic mocking frameworks of the past, they were "strict" by default.
* <p>
* Being "loose" by default makes Mockito tests harder to debug at times.
* There are scenarios where misconfigured stubbing (like using a wrong argument) forces the user to run the test with a debugger.
* Ideally, tests failures are immediately obvious and don't require debugger to identify the root cause.
* Starting with version 2.1 Mockito has been getting new features that nudge the framework towards "strictness".
* We want Mockito to offer fantastic debuggability while not losing its core mocking style, optimized for
* intuitiveness, explicitness and clean test code.
* <p>
* Help Mockito! Try the new features, give us feedback, join the discussion about Mockito strictness at GitHub
* <a href="https://github.com/mockito/mockito/issues/769">issue 769</a>.
*/
@SuppressWarnings("unchecked")
public class Mockito extends ArgumentMatchers {
static final MockitoCore MOCKITO_CORE = new MockitoCore();
/**
* The default <code>Answer</code> of every mock <b>if</b> the mock was not stubbed.
*
* Typically it just returns some empty value.
* <p>
* {@link Answer} can be used to define the return values of unstubbed invocations.
* <p>
* This implementation first tries the global configuration and if there is no global configuration then
* it will use a default answer that returns zeros, empty collections, nulls, etc.
*/
public static final Answer<Object> RETURNS_DEFAULTS = Answers.RETURNS_DEFAULTS;
/**
* Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}.
* <p>
* {@link Answer} can be used to define the return values of unstubbed invocations.
* <p>
* This implementation can be helpful when working with legacy code.
* Unstubbed methods often return null. If your code uses the object returned by an unstubbed call you get a NullPointerException.
* This implementation of Answer <b>returns SmartNull instead of null</b>.
* <code>SmartNull</code> gives nicer exception message than NPE because it points out the line where unstubbed method was called. You just click on the stack trace.
* <p>
* <code>ReturnsSmartNulls</code> first tries to return ordinary values (zeros, empty collections, empty string, etc.)
* then it tries to return SmartNull. If the return type is final then plain <code>null</code> is returned.
* <p>
* <code>ReturnsSmartNulls</code> will be probably the default return values strategy in Mockito 3.0.0
* <p>
* Example:
* <pre class="code"><code class="java">
* Foo mock = mock(Foo.class, RETURNS_SMART_NULLS);
*
* //calling unstubbed method here:
* Stuff stuff = mock.getStuff();
*
* //using object returned by unstubbed call:
* stuff.doSomething();
*
* //Above doesn't yield NullPointerException this time!
* //Instead, SmartNullPointerException is thrown.
* //Exception's cause links to unstubbed <i>mock.getStuff()</i> - just click on the stack trace.
* </code></pre>
*/
public static final Answer<Object> RETURNS_SMART_NULLS = Answers.RETURNS_SMART_NULLS;
/**
* Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}
* <p>
* {@link Answer} can be used to define the return values of unstubbed invocations.
* <p>
* This implementation can be helpful when working with legacy code.
* <p>
* ReturnsMocks first tries to return ordinary values (zeros, empty collections, empty string, etc.)
* then it tries to return mocks. If the return type cannot be mocked (e.g. is final) then plain <code>null</code> is returned.
* <p>
*/
public static final Answer<Object> RETURNS_MOCKS = Answers.RETURNS_MOCKS;
/**
* Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}.
* <p>
* Example that shows how deep stub works:
* <pre class="code"><code class="java">
* Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS);
*
* // note that we're stubbing a chain of methods here: getBar().getName()
* when(mock.getBar().getName()).thenReturn("deep");
*
* // note that we're chaining method calls: getBar().getName()
* assertEquals("deep", mock.getBar().getName());
* </code></pre>
* </p>
*
* <p>
* <strong>WARNING: </strong>
* This feature should rarely be required for regular clean code! Leave it for legacy code.
* Mocking a mock to return a mock, to return a mock, (...), to return something meaningful
* hints at violation of Law of Demeter or mocking a value object (a well known anti-pattern).
* </p>
*
* <p>
* Good quote I've seen one day on the web: <strong>every time a mock returns a mock a fairy dies</strong>.
* </p>
*
* <p>
* Please note that this answer will return existing mocks that matches the stub. This
* behavior is ok with deep stubs and allows verification to work on the last mock of the chain.
* <pre class="code"><code class="java">
* when(mock.getBar(anyString()).getThingy().getName()).thenReturn("deep");
*
* mock.getBar("candy bar").getThingy().getName();
*
* assertSame(mock.getBar(anyString()).getThingy().getName(), mock.getBar(anyString()).getThingy().getName());
* verify(mock.getBar("candy bar").getThingy()).getName();
* verify(mock.getBar(anyString()).getThingy()).getName();
* </code></pre>
* </p>
*
* <p>
* Verification only works with the last mock in the chain. You can use verification modes.
* <pre class="code"><code class="java">
* when(person.getAddress(anyString()).getStreet().getName()).thenReturn("deep");
* when(person.getAddress(anyString()).getStreet(Locale.ITALIAN).getName()).thenReturn("deep");
* when(person.getAddress(anyString()).getStreet(Locale.CHINESE).getName()).thenReturn("deep");
*
* person.getAddress("the docks").getStreet().getName();
* person.getAddress("the docks").getStreet().getLongName();
* person.getAddress("the docks").getStreet(Locale.ITALIAN).getName();
* person.getAddress("the docks").getStreet(Locale.CHINESE).getName();
*
* // note that we are actually referring to the very last mock in the stubbing chain.
* InOrder inOrder = inOrder(
* person.getAddress("the docks").getStreet(),
* person.getAddress("the docks").getStreet(Locale.CHINESE),
* person.getAddress("the docks").getStreet(Locale.ITALIAN)
* );
* inOrder.verify(person.getAddress("the docks").getStreet(), times(1)).getName();
* inOrder.verify(person.getAddress("the docks").getStreet()).getLongName();
* inOrder.verify(person.getAddress("the docks").getStreet(Locale.ITALIAN), atLeast(1)).getName();
* inOrder.verify(person.getAddress("the docks").getStreet(Locale.CHINESE)).getName();
* </code></pre>
* </p>
*
* <p>
* How deep stub work internally?
* <pre class="code"><code class="java">
* //this:
* Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS);
* when(mock.getBar().getName(), "deep");
*
* //is equivalent of
* Foo foo = mock(Foo.class);
* Bar bar = mock(Bar.class);
* when(foo.getBar()).thenReturn(bar);
* when(bar.getName()).thenReturn("deep");
* </code></pre>
* </p>
*
* <p>
* This feature will not work when any return type of methods included in the chain cannot be mocked
* (for example: is a primitive or a final class). This is because of java type system.
* </p>
*/
public static final Answer<Object> RETURNS_DEEP_STUBS = Answers.RETURNS_DEEP_STUBS;
/**
* Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}
* <p>
* {@link Answer} can be used to define the return values of unstubbed invocations.
* <p>
* This implementation can be helpful when working with legacy code.
* When this implementation is used, unstubbed methods will delegate to the real implementation.
* This is a way to create a partial mock object that calls real methods by default.
* <p>
* As usual you are going to read <b>the partial mock warning</b>:
* Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
* How does partial mock fit into this paradigm? Well, it just doesn't...
* Partial mock usually means that the complexity has been moved to a different method on the same object.
* In most cases, this is not the way you want to design your application.
* <p>
* However, there are rare cases when partial mocks come handy:
* dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
* However, I wouldn't use partial mocks for new, test-driven & well-designed code.
* <p>
* Example:
* <pre class="code"><code class="java">
* Foo mock = mock(Foo.class, CALLS_REAL_METHODS);
*
* // this calls the real implementation of Foo.getSomething()
* value = mock.getSomething();
*
* when(mock.getSomething()).thenReturn(fakeValue);
*
* // now fakeValue is returned
* value = mock.getSomething();
* </code></pre>
*/
public static final Answer<Object> CALLS_REAL_METHODS = Answers.CALLS_REAL_METHODS;
/**
* Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}.
*
* Allows Builder mocks to return itself whenever a method is invoked that returns a Type equal
* to the class or a superclass.
*
* <p><b>Keep in mind this answer uses the return type of a method.
* If this type is assignable to the class of the mock, it will return the mock.
* Therefore if you have a method returning a superclass (for example {@code Object}) it will match and return the mock.</b></p>
*
* Consider a HttpBuilder used in a HttpRequesterWithHeaders.
*
* <pre class="code"><code class="java">
* public class HttpRequesterWithHeaders {
*
* private HttpBuilder builder;
*
* public HttpRequesterWithHeaders(HttpBuilder builder) {
* this.builder = builder;
* }
*
* public String request(String uri) {
* return builder.withUrl(uri)
* .withHeader("Content-type: application/json")
* .withHeader("Authorization: Bearer")
* .request();
* }
* }
*
* private static class HttpBuilder {
*
* private String uri;
* private List<String> headers;
*
* public HttpBuilder() {
* this.headers = new ArrayList<String>();
* }
*
* public HttpBuilder withUrl(String uri) {
* this.uri = uri;
* return this;
* }
*
* public HttpBuilder withHeader(String header) {
* this.headers.add(header);
* return this;
* }
*
* public String request() {
* return uri + headers.toString();
* }
* }
* </code></pre>
*
* The following test will succeed
*
* <pre><code>
* @Test
* public void use_full_builder_with_terminating_method() {
* HttpBuilder builder = mock(HttpBuilder.class, RETURNS_SELF);
* HttpRequesterWithHeaders requester = new HttpRequesterWithHeaders(builder);
* String response = "StatusCode: 200";
*
* when(builder.request()).thenReturn(response);
*
* assertThat(requester.request("URI")).isEqualTo(response);
* }
* </code></pre>
*/
public static final Answer<Object> RETURNS_SELF = Answers.RETURNS_SELF;
/**
* Creates mock object of given class or interface.
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param classToMock class or interface to mock
* @return mock object
*/
public static <T> T mock(Class<T> classToMock) {
return mock(classToMock, withSettings());
}
/**
* Specifies mock name. Naming mocks can be helpful for debugging - the name is used in all verification errors.
* <p>
* Beware that naming mocks is not a solution for complex code which uses too many mocks or collaborators.
* <b>If you have too many mocks then refactor the code</b> so that it's easy to test/debug without necessity of naming mocks.
* <p>
* <b>If you use <code>@Mock</code> annotation then you've got naming mocks for free!</b> <code>@Mock</code> uses field name as mock name. {@link Mock Read more.}
* <p>
*
* See examples in javadoc for {@link Mockito} class
*
* @param classToMock class or interface to mock
* @param name of the mock
* @return mock object
*/
public static <T> T mock(Class<T> classToMock, String name) {
return mock(classToMock, withSettings()
.name(name)
.defaultAnswer(RETURNS_DEFAULTS));
}
/**
* Returns a MockingDetails instance that enables inspecting a particular object for Mockito related information.
* Can be used to find out if given object is a Mockito mock
* or to find out if a given mock is a spy or mock.
* <p>
* In future Mockito versions MockingDetails may grow and provide other useful information about the mock,
* e.g. invocations, stubbing info, etc.
*
* @param toInspect - object to inspect. null input is allowed.
* @return A {@link org.mockito.MockingDetails} instance.
* @since 1.9.5
*/
public static MockingDetails mockingDetails(Object toInspect) {
return MOCKITO_CORE.mockingDetails(toInspect);
}
/**
* Creates mock with a specified strategy for its answers to interactions.
* It's quite an advanced feature and typically you don't need it to write decent tests.
* However it can be helpful when working with legacy systems.
* <p>
* It is the default answer so it will be used <b>only when you don't</b> stub the method call.
*
* <pre class="code"><code class="java">
* Foo mock = mock(Foo.class, RETURNS_SMART_NULLS);
* Foo mockTwo = mock(Foo.class, new YourOwnAnswer());
* </code></pre>
*
* <p>See examples in javadoc for {@link Mockito} class</p>
*
* @param classToMock class or interface to mock
* @param defaultAnswer default answer for unstubbed methods
*
* @return mock object
*/
public static <T> T mock(Class<T> classToMock, Answer defaultAnswer) {
return mock(classToMock, withSettings().defaultAnswer(defaultAnswer));
}
/**
* Creates a mock with some non-standard settings.
* <p>
* The number of configuration points for a mock grows
* so we need a fluent way to introduce new configuration without adding more and more overloaded Mockito.mock() methods.
* Hence {@link MockSettings}.
* <pre class="code"><code class="java">
* Listener mock = mock(Listener.class, withSettings()
* .name("firstListner").defaultBehavior(RETURNS_SMART_NULLS));
* );
* </code></pre>
* <b>Use it carefully and occasionally</b>. What might be reason your test needs non-standard mocks?
* Is the code under test so complicated that it requires non-standard mocks?
* Wouldn't you prefer to refactor the code under test so it is testable in a simple way?
* <p>
* See also {@link Mockito#withSettings()}
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param classToMock class or interface to mock
* @param mockSettings additional mock settings
* @return mock object
*/
public static <T> T mock(Class<T> classToMock, MockSettings mockSettings) {
return MOCKITO_CORE.mock(classToMock, mockSettings);
}
/**
* Creates a spy of the real object. The spy calls <b>real</b> methods unless they are stubbed.
* <p>
* Real spies should be used <b>carefully and occasionally</b>, for example when dealing with legacy code.
* <p>
* As usual you are going to read <b>the partial mock warning</b>:
* Object oriented programming tackles complexity by dividing the complexity into separate, specific, SRPy objects.
* How does partial mock fit into this paradigm? Well, it just doesn't...
* Partial mock usually means that the complexity has been moved to a different method on the same object.
* In most cases, this is not the way you want to design your application.
* <p>
* However, there are rare cases when partial mocks come handy:
* dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
* However, I wouldn't use partial mocks for new, test-driven & well-designed code.
* <p>
* Example:
*
* <pre class="code"><code class="java">
* List list = new LinkedList();
* List spy = spy(list);
*
* //optionally, you can stub out some methods:
* when(spy.size()).thenReturn(100);
*
* //using the spy calls <b>real</b> methods
* spy.add("one");
* spy.add("two");
*
* //prints "one" - the first element of a list
* System.out.println(spy.get(0));
*
* //size() method was stubbed - 100 is printed
* System.out.println(spy.size());
*
* //optionally, you can verify
* verify(spy).add("one");
* verify(spy).add("two");
* </code></pre>
*
* <h4>Important gotcha on spying real objects!</h4>
* <ol>
* <li>Sometimes it's impossible or impractical to use {@link Mockito#when(Object)} for stubbing spies.
* Therefore for spies it is recommended to always use <code>doReturn</code>|<code>Answer</code>|<code>Throw()</code>|<code>CallRealMethod</code>
* family of methods for stubbing. Example:
*
* <pre class="code"><code class="java">
* List list = new LinkedList();
* List spy = spy(list);
*
* //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
* when(spy.get(0)).thenReturn("foo");
*
* //You have to use doReturn() for stubbing
* doReturn("foo").when(spy).get(0);
* </code></pre>
* </li>
*
* <li>Mockito <b>*does not*</b> delegate calls to the passed real instance, instead it actually creates a copy of it.
* So if you keep the real instance and interact with it, don't expect the spied to be aware of those interaction
* and their effect on real instance state.
* The corollary is that when an <b>*unstubbed*</b> method is called <b>*on the spy*</b> but <b>*not on the real instance*</b>,
* you won't see any effects on the real instance.</li>
*
* <li>Watch out for final methods.
* Mockito doesn't mock final methods so the bottom line is: when you spy on real objects + you try to stub a final method = trouble.
* Also you won't be able to verify those method as well.
* </li>
* </ol>
* <p>
* See examples in javadoc for {@link Mockito} class
*
* <p>Note that the spy won't have any annotations of the spied type, because CGLIB won't rewrite them.
* It may troublesome for code that rely on the spy to have these annotations.</p>
*
*
* @param object
* to spy on
* @return a spy of the real object
*/
public static <T> T spy(T object) {
return MOCKITO_CORE.mock((Class<T>) object.getClass(), withSettings()
.spiedInstance(object)
.defaultAnswer(CALLS_REAL_METHODS));
}
/**
* Please refer to the documentation of {@link #spy(Object)}.
* Overusing spies hints at code design smells.
* <p>
* This method, in contrast to the original {@link #spy(Object)}, creates a spy based on class instead of an object.
* Sometimes it is more convenient to create spy based on the class and avoid providing an instance of a spied object.
* This is particularly useful for spying on abstract classes because they cannot be instantiated.
* See also {@link MockSettings#useConstructor(Object...)}.
* <p>
* Examples:
* <pre class="code"><code class="java">
* SomeAbstract spy = spy(SomeAbstract.class);
*
* //Robust API, via settings builder:
* OtherAbstract spy = mock(OtherAbstract.class, withSettings()
* .useConstructor().defaultAnswer(CALLS_REAL_METHODS));
*
* //Mocking a non-static inner abstract class:
* InnerAbstract spy = mock(InnerAbstract.class, withSettings()
* .useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS));
* </code></pre>
*
* @param classToSpy the class to spy
* @param <T> type of the spy
* @return a spy of the provided class
* @since 1.10.12
*/
@Incubating
public static <T> T spy(Class<T> classToSpy) {
return MOCKITO_CORE.mock(classToSpy, withSettings()
.useConstructor()
.defaultAnswer(CALLS_REAL_METHODS));
}
/**
* Enables stubbing methods. Use it when you want the mock to return particular value when particular method is called.
* <p>
* Simply put: "<b>When</b> the x method is called <b>then</b> return y".
*
* <p>
* Examples:
*
* <pre class="code"><code class="java">
* <b>when</b>(mock.someMethod()).<b>thenReturn</b>(10);
*
* //you can use flexible argument matchers, e.g:
* when(mock.someMethod(<b>anyString()</b>)).thenReturn(10);
*
* //setting exception to be thrown:
* when(mock.someMethod("some arg")).thenThrow(new RuntimeException());
*
* //you can set different behavior for consecutive method calls.
* //Last stubbing (e.g: thenReturn("foo")) determines the behavior of further consecutive calls.
* when(mock.someMethod("some arg"))
* .thenThrow(new RuntimeException())
* .thenReturn("foo");
*
* //Alternative, shorter version for consecutive stubbing:
* when(mock.someMethod("some arg"))
* .thenReturn("one", "two");
* //is the same as:
* when(mock.someMethod("some arg"))
* .thenReturn("one")
* .thenReturn("two");
*
* //shorter version for consecutive method calls throwing exceptions:
* when(mock.someMethod("some arg"))
* .thenThrow(new RuntimeException(), new NullPointerException();
*
* </code></pre>
*
* For stubbing void methods with throwables see: {@link Mockito#doThrow(Throwable...)}
* <p>
* Stubbing can be overridden: for example common stubbing can go to fixture
* setup but the test methods can override it.
* Please note that overridding stubbing is a potential code smell that points out too much stubbing.
* <p>
* Once stubbed, the method will always return stubbed value regardless
* of how many times it is called.
* <p>
* Last stubbing is more important - when you stubbed the same method with
* the same arguments many times.
* <p>
* Although it is possible to verify a stubbed invocation, usually <b>it's just redundant</b>.
* Let's say you've stubbed <code>foo.bar()</code>.
* If your code cares what <code>foo.bar()</code> returns then something else breaks(often before even <code>verify()</code> gets executed).
* If your code doesn't care what <code>get(0)</code> returns then it should not be stubbed.
* Not convinced? See <a href="http://monkeyisland.pl/2008/04/26/asking-and-telling">here</a>.
*
* <p>
* See examples in javadoc for {@link Mockito} class
* @param methodCall method to be stubbed
* @return OngoingStubbing object used to stub fluently.
* <strong>Do not</strong> create a reference to this returned object.
*/
public static <T> OngoingStubbing<T> when(T methodCall) {
return MOCKITO_CORE.when(methodCall);
}
/**
* Verifies certain behavior <b>happened once</b>.
* <p>
* Alias to <code>verify(mock, times(1))</code> E.g:
* <pre class="code"><code class="java">
* verify(mock).someMethod("some arg");
* </code></pre>
* Above is equivalent to:
* <pre class="code"><code class="java">
* verify(mock, times(1)).someMethod("some arg");
* </code></pre>
* <p>
* Arguments passed are compared using <code>equals()</code> method.
* Read about {@link ArgumentCaptor} or {@link ArgumentMatcher} to find out other ways of matching / asserting arguments passed.
* <p>
* Although it is possible to verify a stubbed invocation, usually <b>it's just redundant</b>.
* Let's say you've stubbed <code>foo.bar()</code>.
* If your code cares what <code>foo.bar()</code> returns then something else breaks(often before even <code>verify()</code> gets executed).
* If your code doesn't care what <code>get(0)</code> returns then it should not be stubbed.
* Not convinced? See <a href="http://monkeyisland.pl/2008/04/26/asking-and-telling">here</a>.
*
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param mock to be verified
* @return mock object itself
*/
public static <T> T verify(T mock) {
return MOCKITO_CORE.verify(mock, times(1));
}
/**
* Verifies certain behavior happened at least once / exact number of times / never. E.g:
* <pre class="code"><code class="java">
* verify(mock, times(5)).someMethod("was called five times");
*
* verify(mock, atLeast(2)).someMethod("was called at least two times");
*
* //you can use flexible argument matchers, e.g:
* verify(mock, atLeastOnce()).someMethod(<b>anyString()</b>);
* </code></pre>
*
* <b>times(1) is the default</b> and can be omitted
* <p>
* Arguments passed are compared using <code>equals()</code> method.
* Read about {@link ArgumentCaptor} or {@link ArgumentMatcher} to find out other ways of matching / asserting arguments passed.
* <p>
*
* @param mock to be verified
* @param mode times(x), atLeastOnce() or never()
*
* @return mock object itself
*/
public static <T> T verify(T mock, VerificationMode mode) {
return MOCKITO_CORE.verify(mock, mode);
}
/**
* Smart Mockito users hardly use this feature because they know it could be a sign of poor tests.
* Normally, you don't need to reset your mocks, just create new mocks for each test method.
* <p>
* Instead of <code>#reset()</code> please consider writing simple, small and focused test methods over lengthy, over-specified tests.
* <b>First potential code smell is <code>reset()</code> in the middle of the test method.</b> This probably means you're testing too much.
* Follow the whisper of your test methods: "Please keep us small & focused on single behavior".
* There are several threads about it on mockito mailing list.
* <p>
* The only reason we added <code>reset()</code> method is to
* make it possible to work with container-injected mocks.
* For more information see the FAQ (<a href="https://github.com/mockito/mockito/wiki/FAQ">here</a>).
* <p>
* <b>Don't harm yourself.</b> <code>reset()</code> in the middle of the test method is a code smell (you're probably testing too much).
* <pre class="code"><code class="java">
* List mock = mock(List.class);
* when(mock.size()).thenReturn(10);
* mock.add(1);
*
* reset(mock);
* //at this point the mock forgot any interactions & stubbing
* </code></pre>
*
* @param <T> The Type of the mocks
* @param mocks to be reset
*/
public static <T> void reset(T ... mocks) {
MOCKITO_CORE.reset(mocks);
}
/**
* Use this method in order to only clear invocations, when stubbing is non-trivial. Use-cases can be:
* <ul>
* <li>You are using a dependency injection framework to inject your mocks.</li>
* <li>The mock is used in a stateful scenario. For example a class is Singleton which depends on your mock.</li>
* </ul>
*
* <b>Try to avoid this method at all costs. Only clear invocations if you are unable to efficiently test your program.</b>
* @param <T> The type of the mocks
* @param mocks The mocks to clear the invocations for
*/
public static <T> void clearInvocations(T ... mocks) {
MOCKITO_CORE.clearInvocations(mocks);
}
/**
* Checks if any of given mocks has any unverified interaction.
* <p>
* You can use this method after you verified your mocks - to make sure that nothing
* else was invoked on your mocks.
* <p>
* See also {@link Mockito#never()} - it is more explicit and communicates the intent well.
* <p>
* Stubbed invocations (if called) are also treated as interactions.
* <p>
* A word of <b>warning</b>:
* Some users who did a lot of classic, expect-run-verify mocking tend to use <code>verifyNoMoreInteractions()</code> very often, even in every test method.
* <code>verifyNoMoreInteractions()</code> is not recommended to use in every test method.
* <code>verifyNoMoreInteractions()</code> is a handy assertion from the interaction testing toolkit. Use it only when it's relevant.
* Abusing it leads to overspecified, less maintainable tests. You can find further reading
* <a href="http://monkeyisland.pl/2008/07/12/should-i-worry-about-the-unexpected/">here</a>.
* <p>
* This method will also detect unverified invocations that occurred before the test method,
* for example: in <code>setUp()</code>, <code>@Before</code> method or in constructor.
* Consider writing nice code that makes interactions only in test methods.
*
* <p>
* Example:
*
* <pre class="code"><code class="java">
* //interactions
* mock.doSomething();
* mock.doSomethingUnexpected();
*
* //verification
* verify(mock).doSomething();
*
* //following will fail because 'doSomethingUnexpected()' is unexpected
* verifyNoMoreInteractions(mock);
*
* </code></pre>
*
* See examples in javadoc for {@link Mockito} class
*
* @param mocks to be verified
*/
public static void verifyNoMoreInteractions(Object... mocks) {
MOCKITO_CORE.verifyNoMoreInteractions(mocks);
}
/**
* Verifies that no interactions happened on given mocks.
* <pre class="code"><code class="java">
* verifyZeroInteractions(mockOne, mockTwo);
* </code></pre>
* This method will also detect invocations
* that occurred before the test method, for example: in <code>setUp()</code>, <code>@Before</code> method or in constructor.
* Consider writing nice code that makes interactions only in test methods.
* <p>
* See also {@link Mockito#never()} - it is more explicit and communicates the intent well.
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param mocks to be verified
*/
public static void verifyZeroInteractions(Object... mocks) {
MOCKITO_CORE.verifyNoMoreInteractions(mocks);
}
/**
* Use <code>doThrow()</code> when you want to stub the void method with an exception.
* <p>
* Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler
* does not like void methods inside brackets...
* <p>
* Example:
*
* <pre class="code"><code class="java">
* doThrow(new RuntimeException()).when(mock).someVoidMethod();
* </code></pre>
*
* @param toBeThrown to be thrown when the stubbed method is called
* @return stubber - to select a method for stubbing
*/
public static Stubber doThrow(Throwable... toBeThrown) {
return MOCKITO_CORE.stubber().doThrow(toBeThrown);
}
/**
* Use <code>doThrow()</code> when you want to stub the void method with an exception.
* <p>
* A new exception instance will be created for each method invocation.
* <p>
* Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler
* does not like void methods inside brackets...
* <p>
* Example:
*
* <pre class="code"><code class="java">
* doThrow(RuntimeException.class).when(mock).someVoidMethod();
* </code></pre>
*
* @param toBeThrown to be thrown when the stubbed method is called
* @return stubber - to select a method for stubbing
* @since 2.1.0
*/
public static Stubber doThrow(Class<? extends Throwable> toBeThrown) {
return MOCKITO_CORE.stubber().doThrow(toBeThrown);
}
/**
* Same as {@link #doThrow(Class)} but sets consecutive exception classes to be thrown. Remember to use
* <code>doThrow()</code> when you want to stub the void method to throw several exception of specified class.
* <p>
* A new exception instance will be created for each method invocation.
* <p>
* Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler
* does not like void methods inside brackets...
* <p>
* Example:
*
* <pre class="code"><code class="java">
* doThrow(RuntimeException.class, BigFailure.class).when(mock).someVoidMethod();
* </code></pre>
*
* @param toBeThrown to be thrown when the stubbed method is called
* @param toBeThrownNext next to be thrown when the stubbed method is called
* @return stubber - to select a method for stubbing
* @since 2.1.0
*/
// Additional method helps users of JDK7+ to hide heap pollution / unchecked generics array creation
@SuppressWarnings ({"unchecked", "varargs"})
public static Stubber doThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... toBeThrownNext) {
return MOCKITO_CORE.stubber().doThrow(toBeThrown, toBeThrownNext);
}
/**
* Use <code>doCallRealMethod()</code> when you want to call the real implementation of a method.
* <p>
* As usual you are going to read <b>the partial mock warning</b>:
* Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
* How does partial mock fit into this paradigm? Well, it just doesn't...
* Partial mock usually means that the complexity has been moved to a different method on the same object.
* In most cases, this is not the way you want to design your application.
* <p>
* However, there are rare cases when partial mocks come handy:
* dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
* However, I wouldn't use partial mocks for new, test-driven & well-designed code.
* <p>
* See also javadoc {@link Mockito#spy(Object)} to find out more about partial mocks.
* <b>Mockito.spy() is a recommended way of creating partial mocks.</b>
* The reason is it guarantees real methods are called against correctly constructed object because you're responsible for constructing the object passed to spy() method.
* <p>
* Example:
* <pre class="code"><code class="java">
* Foo mock = mock(Foo.class);
* doCallRealMethod().when(mock).someVoidMethod();
*
* // this will call the real implementation of Foo.someVoidMethod()
* mock.someVoidMethod();
* </code></pre>
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @return stubber - to select a method for stubbing
* @since 1.9.5
*/
public static Stubber doCallRealMethod() {
return MOCKITO_CORE.stubber().doCallRealMethod();
}
/**
* Use <code>doAnswer()</code> when you want to stub a void method with generic {@link Answer}.
* <p>
* Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler does not like void methods inside brackets...
* <p>
* Example:
*
* <pre class="code"><code class="java">
* doAnswer(new Answer() {
* public Object answer(InvocationOnMock invocation) {
* Object[] args = invocation.getArguments();
* Mock mock = invocation.getMock();
* return null;
* }})
* .when(mock).someMethod();
* </code></pre>
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param answer to answer when the stubbed method is called
* @return stubber - to select a method for stubbing
*/
public static Stubber doAnswer(Answer answer) {
return MOCKITO_CORE.stubber().doAnswer(answer);
}
/**
* Use <code>doNothing()</code> for setting void methods to do nothing. <b>Beware that void methods on mocks do nothing by default!</b>
* However, there are rare situations when doNothing() comes handy:
* <p>
* <ol>
* <li>Stubbing consecutive calls on a void method:
* <pre class="code"><code class="java">
* doNothing().
* doThrow(new RuntimeException())
* .when(mock).someVoidMethod();
*
* //does nothing the first time:
* mock.someVoidMethod();
*
* //throws RuntimeException the next time:
* mock.someVoidMethod();
* </code></pre>
* </li>
* <li>When you spy real objects and you want the void method to do nothing:
* <pre class="code"><code class="java">
* List list = new LinkedList();
* List spy = spy(list);
*
* //let's make clear() do nothing
* doNothing().when(spy).clear();
*
* spy.add("one");
*
* //clear() does nothing, so the list still contains "one"
* spy.clear();
* </code></pre>
* </li>
* </ol>
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @return stubber - to select a method for stubbing
*/
public static Stubber doNothing() {
return MOCKITO_CORE.stubber().doNothing();
}
/**
* Use <code>doReturn()</code> in those rare occasions when you cannot use {@link Mockito#when(Object)}.
* <p>
* <b>Beware that {@link Mockito#when(Object)} is always recommended for stubbing because it is argument type-safe
* and more readable</b> (especially when stubbing consecutive calls).
* <p>
* Here are those rare occasions when doReturn() comes handy:
* <p>
*
* <ol>
* <li>When spying real objects and calling real methods on a spy brings side effects
*
* <pre class="code"><code class="java">
* List list = new LinkedList();
* List spy = spy(list);
*
* //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
* when(spy.get(0)).thenReturn("foo");
*
* //You have to use doReturn() for stubbing:
* doReturn("foo").when(spy).get(0);
* </code></pre>
* </li>
*
* <li>Overriding a previous exception-stubbing:
* <pre class="code"><code class="java">
* when(mock.foo()).thenThrow(new RuntimeException());
*
* //Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown.
* when(mock.foo()).thenReturn("bar");
*
* //You have to use doReturn() for stubbing:
* doReturn("bar").when(mock).foo();
* </code></pre>
* </li>
* </ol>
*
* Above scenarios shows a tradeoff of Mockito's elegant syntax. Note that the scenarios are very rare, though.
* Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general
* overridding stubbing is a potential code smell that points out too much stubbing.
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param toBeReturned to be returned when the stubbed method is called
* @return stubber - to select a method for stubbing
*/
public static Stubber doReturn(Object toBeReturned) {
return MOCKITO_CORE.stubber().doReturn(toBeReturned);
}
/**
* Same as {@link #doReturn(Object)} but sets consecutive values to be returned. Remember to use
* <code>doReturn()</code> in those rare occasions when you cannot use {@link Mockito#when(Object)}.
* <p>
* <b>Beware that {@link Mockito#when(Object)} is always recommended for stubbing because it is argument type-safe
* and more readable</b> (especially when stubbing consecutive calls).
* <p>
* Here are those rare occasions when doReturn() comes handy:
* <p>
*
* <ol>
* <li>When spying real objects and calling real methods on a spy brings side effects
*
* <pre class="code"><code class="java">
* List list = new LinkedList();
* List spy = spy(list);
*
* //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
* when(spy.get(0)).thenReturn("foo", "bar", "qix");
*
* //You have to use doReturn() for stubbing:
* doReturn("foo", "bar", "qix").when(spy).get(0);
* </code></pre>
* </li>
*
* <li>Overriding a previous exception-stubbing:
* <pre class="code"><code class="java">
* when(mock.foo()).thenThrow(new RuntimeException());
*
* //Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown.
* when(mock.foo()).thenReturn("bar", "foo", "qix");
*
* //You have to use doReturn() for stubbing:
* doReturn("bar", "foo", "qix").when(mock).foo();
* </code></pre>
* </li>
* </ol>
*
* Above scenarios shows a trade-off of Mockito's elegant syntax. Note that the scenarios are very rare, though.
* Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general
* overridding stubbing is a potential code smell that points out too much stubbing.
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param toBeReturned to be returned when the stubbed method is called
* @param toBeReturnedNext to be returned in consecutive calls when the stubbed method is called
* @return stubber - to select a method for stubbing
* @since 2.1.0
*/
@SuppressWarnings({"unchecked", "varargs"})
public static Stubber doReturn(Object toBeReturned, Object... toBeReturnedNext) {
return MOCKITO_CORE.stubber().doReturn(toBeReturned, toBeReturnedNext);
}
/**
* Creates {@link org.mockito.InOrder} object that allows verifying mocks in order.
*
* <pre class="code"><code class="java">
* InOrder inOrder = inOrder(firstMock, secondMock);
*
* inOrder.verify(firstMock).add("was called first");
* inOrder.verify(secondMock).add("was called second");
* </code></pre>
*
* Verification in order is flexible - <b>you don't have to verify all interactions</b> one-by-one
* but only those that you are interested in testing in order.
* <p>
* Also, you can create InOrder object passing only mocks that are relevant for in-order verification.
* <p>
* <code>InOrder</code> verification is 'greedy', but you will hardly ever notice it.
* If you want to find out more, read
* <a href="https://github.com/mockito/mockito/wiki/Greedy-algorithm-of-verfication-InOrder">this wiki page</a>.
* <p>
* As of Mockito 1.8.4 you can verifyNoMoreInvocations() in order-sensitive way. Read more: {@link InOrder#verifyNoMoreInteractions()}
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param mocks to be verified in order
*
* @return InOrder object to be used to verify in order
*/
public static InOrder inOrder(Object... mocks) {
return MOCKITO_CORE.inOrder(mocks);
}
/**
* Ignores stubbed methods of given mocks for the sake of verification.
* Sometimes useful when coupled with <code>verifyNoMoreInteractions()</code> or verification <code>inOrder()</code>.
* Helps avoiding redundant verification of stubbed calls - typically we're not interested in verifying stubs.
* <p>
* <b>Warning</b>, <code>ignoreStubs()</code> might lead to overuse of <code>verifyNoMoreInteractions(ignoreStubs(...));</code>
* Bear in mind that Mockito does not recommend bombarding every test with <code>verifyNoMoreInteractions()</code>
* for the reasons outlined in javadoc for {@link Mockito#verifyNoMoreInteractions(Object...)}
* Other words: all <b>*stubbed*</b> methods of given mocks are marked <b>*verified*</b> so that they don't get in a way during verifyNoMoreInteractions().
* <p>
* This method <b>changes the input mocks</b>! This method returns input mocks just for convenience.
* <p>
* Ignored stubs will also be ignored for verification inOrder, including {@link org.mockito.InOrder#verifyNoMoreInteractions()}.
* See the second example.
* <p>
* Example:
* <pre class="code"><code class="java">
* //mocking lists for the sake of the example (if you mock List in real you will burn in hell)
* List mock1 = mock(List.class), mock2 = mock(List.class);
*
* //stubbing mocks:
* when(mock1.get(0)).thenReturn(10);
* when(mock2.get(0)).thenReturn(20);
*
* //using mocks by calling stubbed get(0) methods:
* System.out.println(mock1.get(0)); //prints 10
* System.out.println(mock2.get(0)); //prints 20
*
* //using mocks by calling clear() methods:
* mock1.clear();
* mock2.clear();
*
* //verification:
* verify(mock1).clear();
* verify(mock2).clear();
*
* //verifyNoMoreInteractions() fails because get() methods were not accounted for.
* try { verifyNoMoreInteractions(mock1, mock2); } catch (NoInteractionsWanted e);
*
* //However, if we ignore stubbed methods then we can verifyNoMoreInteractions()
* verifyNoMoreInteractions(ignoreStubs(mock1, mock2));
*
* //Remember that ignoreStubs() <b>*changes*</b> the input mocks and returns them for convenience.
* </code></pre>
* Ignoring stubs can be used with <b>verification in order</b>:
* <pre class="code"><code class="java">
* List list = mock(List.class);
* when(mock.get(0)).thenReturn("foo");
*
* list.add(0);
* System.out.println(list.get(0)); //we don't want to verify this
* list.clear();
*
* InOrder inOrder = inOrder(ignoreStubs(list));
* inOrder.verify(list).add(0);
* inOrder.verify(list).clear();
* inOrder.verifyNoMoreInteractions();
* </code></pre>
*
* @since 1.9.0
* @param mocks input mocks that will be changed
* @return the same mocks that were passed in as parameters
*/
public static Object[] ignoreStubs(Object... mocks) {
return MOCKITO_CORE.ignoreStubs(mocks);
}
/**
* Allows verifying exact number of invocations. E.g:
* <pre class="code"><code class="java">
* verify(mock, times(2)).someMethod("some arg");
* </code></pre>
*
* See examples in javadoc for {@link Mockito} class
*
* @param wantedNumberOfInvocations wanted number of invocations
*
* @return verification mode
*/
public static VerificationMode times(int wantedNumberOfInvocations) {
return VerificationModeFactory.times(wantedNumberOfInvocations);
}
/**
* Alias to <code>times(0)</code>, see {@link Mockito#times(int)}
* <p>
* Verifies that interaction did not happen. E.g:
* <pre class="code"><code class="java">
* verify(mock, never()).someMethod();
* </code></pre>
*
* <p>
* If you want to verify there were NO interactions with the mock
* check out {@link Mockito#verifyZeroInteractions(Object...)}
* or {@link Mockito#verifyNoMoreInteractions(Object...)}
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @return verification mode
*/
public static VerificationMode never() {
return times(0);
}
/**
* Allows at-least-once verification. E.g:
* <pre class="code"><code class="java">
* verify(mock, atLeastOnce()).someMethod("some arg");
* </code></pre>
* Alias to <code>atLeast(1)</code>.
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @return verification mode
*/
public static VerificationMode atLeastOnce() {
return VerificationModeFactory.atLeastOnce();
}
/**
* Allows at-least-x verification. E.g:
* <pre class="code"><code class="java">
* verify(mock, atLeast(3)).someMethod("some arg");
* </code></pre>
*
* See examples in javadoc for {@link Mockito} class
*
* @param minNumberOfInvocations minimum number of invocations
*
* @return verification mode
*/
public static VerificationMode atLeast(int minNumberOfInvocations) {
return VerificationModeFactory.atLeast(minNumberOfInvocations);
}
/**
* Allows at-most-x verification. E.g:
* <pre class="code"><code class="java">
* verify(mock, atMost(3)).someMethod("some arg");
* </code></pre>
*
* See examples in javadoc for {@link Mockito} class
*
* @param maxNumberOfInvocations max number of invocations
*
* @return verification mode
*/
public static VerificationMode atMost(int maxNumberOfInvocations) {
return VerificationModeFactory.atMost(maxNumberOfInvocations);
}
/**
* Allows non-greedy verification in order. For example
* <pre class="code"><code class="java">
* inOrder.verify( mock, calls( 2 )).someMethod( "some arg" );
* </code></pre>
* <ul>
* <li>will not fail if the method is called 3 times, unlike times( 2 )</li>
* <li>will not mark the third invocation as verified, unlike atLeast( 2 )</li>
* </ul>
* This verification mode can only be used with in order verification.
* @param wantedNumberOfInvocations number of invocations to verify
* @return verification mode
*/
public static VerificationMode calls( int wantedNumberOfInvocations ){
return VerificationModeFactory.calls( wantedNumberOfInvocations );
}
/**
* Allows checking if given method was the only one invoked. E.g:
* <pre class="code"><code class="java">
* verify(mock, only()).someMethod();
* //above is a shorthand for following 2 lines of code:
* verify(mock).someMethod();
* verifyNoMoreInvocations(mock);
* </code></pre>
*
* <p>
* See also {@link Mockito#verifyNoMoreInteractions(Object...)}
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @return verification mode
*/
public static VerificationMode only() {
return VerificationModeFactory.only();
}
/**
* Allows verifying with timeout. It causes a verify to wait for a specified period of time for a desired
* interaction rather than fails immediately if has not already happened. May be useful for testing in concurrent
* conditions.
* <p>
* This differs from {@link Mockito#after after()} in that after() will wait the full period, unless
* the final test result is known early (e.g. if a never() fails), whereas timeout() will stop early as soon
* as verification passes, producing different behaviour when used with times(2), for example, which can pass
* and then later fail. In that case, timeout would pass as soon as times(2) passes, whereas after would run until
* times(2) failed, and then fail.
* <p>
* This feature should be used rarely - figure out a better way of testing your multi-threaded system.
* <pre class="code"><code class="java">
* //passes when someMethod() is called within given time span
* verify(mock, timeout(100)).someMethod();
* //above is an alias to:
* verify(mock, timeout(100).times(1)).someMethod();
*
* //passes as soon as someMethod() has been called 2 times before the given timeout
* verify(mock, timeout(100).times(2)).someMethod();
*
* //equivalent: this also passes as soon as someMethod() has been called 2 times before the given timeout
* verify(mock, timeout(100).atLeast(2)).someMethod();
*
* //verifies someMethod() within given time span using given verification mode
* //useful only if you have your own custom verification modes.
* verify(mock, new Timeout(100, yourOwnVerificationMode)).someMethod();
* </code></pre>
*
* See examples in javadoc for {@link Mockito} class
*
* @param millis - time span in milliseconds
*
* @return verification mode
*/
public static VerificationWithTimeout timeout(long millis) {
return new Timeout(millis, VerificationModeFactory.times(1));
}
/**
* Allows verifying over a given period. It causes a verify to wait for a specified period of time for a desired
* interaction rather than failing immediately if has not already happened. May be useful for testing in concurrent
* conditions.
* <p>
* This differs from {@link Mockito#timeout timeout()} in that after() will wait the full period, whereas timeout()
* will stop early as soon as verification passes, producing different behaviour when used with times(2), for example,
* which can pass and then later fail. In that case, timeout would pass as soon as times(2) passes, whereas after would
* run the full time, which point it will fail, as times(2) has failed.
* <p>
* This feature should be used rarely - figure out a better way of testing your multi-threaded system.
* <p>
* Not yet implemented to work with InOrder verification.
* <pre class="code"><code class="java">
* //passes after 100ms, if someMethod() has only been called once at that time.
* verify(mock, after(100)).someMethod();
* //above is an alias to:
* verify(mock, after(100).times(1)).someMethod();
*
* //passes if someMethod() is called <b>*exactly*</b> 2 times after the given timespan
* verify(mock, after(100).times(2)).someMethod();
*
* //passes if someMethod() has not been called after the given timespan
* verify(mock, after(100).never()).someMethod();
*
* //verifies someMethod() after a given time span using given verification mode
* //useful only if you have your own custom verification modes.
* verify(mock, new After(100, yourOwnVerificationMode)).someMethod();
* </code></pre>
*
* See examples in javadoc for {@link Mockito} class
*
* @param millis - time span in milliseconds
*
* @return verification mode
*/
public static VerificationAfterDelay after(long millis) {
return new After(millis, VerificationModeFactory.times(1));
}
/**
* First of all, in case of any trouble, I encourage you to read the Mockito FAQ: <a href="https://github.com/mockito/mockito/wiki/FAQ">https://github.com/mockito/mockito/wiki/FAQ</a>
* <p>
* In case of questions you may also post to mockito mailing list: <a href="http://groups.google.com/group/mockito">http://groups.google.com/group/mockito</a>
* <p>
* <code>validateMockitoUsage()</code> <b>explicitly validates</b> the framework state to detect invalid use of Mockito.
* However, this feature is optional <b>because Mockito validates the usage all the time...</b> but there is a gotcha so read on.
* <p>
* Examples of incorrect use:
* <pre class="code"><code class="java">
* //Oops, thenReturn() part is missing:
* when(mock.get());
*
* //Oops, verified method call is inside verify() where it should be on the outside:
* verify(mock.execute());
*
* //Oops, missing method to verify:
* verify(mock);
* </code></pre>
*
* Mockito throws exceptions if you misuse it so that you know if your tests are written correctly.
* The gotcha is that Mockito does the validation <b>next time</b> you use the framework (e.g. next time you verify, stub, call mock etc.).
* But even though the exception might be thrown in the next test,
* the exception <b>message contains a navigable stack trace element</b> with location of the defect.
* Hence you can click and find the place where Mockito was misused.
* <p>
* Sometimes though, you might want to validate the framework usage explicitly.
* For example, one of the users wanted to put <code>validateMockitoUsage()</code> in his <code>@After</code> method
* so that he knows immediately when he misused Mockito.
* Without it, he would have known about it not sooner than <b>next time</b> he used the framework.
* One more benefit of having <code>validateMockitoUsage()</code> in <code>@After</code> is that jUnit runner and rule will always fail in the test method with defect
* whereas ordinary 'next-time' validation might fail the <b>next</b> test method.
* But even though JUnit might report next test as red, don't worry about it
* and just click at navigable stack trace element in the exception message to instantly locate the place where you misused mockito.
* <p>
* <b>Both built-in runner: {@link MockitoJUnitRunner} and rule: {@link MockitoRule}</b> do validateMockitoUsage() after each test method.
* <p>
* Bear in mind that <b>usually you don't have to <code>validateMockitoUsage()</code></b>
* and framework validation triggered on next-time basis should be just enough,
* mainly because of enhanced exception message with clickable location of defect.
* However, I would recommend validateMockitoUsage() if you already have sufficient test infrastructure
* (like your own runner or base class for all tests) because adding a special action to <code>@After</code> has zero cost.
* <p>
* See examples in javadoc for {@link Mockito} class
*/
public static void validateMockitoUsage() {
MOCKITO_CORE.validateMockitoUsage();
}
/**
* Allows mock creation with additional mock settings.
* <p>
* Don't use it too often.
* Consider writing simple tests that use simple mocks.
* Repeat after me: simple tests push simple, KISSy, readable & maintainable code.
* If you cannot write a test in a simple way - refactor the code under test.
* <p>
* Examples of mock settings:
* <pre class="code"><code class="java">
* //Creates mock with different default answer & name
* Foo mock = mock(Foo.class, withSettings()
* .defaultAnswer(RETURNS_SMART_NULLS)
* .name("cool mockie"));
*
* //Creates mock with different default answer, descriptive name and extra interfaces
* Foo mock = mock(Foo.class, withSettings()
* .defaultAnswer(RETURNS_SMART_NULLS)
* .name("cool mockie")
* .extraInterfaces(Bar.class));
* </code></pre>
* {@link MockSettings} has been introduced for two reasons.
* Firstly, to make it easy to add another mock settings when the demand comes.
* Secondly, to enable combining different mock settings without introducing zillions of overloaded mock() methods.
* <p>
* See javadoc for {@link MockSettings} to learn about possible mock settings.
* <p>
*
* @return mock settings instance with defaults.
*/
public static MockSettings withSettings() {
return new MockSettingsImpl().defaultAnswer(RETURNS_DEFAULTS);
}
/**
* Adds a description to be printed if verification fails.
* <pre class="code"><code class="java">
* verify(mock, description("This will print on failure")).someMethod("some arg");
* </code></pre>
* @param description The description to print on failure.
* @return verification mode
* @since 2.1.0
*/
public static VerificationMode description(String description) {
return times(1).description(description);
}
/**
* @deprecated - please use {@link MockingDetails#printInvocations()}.
*/
@Deprecated
static MockitoDebugger debug() {
return new MockitoDebuggerImpl();
}
/**
* For advanced users or framework integrators. See {@link MockitoFramework} class.
*
* @since 2.1.0
*/
@Incubating
public static MockitoFramework framework() {
return new DefaultMockitoFramework();
}
/**
* {@code MockitoSession} is an optional, highly recommended feature
* that helps driving cleaner tests by eliminating boilerplate code and adding extra validation.
* <p>
* For more information, including use cases and sample code, see the javadoc for {@link MockitoSession}.
*
* @since 2.7.0
*/
@Incubating
public static MockitoSessionBuilder mockitoSession() {
return new DefaultMockitoSessionBuilder();
}
}
| src/main/java/org/mockito/Mockito.java | /*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito;
import org.mockito.internal.MockitoCore;
import org.mockito.internal.creation.MockSettingsImpl;
import org.mockito.internal.debugging.MockitoDebuggerImpl;
import org.mockito.internal.framework.DefaultMockitoFramework;
import org.mockito.internal.session.DefaultMockitoSessionBuilder;
import org.mockito.internal.verification.VerificationModeFactory;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.MockitoRule;
import org.mockito.mock.SerializableMode;
import org.mockito.quality.MockitoHint;
import org.mockito.quality.Strictness;
import org.mockito.session.MockitoSessionBuilder;
import org.mockito.stubbing.*;
import org.mockito.verification.*;
/**
* <p align="left"><img src="logo.png" srcset="[email protected] 2x" alt="Mockito logo"/></p>
* The Mockito library enables mock creation, verification and stubbing.
*
* <p>
* This javadoc content is also available on the <a href="http://mockito.org">http://mockito.org</a> web page.
* All documentation is kept in javadocs because it guarantees consistency between what's on the web and what's in the source code.
* It allows access to documentation straight from the IDE even if you work offline.
* It motivates Mockito developers to keep documentation up-to-date with the code that they write,
* every day, with every commit.
*
* <h1>Contents</h1>
*
* <b>
* <a href="#0">0. Migrating to Mockito 2</a><br/>
* <a href="#0.1">0.1 Mockito Android support</a></br/>
* <a href="#0.2">0.2 Configuration-free inline mock making</a></br/>
* <a href="#1">1. Let's verify some behaviour! </a><br/>
* <a href="#2">2. How about some stubbing? </a><br/>
* <a href="#3">3. Argument matchers </a><br/>
* <a href="#4">4. Verifying exact number of invocations / at least once / never </a><br/>
* <a href="#5">5. Stubbing void methods with exceptions </a><br/>
* <a href="#6">6. Verification in order </a><br/>
* <a href="#7">7. Making sure interaction(s) never happened on mock </a><br/>
* <a href="#8">8. Finding redundant invocations </a><br/>
* <a href="#9">9. Shorthand for mocks creation - <code>@Mock</code> annotation </a><br/>
* <a href="#10">10. Stubbing consecutive calls (iterator-style stubbing) </a><br/>
* <a href="#11">11. Stubbing with callbacks </a><br/>
* <a href="#12">12. <code>doReturn()</code>|<code>doThrow()</code>|<code>doAnswer()</code>|<code>doNothing()</code>|<code>doCallRealMethod()</code> family of methods</a><br/>
* <a href="#13">13. Spying on real objects </a><br/>
* <a href="#14">14. Changing default return values of unstubbed invocations (Since 1.7) </a><br/>
* <a href="#15">15. Capturing arguments for further assertions (Since 1.8.0) </a><br/>
* <a href="#16">16. Real partial mocks (Since 1.8.0) </a><br/>
* <a href="#17">17. Resetting mocks (Since 1.8.0) </a><br/>
* <a href="#18">18. Troubleshooting & validating framework usage (Since 1.8.0) </a><br/>
* <a href="#19">19. Aliases for behavior driven development (Since 1.8.0) </a><br/>
* <a href="#20">20. Serializable mocks (Since 1.8.1) </a><br/>
* <a href="#21">21. New annotations: <code>@Captor</code>, <code>@Spy</code>, <code>@InjectMocks</code> (Since 1.8.3) </a><br/>
* <a href="#22">22. Verification with timeout (Since 1.8.5) </a><br/>
* <a href="#23">23. Automatic instantiation of <code>@Spies</code>, <code>@InjectMocks</code> and constructor injection goodness (Since 1.9.0)</a><br/>
* <a href="#24">24. One-liner stubs (Since 1.9.0)</a><br/>
* <a href="#25">25. Verification ignoring stubs (Since 1.9.0)</a><br/>
* <a href="#26">26. Mocking details (Improved in 2.2.x)</a><br/>
* <a href="#27">27. Delegate calls to real instance (Since 1.9.5)</a><br/>
* <a href="#28">28. <code>MockMaker</code> API (Since 1.9.5)</a><br/>
* <a href="#29">29. BDD style verification (Since 1.10.0)</a><br/>
* <a href="#30">30. Spying or mocking abstract classes (Since 1.10.12, further enhanced in 2.7.13 and 2.7.14)</a><br/>
* <a href="#31">31. Mockito mocks can be <em>serialized</em> / <em>deserialized</em> across classloaders (Since 1.10.0)</a></h3><br/>
* <a href="#32">32. Better generic support with deep stubs (Since 1.10.0)</a></h3><br/>
* <a href="#32">33. Mockito JUnit rule (Since 1.10.17)</a><br/>
* <a href="#34">34. Switch <em>on</em> or <em>off</em> plugins (Since 1.10.15)</a><br/>
* <a href="#35">35. Custom verification failure message (Since 2.1.0)</a><br/>
* <a href="#36">36. Java 8 Lambda Matcher Support (Since 2.1.0)</a><br/>
* <a href="#37">37. Java 8 Custom Answer Support (Since 2.1.0)</a><br/>
* <a href="#38">38. Meta data and generic type retention (Since 2.1.0)</a><br/>
* <a href="#39">39. Mocking final types, enums and final methods (Since 2.1.0)</a><br/>
* <a href="#40">40. (**new**) Improved productivity and cleaner tests with "stricter" Mockito (Since 2.+)</a><br/>
* </b>
*
* <h3 id="0">0. <a class="meaningful_link" href="#mockito2" name="mockito2">Migrating to Mockito 2</a></h3>
*
* In order to continue improving Mockito and further improve the unit testing experience, we want you to upgrade to 2.1.0!
* Mockito follows <a href="http://semver.org/">semantic versioning</a> and contains breaking changes only on major version upgrades.
* In the lifecycle of a library, breaking changes are necessary
* to roll out a set of brand new features that alter the existing behavior or even change the API.
* For a comprehensive guide on the new release including incompatible changes,
* see '<a href="https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2">What's new in Mockito 2</a>' wiki page.
* We hope that you enjoy Mockito 2!
*
* <h3 id="0.1">0.1. <a class="meaningful_link" href="#mockito" name="mockito-android">Mockito Android support</a></h3>
*
* With Mockito version 2.6.1 we ship "native" Android support. To enable Android support, add the `mockito-android` library as dependency
* to your project. This artifact is published to the same Mockito organization and can be imported for Android as follows:
*
* <pre class="code"><code>
* repositories {
* jcenter()
* }
* dependencies {
* testCompile "org.mockito:mockito-core:+"
* androidTestCompile "org.mockito:mockito-android:+"
* }
* </code></pre>
*
* You can continue to run the same unit tests on a regular VM by using the `mockito-core` artifact in your "testCompile" scope as shown
* above. Be aware that you cannot use the <a href="#39">inline mock maker</a> on Android due to limitations in the Android VM.
*
* If you encounter issues with mocking on Android, please open an issue
* <a href="https://github.com/mockito/mockito/issues/new">on the official issue tracker</a>.
* Do provide the version of Android you are working on and dependencies of your project.
*
* <h3 id="0.2">0.2. <a class="meaningful_link" href="#mockito-inline" name="mockito-inline">Configuration-free inline mock making</a></h3>
*
* Starting with version 2.7.6, we offer the 'mockito-inline' artifact that enables <a href="#39">inline mock making</a> without configuring
* the MockMaker extension file. To use this, add the `mockito-inline` instead of the `mockito-core` artifact as follows:
*
* <pre class="code"><code>
* repositories {
* jcenter()
* }
* dependencies {
* testCompile "org.mockito:mockito-inline:+"
* }
* </code></pre>
*
* Be aware that this artifact may be abolished when the inline mock making feature is integrated into the default mock maker.
*
* <p>
* For more information about inline mock making, see <a href="#39">section 39</a>.
*
* <h3 id="1">1. <a class="meaningful_link" href="#verification" name="verification">Let's verify some behaviour!</a></h3>
*
* The following examples mock a List, because most people are familiar with the interface (such as the
* <code>add()</code>, <code>get()</code>, <code>clear()</code> methods). <br>
* In reality, please don't mock the List class. Use a real instance instead.
*
* <pre class="code"><code class="java">
* //Let's import Mockito statically so that the code looks clearer
* import static org.mockito.Mockito.*;
*
* //mock creation
* List mockedList = mock(List.class);
*
* //using mock object
* mockedList.add("one");
* mockedList.clear();
*
* //verification
* verify(mockedList).add("one");
* verify(mockedList).clear();
* </code></pre>
*
* <p>
* Once created, a mock will remember all interactions. Then you can selectively
* verify whatever interactions you are interested in.
*
*
*
*
* <h3 id="2">2. <a class="meaningful_link" href="#stubbing" name="stubbing">How about some stubbing?</a></h3>
*
* <pre class="code"><code class="java">
* //You can mock concrete classes, not just interfaces
* LinkedList mockedList = mock(LinkedList.class);
*
* //stubbing
* when(mockedList.get(0)).thenReturn("first");
* when(mockedList.get(1)).thenThrow(new RuntimeException());
*
* //following prints "first"
* System.out.println(mockedList.get(0));
*
* //following throws runtime exception
* System.out.println(mockedList.get(1));
*
* //following prints "null" because get(999) was not stubbed
* System.out.println(mockedList.get(999));
*
* //Although it is possible to verify a stubbed invocation, usually <b>it's just redundant</b>
* //If your code cares what get(0) returns, then something else breaks (often even before verify() gets executed).
* //If your code doesn't care what get(0) returns, then it should not be stubbed. Not convinced? See <a href="http://monkeyisland.pl/2008/04/26/asking-and-telling">here</a>.
* verify(mockedList).get(0);
* </code></pre>
*
* <ul>
* <li> By default, for all methods that return a value, a mock will return either null, a
* a primitive/primitive wrapper value, or an empty collection, as appropriate.
* For example 0 for an int/Integer and false for a boolean/Boolean. </li>
*
* <li> Stubbing can be overridden: for example common stubbing can go to
* fixture setup but the test methods can override it.
* Please note that overridding stubbing is a potential code smell that points out too much stubbing</li>
*
* <li> Once stubbed, the method will always return a stubbed value, regardless
* of how many times it is called. </li>
*
* <li> Last stubbing is more important - when you stubbed the same method with
* the same arguments many times.
* Other words: <b>the order of stubbing matters</b> but it is only meaningful rarely,
* e.g. when stubbing exactly the same method calls or sometimes when argument matchers are used, etc.</li>
*
* </ul>
*
*
*
* <h3 id="3">3. <a class="meaningful_link" href="#argument_matchers" name="argument_matchers">Argument matchers</a></h3>
*
* Mockito verifies argument values in natural java style: by using an <code>equals()</code> method.
* Sometimes, when extra flexibility is required then you might use argument matchers:
*
* <pre class="code"><code class="java">
* //stubbing using built-in anyInt() argument matcher
* when(mockedList.get(anyInt())).thenReturn("element");
*
* //stubbing using custom matcher (let's say isValid() returns your own matcher implementation):
* when(mockedList.contains(argThat(isValid()))).thenReturn("element");
*
* //following prints "element"
* System.out.println(mockedList.get(999));
*
* //<b>you can also verify using an argument matcher</b>
* verify(mockedList).get(anyInt());
*
* //<b>argument matchers can also be written as Java 8 Lambdas</b>
* verify(mockedList).add(argThat(someString -> someString.length() > 5));
*
* </code></pre>
*
* <p>
* Argument matchers allow flexible verification or stubbing.
* {@link ArgumentMatchers Click here} {@link org.mockito.hamcrest.MockitoHamcrest or here} to see more built-in matchers
* and examples of <b>custom argument matchers / hamcrest matchers</b>.
* <p>
* For information solely on <b>custom argument matchers</b> check out javadoc for {@link ArgumentMatcher} class.
* <p>
* Be reasonable with using complicated argument matching.
* The natural matching style using <code>equals()</code> with occasional <code>anyX()</code> matchers tend to give clean & simple tests.
* Sometimes it's just better to refactor the code to allow <code>equals()</code> matching or even implement <code>equals()</code> method to help out with testing.
* <p>
* Also, read <a href="#15">section 15</a> or javadoc for {@link ArgumentCaptor} class.
* {@link ArgumentCaptor} is a special implementation of an argument matcher that captures argument values for further assertions.
* <p>
* <b>Warning on argument matchers:</b>
* <p>
* If you are using argument matchers, <b>all arguments</b> have to be provided
* by matchers.
* <p>
The following example shows verification but the same applies to stubbing:
*
* <pre class="code"><code class="java">
* verify(mock).someMethod(anyInt(), anyString(), <b>eq("third argument")</b>);
* //above is correct - eq() is also an argument matcher
*
* verify(mock).someMethod(anyInt(), anyString(), <b>"third argument"</b>);
* //above is incorrect - exception will be thrown because third argument is given without an argument matcher.
* </code></pre>
*
* <p>
* Matcher methods like <code>anyObject()</code>, <code>eq()</code> <b>do not</b> return matchers.
* Internally, they record a matcher on a stack and return a dummy value (usually null).
* This implementation is due to static type safety imposed by the java compiler.
* The consequence is that you cannot use <code>anyObject()</code>, <code>eq()</code> methods outside of verified/stubbed method.
*
*
*
*
* <h3 id="4">4. <a class="meaningful_link" href="#exact_verification" name="exact_verification">Verifying exact number of invocations</a> /
* <a class="meaningful_link" href="#at_least_verification" name="at_least_verification">at least x</a> / never</h3>
*
* <pre class="code"><code class="java">
* //using mock
* mockedList.add("once");
*
* mockedList.add("twice");
* mockedList.add("twice");
*
* mockedList.add("three times");
* mockedList.add("three times");
* mockedList.add("three times");
*
* //following two verifications work exactly the same - times(1) is used by default
* verify(mockedList).add("once");
* verify(mockedList, times(1)).add("once");
*
* //exact number of invocations verification
* verify(mockedList, times(2)).add("twice");
* verify(mockedList, times(3)).add("three times");
*
* //verification using never(). never() is an alias to times(0)
* verify(mockedList, never()).add("never happened");
*
* //verification using atLeast()/atMost()
* verify(mockedList, atLeastOnce()).add("three times");
* verify(mockedList, atLeast(2)).add("five times");
* verify(mockedList, atMost(5)).add("three times");
*
* </code></pre>
*
* <p>
* <b>times(1) is the default.</b> Therefore using times(1) explicitly can be
* omitted.
*
*
*
*
* <h3 id="5">5. <a class="meaningful_link" href="#stubbing_with_exceptions" name="stubbing_with_exceptions">Stubbing void methods with exceptions</a></h3>
*
* <pre class="code"><code class="java">
* doThrow(new RuntimeException()).when(mockedList).clear();
*
* //following throws RuntimeException:
* mockedList.clear();
* </code></pre>
*
* Read more about <code>doThrow()</code>|<code>doAnswer()</code> family of methods in <a href="#12">section 12</a>.
* <p>
*
* <h3 id="6">6. <a class="meaningful_link" href="#in_order_verification" name="in_order_verification">Verification in order</a></h3>
*
* <pre class="code"><code class="java">
* // A. Single mock whose methods must be invoked in a particular order
* List singleMock = mock(List.class);
*
* //using a single mock
* singleMock.add("was added first");
* singleMock.add("was added second");
*
* //create an inOrder verifier for a single mock
* InOrder inOrder = inOrder(singleMock);
*
* //following will make sure that add is first called with "was added first, then with "was added second"
* inOrder.verify(singleMock).add("was added first");
* inOrder.verify(singleMock).add("was added second");
*
* // B. Multiple mocks that must be used in a particular order
* List firstMock = mock(List.class);
* List secondMock = mock(List.class);
*
* //using mocks
* firstMock.add("was called first");
* secondMock.add("was called second");
*
* //create inOrder object passing any mocks that need to be verified in order
* InOrder inOrder = inOrder(firstMock, secondMock);
*
* //following will make sure that firstMock was called before secondMock
* inOrder.verify(firstMock).add("was called first");
* inOrder.verify(secondMock).add("was called second");
*
* // Oh, and A + B can be mixed together at will
* </code></pre>
*
* Verification in order is flexible - <b>you don't have to verify all
* interactions</b> one-by-one but only those that you are interested in
* testing in order.
* <p>
* Also, you can create an InOrder object passing only the mocks that are relevant for
* in-order verification.
*
*
*
*
* <h3 id="7">7. <a class="meaningful_link" href="#never_verification" name="never_verification">Making sure interaction(s) never happened on mock</a></h3>
*
* <pre class="code"><code class="java">
* //using mocks - only mockOne is interacted
* mockOne.add("one");
*
* //ordinary verification
* verify(mockOne).add("one");
*
* //verify that method was never called on a mock
* verify(mockOne, never()).add("two");
*
* //verify that other mocks were not interacted
* verifyZeroInteractions(mockTwo, mockThree);
*
* </code></pre>
*
*
*
*
* <h3 id="8">8. <a class="meaningful_link" href="#finding_redundant_invocations" name="finding_redundant_invocations">Finding redundant invocations</a></h3>
*
* <pre class="code"><code class="java">
* //using mocks
* mockedList.add("one");
* mockedList.add("two");
*
* verify(mockedList).add("one");
*
* //following verification will fail
* verifyNoMoreInteractions(mockedList);
* </code></pre>
*
* A word of <b>warning</b>:
* Some users who did a lot of classic, expect-run-verify mocking tend to use <code>verifyNoMoreInteractions()</code> very often, even in every test method.
* <code>verifyNoMoreInteractions()</code> is not recommended to use in every test method.
* <code>verifyNoMoreInteractions()</code> is a handy assertion from the interaction testing toolkit. Use it only when it's relevant.
* Abusing it leads to <strong>overspecified</strong>, <strong>less maintainable</strong> tests. You can find further reading
* <a href="http://monkeyisland.pl/2008/07/12/should-i-worry-about-the-unexpected/">here</a>.
*
* <p>
* See also {@link Mockito#never()} - it is more explicit and
* communicates the intent well.
* <p>
*
*
*
*
* <h3 id="9">9. <a class="meaningful_link" href="#mock_annotation" name="mock_annotation">Shorthand for mocks creation - <code>@Mock</code> annotation</a></h3>
*
* <ul>
* <li>Minimizes repetitive mock creation code.</li>
* <li>Makes the test class more readable.</li>
* <li>Makes the verification error easier to read because the <b>field name</b>
* is used to identify the mock.</li>
* </ul>
*
* <pre class="code"><code class="java">
* public class ArticleManagerTest {
*
* @Mock private ArticleCalculator calculator;
* @Mock private ArticleDatabase database;
* @Mock private UserProvider userProvider;
*
* private ArticleManager manager;
* </code></pre>
*
* <b>Important!</b> This needs to be somewhere in the base class or a test
* runner:
*
* <pre class="code"><code class="java">
* MockitoAnnotations.initMocks(testClass);
* </code></pre>
*
* You can use built-in runner: {@link MockitoJUnitRunner} or a rule: {@link MockitoRule}.
* <p>
* Read more here: {@link MockitoAnnotations}
*
*
*
*
* <h3 id="10">10. <a class="meaningful_link" href="#stubbing_consecutive_calls" name="stubbing_consecutive_calls">Stubbing consecutive calls</a> (iterator-style stubbing)</h3>
*
* Sometimes we need to stub with different return value/exception for the same
* method call. Typical use case could be mocking iterators.
* Original version of Mockito did not have this feature to promote simple mocking.
* For example, instead of iterators one could use {@link Iterable} or simply
* collections. Those offer natural ways of stubbing (e.g. using real
* collections). In rare scenarios stubbing consecutive calls could be useful,
* though:
* <p>
*
* <pre class="code"><code class="java">
* when(mock.someMethod("some arg"))
* .thenThrow(new RuntimeException())
* .thenReturn("foo");
*
* //First call: throws runtime exception:
* mock.someMethod("some arg");
*
* //Second call: prints "foo"
* System.out.println(mock.someMethod("some arg"));
*
* //Any consecutive call: prints "foo" as well (last stubbing wins).
* System.out.println(mock.someMethod("some arg"));
* </code></pre>
*
* Alternative, shorter version of consecutive stubbing:
*
* <pre class="code"><code class="java">
* when(mock.someMethod("some arg"))
* .thenReturn("one", "two", "three");
* </code></pre>
*
* <strong>Warning</strong> : if instead of chaining {@code .thenReturn()} calls, multiple stubbing with the same matchers or arguments
* is used, then each stubbing will override the previous one:
*
* <pre class="code"><code class="java">
* //All mock.someMethod("some arg") calls will return "two"
* when(mock.someMethod("some arg"))
* .thenReturn("one")
* when(mock.someMethod("some arg"))
* .thenReturn("two")
* </code></pre>
*
*
*
* <h3 id="11">11. <a class="meaningful_link" href="#answer_stubs" name="answer_stubs">Stubbing with callbacks</a></h3>
*
* Allows stubbing with generic {@link Answer} interface.
* <p>
* Yet another controversial feature which was not included in Mockito
* originally. We recommend simply stubbing with <code>thenReturn()</code> or
* <code>thenThrow()</code>, which should be enough to test/test-drive
* any clean & simple code. However, if you do have a need to stub with the generic Answer interface, here is an example:
*
* <pre class="code"><code class="java">
* when(mock.someMethod(anyString())).thenAnswer(new Answer() {
* Object answer(InvocationOnMock invocation) {
* Object[] args = invocation.getArguments();
* Object mock = invocation.getMock();
* return "called with arguments: " + args;
* }
* });
*
* //the following prints "called with arguments: foo"
* System.out.println(mock.someMethod("foo"));
* </code></pre>
*
*
*
*
* <h3 id="12">12. <a class="meaningful_link" href="#do_family_methods_stubs" name="do_family_methods_stubs"><code>doReturn()</code>|<code>doThrow()</code>|
* <code>doAnswer()</code>|<code>doNothing()</code>|<code>doCallRealMethod()</code> family of methods</a></h3>
*
* Stubbing void methods requires a different approach from {@link Mockito#when(Object)} because the compiler does not
* like void methods inside brackets...
* <p>
* Use <code>doThrow()</code> when you want to stub a void method with an exception:
* <pre class="code"><code class="java">
* doThrow(new RuntimeException()).when(mockedList).clear();
*
* //following throws RuntimeException:
* mockedList.clear();
* </code></pre>
* </p>
*
* <p>
* You can use <code>doThrow()</code>, <code>doAnswer()</code>, <code>doNothing()</code>, <code>doReturn()</code>
* and <code>doCallRealMethod()</code> in place of the corresponding call with <code>when()</code>, for any method.
* It is necessary when you
* <ul>
* <li>stub void methods</li>
* <li>stub methods on spy objects (see below)</li>
* <li>stub the same method more than once, to change the behaviour of a mock in the middle of a test.</li>
* </ul>
* but you may prefer to use these methods in place of the alternative with <code>when()</code>, for all of your stubbing calls.
* <p>
* Read more about these methods:
* <p>
* {@link Mockito#doReturn(Object)}
* <p>
* {@link Mockito#doThrow(Throwable...)}
* <p>
* {@link Mockito#doThrow(Class)}
* <p>
* {@link Mockito#doAnswer(Answer)}
* <p>
* {@link Mockito#doNothing()}
* <p>
* {@link Mockito#doCallRealMethod()}
*
*
*
*
* <h3 id="13">13. <a class="meaningful_link" href="#spy" name="spy">Spying on real objects</a></h3>
*
* You can create spies of real objects. When you use the spy then the <b>real</b> methods are called
* (unless a method was stubbed).
* <p>
* Real spies should be used <b>carefully and occasionally</b>, for example when dealing with legacy code.
*
* <p>
* Spying on real objects can be associated with "partial mocking" concept.
* <b>Before the release 1.8</b>, Mockito spies were not real partial mocks.
* The reason was we thought partial mock is a code smell.
* At some point we found legitimate use cases for partial mocks
* (3rd party interfaces, interim refactoring of legacy code, the full article is
* <a href="http://monkeyisland.pl/2009/01/13/subclass-and-override-vs-partial-mocking-vs-refactoring">here</a>)
* <p>
*
* <pre class="code"><code class="java">
* List list = new LinkedList();
* List spy = spy(list);
*
* //optionally, you can stub out some methods:
* when(spy.size()).thenReturn(100);
*
* //using the spy calls <b>*real*</b> methods
* spy.add("one");
* spy.add("two");
*
* //prints "one" - the first element of a list
* System.out.println(spy.get(0));
*
* //size() method was stubbed - 100 is printed
* System.out.println(spy.size());
*
* //optionally, you can verify
* verify(spy).add("one");
* verify(spy).add("two");
* </code></pre>
*
* <h4>Important gotcha on spying real objects!</h4>
* <ol>
* <li>Sometimes it's impossible or impractical to use {@link Mockito#when(Object)} for stubbing spies.
* Therefore when using spies please consider <code>doReturn</code>|<code>Answer</code>|<code>Throw()</code> family of
* methods for stubbing. Example:
*
* <pre class="code"><code class="java">
* List list = new LinkedList();
* List spy = spy(list);
*
* //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
* when(spy.get(0)).thenReturn("foo");
*
* //You have to use doReturn() for stubbing
* doReturn("foo").when(spy).get(0);
* </code></pre>
* </li>
*
* <li>Mockito <b>*does not*</b> delegate calls to the passed real instance, instead it actually creates a copy of it.
* So if you keep the real instance and interact with it, don't expect the spied to be aware of those interaction
* and their effect on real instance state.
* The corollary is that when an <b>*unstubbed*</b> method is called <b>*on the spy*</b> but <b>*not on the real instance*</b>,
* you won't see any effects on the real instance.
* </li>
*
* <li>Watch out for final methods.
* Mockito doesn't mock final methods so the bottom line is: when you spy on real objects + you try to stub a final method = trouble.
* Also you won't be able to verify those method as well.
* </li>
* </ol>
*
*
*
*
* <h3 id="14">14. Changing <a class="meaningful_link" href="#defaultreturn" name="defaultreturn">default return values of unstubbed invocations</a> (Since 1.7)</h3>
*
* You can create a mock with specified strategy for its return values.
* It's quite an advanced feature and typically you don't need it to write decent tests.
* However, it can be helpful for working with <b>legacy systems</b>.
* <p>
* It is the default answer so it will be used <b>only when you don't</b> stub the method call.
*
* <pre class="code"><code class="java">
* Foo mock = mock(Foo.class, Mockito.RETURNS_SMART_NULLS);
* Foo mockTwo = mock(Foo.class, new YourOwnAnswer());
* </code></pre>
*
* <p>
* Read more about this interesting implementation of <i>Answer</i>: {@link Mockito#RETURNS_SMART_NULLS}
*
*
*
*
* <h3 id="15">15. <a class="meaningful_link" href="#captors" name="captors">Capturing arguments</a> for further assertions (Since 1.8.0)</h3>
*
* Mockito verifies argument values in natural java style: by using an <code>equals()</code> method.
* This is also the recommended way of matching arguments because it makes tests clean & simple.
* In some situations though, it is helpful to assert on certain arguments after the actual verification.
* For example:
* <pre class="code"><code class="java">
* ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
* verify(mock).doSomething(argument.capture());
* assertEquals("John", argument.getValue().getName());
* </code></pre>
*
* <b>Warning:</b> it is recommended to use ArgumentCaptor with verification <b>but not</b> with stubbing.
* Using ArgumentCaptor with stubbing may decrease test readability because captor is created outside of assert (aka verify or 'then') block.
* Also it may reduce defect localization because if stubbed method was not called then no argument is captured.
* <p>
* In a way ArgumentCaptor is related to custom argument matchers (see javadoc for {@link ArgumentMatcher} class).
* Both techniques can be used for making sure certain arguments where passed to mocks.
* However, ArgumentCaptor may be a better fit if:
* <ul>
* <li>custom argument matcher is not likely to be reused</li>
* <li>you just need it to assert on argument values to complete verification</li>
* </ul>
* Custom argument matchers via {@link ArgumentMatcher} are usually better for stubbing.
*
*
*
*
* <h3 id="16">16. <a class="meaningful_link" href="#partial_mocks" name="partial_mocks">Real partial mocks</a> (Since 1.8.0)</h3>
*
* Finally, after many internal debates & discussions on the mailing list, partial mock support was added to Mockito.
* Previously we considered partial mocks as code smells. However, we found a legitimate use case for partial mocks - more reading:
* <a href="http://monkeyisland.pl/2009/01/13/subclass-and-override-vs-partial-mocking-vs-refactoring">here</a>
* <p>
* <b>Before release 1.8</b> <code>spy()</code> was not producing real partial mocks and it was confusing for some users.
* Read more about spying: <a href="#13">here</a> or in javadoc for {@link Mockito#spy(Object)} method.
* <p>
* <pre class="code"><code class="java">
* //you can create partial mock with spy() method:
* List list = spy(new LinkedList());
*
* //you can enable partial mock capabilities selectively on mocks:
* Foo mock = mock(Foo.class);
* //Be sure the real implementation is 'safe'.
* //If real implementation throws exceptions or depends on specific state of the object then you're in trouble.
* when(mock.someMethod()).thenCallRealMethod();
* </code></pre>
*
* As usual you are going to read <b>the partial mock warning</b>:
* Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
* How does partial mock fit into this paradigm? Well, it just doesn't...
* Partial mock usually means that the complexity has been moved to a different method on the same object.
* In most cases, this is not the way you want to design your application.
* <p>
* However, there are rare cases when partial mocks come handy:
* dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
* However, I wouldn't use partial mocks for new, test-driven & well-designed code.
*
*
*
*
* <h3 id="17">17. <a class="meaningful_link" href="#resetting_mocks" name="resetting_mocks">Resetting mocks</a> (Since 1.8.0)</h3>
*
* Smart Mockito users hardly use this feature because they know it could be a sign of poor tests.
* Normally, you don't need to reset your mocks, just create new mocks for each test method.
* <p>
* Instead of <code>reset()</code> please consider writing simple, small and focused test methods over lengthy, over-specified tests.
* <b>First potential code smell is <code>reset()</code> in the middle of the test method.</b> This probably means you're testing too much.
* Follow the whisper of your test methods: "Please keep us small & focused on single behavior".
* There are several threads about it on mockito mailing list.
* <p>
* The only reason we added <code>reset()</code> method is to
* make it possible to work with container-injected mocks.
* For more information see FAQ (<a href="https://github.com/mockito/mockito/wiki/FAQ">here</a>).
* <p>
* <b>Don't harm yourself.</b> <code>reset()</code> in the middle of the test method is a code smell (you're probably testing too much).
* <pre class="code"><code class="java">
* List mock = mock(List.class);
* when(mock.size()).thenReturn(10);
* mock.add(1);
*
* reset(mock);
* //at this point the mock forgot any interactions & stubbing
* </code></pre>
*
*
*
*
* <h3 id="18">18. <a class="meaningful_link" href="#framework_validation" name="framework_validation">Troubleshooting & validating framework usage</a> (Since 1.8.0)</h3>
*
* First of all, in case of any trouble, I encourage you to read the Mockito FAQ:
* <a href="https://github.com/mockito/mockito/wiki/FAQ">https://github.com/mockito/mockito/wiki/FAQ</a>
* <p>
* In case of questions you may also post to mockito mailing list:
* <a href="http://groups.google.com/group/mockito">http://groups.google.com/group/mockito</a>
* <p>
* Next, you should know that Mockito validates if you use it correctly <b>all the time</b>.
* However, there's a gotcha so please read the javadoc for {@link Mockito#validateMockitoUsage()}
*
*
*
*
* <h3 id="19">19. <a class="meaningful_link" href="#bdd_mockito" name="bdd_mockito">Aliases for behavior driven development</a> (Since 1.8.0)</h3>
*
* Behavior Driven Development style of writing tests uses <b>//given //when //then</b> comments as fundamental parts of your test methods.
* This is exactly how we write our tests and we warmly encourage you to do so!
* <p>
* Start learning about BDD here: <a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development">http://en.wikipedia.org/wiki/Behavior_Driven_Development</a>
* <p>
* The problem is that current stubbing api with canonical role of <b>when</b> word does not integrate nicely with <b>//given //when //then</b> comments.
* It's because stubbing belongs to <b>given</b> component of the test and not to the <b>when</b> component of the test.
* Hence {@link BDDMockito} class introduces an alias so that you stub method calls with {@link BDDMockito#given(Object)} method.
* Now it really nicely integrates with the <b>given</b> component of a BDD style test!
* <p>
* Here is how the test might look like:
* <pre class="code"><code class="java">
* import static org.mockito.BDDMockito.*;
*
* Seller seller = mock(Seller.class);
* Shop shop = new Shop(seller);
*
* public void shouldBuyBread() throws Exception {
* //given
* given(seller.askForBread()).willReturn(new Bread());
*
* //when
* Goods goods = shop.buyBread();
*
* //then
* assertThat(goods, containBread());
* }
* </code></pre>
*
*
*
*
* <h3 id="20">20. <a class="meaningful_link" href="#serializable_mocks" name="serializable_mocks">Serializable mocks</a> (Since 1.8.1)</h3>
*
* Mocks can be made serializable. With this feature you can use a mock in a place that requires dependencies to be serializable.
* <p>
* WARNING: This should be rarely used in unit testing.
* <p>
* The behaviour was implemented for a specific use case of a BDD spec that had an unreliable external dependency. This
* was in a web environment and the objects from the external dependency were being serialized to pass between layers.
* <p>
* To create serializable mock use {@link MockSettings#serializable()}:
* <pre class="code"><code class="java">
* List serializableMock = mock(List.class, withSettings().serializable());
* </code></pre>
* <p>
* The mock can be serialized assuming all the normal <a href='http://java.sun.com/j2se/1.5.0/docs/api/java/io/Serializable.html'>
* serialization requirements</a> are met by the class.
* <p>
* Making a real object spy serializable is a bit more effort as the spy(...) method does not have an overloaded version
* which accepts MockSettings. No worries, you will hardly ever use it.
*
* <pre class="code"><code class="java">
* List<Object> list = new ArrayList<Object>();
* List<Object> spy = mock(ArrayList.class, withSettings()
* .spiedInstance(list)
* .defaultAnswer(CALLS_REAL_METHODS)
* .serializable());
* </code></pre>
*
*
*
*
* <h3 id="21">21. New annotations: <a class="meaningful_link" href="#captor_annotation" name="captor_annotation"><code>@Captor</code></a>,
* <a class="meaningful_link" href="#spy_annotation" name="spy_annotation"><code>@Spy</code></a>,
* <a class="meaningful_link" href="#injectmocks_annotation" name="injectmocks_annotation"><code>@InjectMocks</code></a> (Since 1.8.3)</h3>
*
* <p>
* Release 1.8.3 brings new annotations that may be helpful on occasion:
*
* <ul>
* <li>@{@link Captor} simplifies creation of {@link ArgumentCaptor}
* - useful when the argument to capture is a nasty generic class and you want to avoid compiler warnings
* <li>@{@link Spy} - you can use it instead {@link Mockito#spy(Object)}.
* <li>@{@link InjectMocks} - injects mock or spy fields into tested object automatically.
* </ul>
*
* <p>
* Note that @{@link InjectMocks} can also be used in combination with the @{@link Spy} annotation, it means
* that Mockito will inject mocks into the partial mock under test. This complexity is another good reason why you
* should only use partial mocks as a last resort. See point 16 about partial mocks.
*
* <p>
* All new annotations are <b>*only*</b> processed on {@link MockitoAnnotations#initMocks(Object)}.
* Just like for @{@link Mock} annotation you can use the built-in runner: {@link MockitoJUnitRunner} or rule:
* {@link MockitoRule}.
* <p>
*
*
*
*
* <h3 id="22">22. <a class="meaningful_link" href="#verification_timeout" name="verification_timeout">Verification with timeout</a> (Since 1.8.5)</h3>
* <p>
* Allows verifying with timeout. It causes a verify to wait for a specified period of time for a desired
* interaction rather than fails immediately if had not already happened. May be useful for testing in concurrent
* conditions.
* <p>
* This feature should be used rarely - figure out a better way of testing your multi-threaded system.
* <p>
* Not yet implemented to work with InOrder verification.
* <p>
* Examples:
* <p>
* <pre class="code"><code class="java">
* //passes when someMethod() is called within given time span
* verify(mock, timeout(100)).someMethod();
* //above is an alias to:
* verify(mock, timeout(100).times(1)).someMethod();
*
* //passes when someMethod() is called <b>*exactly*</b> 2 times within given time span
* verify(mock, timeout(100).times(2)).someMethod();
*
* //passes when someMethod() is called <b>*at least*</b> 2 times within given time span
* verify(mock, timeout(100).atLeast(2)).someMethod();
*
* //verifies someMethod() within given time span using given verification mode
* //useful only if you have your own custom verification modes.
* verify(mock, new Timeout(100, yourOwnVerificationMode)).someMethod();
* </code></pre>
*
*
*
*
* <h3 id="23">23. <a class="meaningful_link" href="#automatic_instantiation" name="automatic_instantiation">Automatic instantiation of <code>@Spies</code>,
* <code>@InjectMocks</code></a> and <a class="meaningful_link" href="#constructor_injection" name="constructor_injection">constructor injection goodness</a> (Since 1.9.0)</h3>
*
* <p>
* Mockito will now try to instantiate @{@link Spy} and will instantiate @{@link InjectMocks} fields
* using <b>constructor</b> injection, <b>setter</b> injection, or <b>field</b> injection.
* <p>
* To take advantage of this feature you need to use {@link MockitoAnnotations#initMocks(Object)}, {@link MockitoJUnitRunner}
* or {@link MockitoRule}.
* <p>
* Read more about available tricks and the rules of injection in the javadoc for {@link InjectMocks}
* <pre class="code"><code class="java">
* //instead:
* @Spy BeerDrinker drinker = new BeerDrinker();
* //you can write:
* @Spy BeerDrinker drinker;
*
* //same applies to @InjectMocks annotation:
* @InjectMocks LocalPub;
* </code></pre>
*
*
*
*
* <h3 id="24">24. <a class="meaningful_link" href="#one_liner_stub" name="one_liner_stub">One-liner stubs</a> (Since 1.9.0)</h3>
* <p>
* Mockito will now allow you to create mocks when stubbing.
* Basically, it allows to create a stub in one line of code.
* This can be helpful to keep test code clean.
* For example, some boring stub can be created & stubbed at field initialization in a test:
* <pre class="code"><code class="java">
* public class CarTest {
* Car boringStubbedCar = when(mock(Car.class).shiftGear()).thenThrow(EngineNotStarted.class).getMock();
*
* @Test public void should... {}
* </code></pre>
*
*
*
*
* <h3 id="25">25. <a class="meaningful_link" href="#ignore_stubs_verification" name="ignore_stubs_verification">Verification ignoring stubs</a> (Since 1.9.0)</h3>
* <p>
* Mockito will now allow to ignore stubbing for the sake of verification.
* Sometimes useful when coupled with <code>verifyNoMoreInteractions()</code> or verification <code>inOrder()</code>.
* Helps avoiding redundant verification of stubbed calls - typically we're not interested in verifying stubs.
* <p>
* <b>Warning</b>, <code>ignoreStubs()</code> might lead to overuse of verifyNoMoreInteractions(ignoreStubs(...));
* Bear in mind that Mockito does not recommend bombarding every test with <code>verifyNoMoreInteractions()</code>
* for the reasons outlined in javadoc for {@link Mockito#verifyNoMoreInteractions(Object...)}
* <p>Some examples:
* <pre class="code"><code class="java">
* verify(mock).foo();
* verify(mockTwo).bar();
*
* //ignores all stubbed methods:
* verifyNoMoreInteractions(ignoreStubs(mock, mockTwo));
*
* //creates InOrder that will ignore stubbed
* InOrder inOrder = inOrder(ignoreStubs(mock, mockTwo));
* inOrder.verify(mock).foo();
* inOrder.verify(mockTwo).bar();
* inOrder.verifyNoMoreInteractions();
* </code></pre>
* <p>
* Advanced examples and more details can be found in javadoc for {@link Mockito#ignoreStubs(Object...)}
*
*
*
*
* <h3 id="26">26. <a class="meaningful_link" href="#mocking_details" name="mocking_details">Mocking details</a> (Improved in 2.2.x)</h3>
* <p>
*
* Mockito offers API to inspect the details of a mock object.
* This API is useful for advanced users and mocking framework integrators.
*
* <pre class="code"><code class="java">
* //To identify whether a particular object is a mock or a spy:
* Mockito.mockingDetails(someObject).isMock();
* Mockito.mockingDetails(someObject).isSpy();
*
* //Getting details like type to mock or default answer:
* MockingDetails details = mockingDetails(mock);
* details.getMockCreationSettings().getTypeToMock();
* details.getMockCreationSettings().getDefaultAnswer();
*
* //Getting interactions and stubbings of the mock:
* MockingDetails details = mockingDetails(mock);
* details.getInteractions();
* details.getStubbings();
*
* //Printing all interactions (including stubbing, unused stubs)
* System.out.println(mockingDetails(mock).printInvocations());
* </code></pre>
*
* For more information see javadoc for {@link MockingDetails}.
*
* <h3 id="27">27. <a class="meaningful_link" href="#delegating_call_to_real_instance" name="delegating_call_to_real_instance">Delegate calls to real instance</a> (Since 1.9.5)</h3>
*
* <p>Useful for spies or partial mocks of objects <strong>that are difficult to mock or spy</strong> using the usual spy API.
* Since Mockito 1.10.11, the delegate may or may not be of the same type as the mock.
* If the type is different, a matching method needs to be found on delegate type otherwise an exception is thrown.
*
* Possible use cases for this feature:
* <ul>
* <li>Final classes but with an interface</li>
* <li>Already custom proxied object</li>
* <li>Special objects with a finalize method, i.e. to avoid executing it 2 times</li>
* </ul>
*
* <p>The difference with the regular spy:
* <ul>
* <li>
* The regular spy ({@link #spy(Object)}) contains <strong>all</strong> state from the spied instance
* and the methods are invoked on the spy. The spied instance is only used at mock creation to copy the state from.
* If you call a method on a regular spy and it internally calls other methods on this spy, those calls are remembered
* for verifications, and they can be effectively stubbed.
* </li>
* <li>
* The mock that delegates simply delegates all methods to the delegate.
* The delegate is used all the time as methods are delegated onto it.
* If you call a method on a mock that delegates and it internally calls other methods on this mock,
* those calls are <strong>not</strong> remembered for verifications, stubbing does not have effect on them, too.
* Mock that delegates is less powerful than the regular spy but it is useful when the regular spy cannot be created.
* </li>
* </ul>
*
* <p>
* See more information in docs for {@link AdditionalAnswers#delegatesTo(Object)}.
*
*
*
*
* <h3 id="28">28. <a class="meaningful_link" href="#mock_maker_plugin" name="mock_maker_plugin"><code>MockMaker</code> API</a> (Since 1.9.5)</h3>
* <p>Driven by requirements and patches from Google Android guys Mockito now offers an extension point
* that allows replacing the proxy generation engine. By default, Mockito uses <a href="https://github.com/raphw/byte-buddy">Byte Buddy</a>
* to create dynamic proxies.
* <p>The extension point is for advanced users that want to extend Mockito. For example, it is now possible
* to use Mockito for Android testing with a help of <a href="https://github.com/crittercism/dexmaker">dexmaker</a>.
* <p>For more details, motivations and examples please refer to
* the docs for {@link org.mockito.plugins.MockMaker}.
*
*
*
*
* <h3 id="29">29. <a class="meaningful_link" href="#BDD_behavior_verification" name="BDD_behavior_verification">BDD style verification</a> (Since 1.10.0)</h3>
*
* Enables Behavior Driven Development (BDD) style verification by starting verification with the BDD <b>then</b> keyword.
*
* <pre class="code"><code class="java">
* given(dog.bark()).willReturn(2);
*
* // when
* ...
*
* then(person).should(times(2)).ride(bike);
* </code></pre>
*
* For more information and an example see {@link BDDMockito#then(Object)}}
*
*
*
*
* <h3 id="30">30. <a class="meaningful_link" href="#spying_abstract_classes" name="spying_abstract_classes">Spying or mocking abstract classes (Since 1.10.12, further enhanced in 2.7.13 and 2.7.14)</a></h3>
*
* It is now possible to conveniently spy on abstract classes. Note that overusing spies hints at code design smells (see {@link #spy(Object)}).
* <p>
* Previously, spying was only possible on instances of objects.
* New API makes it possible to use constructor when creating an instance of the mock.
* This is particularly useful for mocking abstract classes because the user is no longer required to provide an instance of the abstract class.
* At the moment, only parameter-less constructor is supported, let us know if it is not enough.
*
* <pre class="code"><code class="java">
* //convenience API, new overloaded spy() method:
* SomeAbstract spy = spy(SomeAbstract.class);
*
* //Mocking abstract methods, spying default methods of an interface (only avilable since 2.7.13)
* Function<Foo, Bar> function = spy(Function.class);
*
* //Robust API, via settings builder:
* OtherAbstract spy = mock(OtherAbstract.class, withSettings()
* .useConstructor().defaultAnswer(CALLS_REAL_METHODS));
*
* //Mocking an abstract class with constructor arguments (only available since 2.7.14)
* SomeAbstract spy = mock(SomeAbstract.class, withSettings()
* .useConstructor("arg1", 123).defaultAnswer(CALLS_REAL_METHODS));
*
* //Mocking a non-static inner abstract class:
* InnerAbstract spy = mock(InnerAbstract.class, withSettings()
* .useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS));
* </code></pre>
*
* For more information please see {@link MockSettings#useConstructor(Object...)}.
*
*
*
*
* <h3 id="31">31. <a class="meaningful_link" href="#serilization_across_classloader" name="serilization_across_classloader">Mockito mocks can be <em>serialized</em> / <em>deserialized</em> across classloaders (Since 1.10.0)</a></h3>
*
* Mockito introduces serialization across classloader.
*
* Like with any other form of serialization, all types in the mock hierarchy have to serializable, inclusing answers.
* As this serialization mode require considerably more work, this is an opt-in setting.
*
* <pre class="code"><code class="java">
* // use regular serialization
* mock(Book.class, withSettings().serializable());
*
* // use serialization across classloaders
* mock(Book.class, withSettings().serializable(ACROSS_CLASSLOADERS));
* </code></pre>
*
* For more details see {@link MockSettings#serializable(SerializableMode)}.
*
*
*
*
* <h3 id="32">32. <a class="meaningful_link" href="#better_generic_support_with_deep_stubs" name="better_generic_support_with_deep_stubs">Better generic support with deep stubs (Since 1.10.0)</a></h3>
*
* Deep stubbing has been improved to find generic information if available in the class.
* That means that classes like this can be used without having to mock the behavior.
*
* <pre class="code"><code class="java">
* class Lines extends List<Line> {
* // ...
* }
*
* lines = mock(Lines.class, RETURNS_DEEP_STUBS);
*
* // Now Mockito understand this is not an Object but a Line
* Line line = lines.iterator().next();
* </code></pre>
*
* Please note that in most scenarios a mock returning a mock is wrong.
*
*
*
*
* <h3 id="33">33. <a class="meaningful_link" href="#mockito_junit_rule" name="mockito_junit_rule">Mockito JUnit rule (Since 1.10.17)</a></h3>
*
* Mockito now offers a JUnit rule. Until now in JUnit there were two ways to initialize fields annotated by Mockito annotations
* such as <code>@{@link Mock}</code>, <code>@{@link Spy}</code>, <code>@{@link InjectMocks}</code>, etc.
*
* <ul>
* <li>Annotating the JUnit test class with a <code>@{@link org.junit.runner.RunWith}({@link MockitoJUnitRunner}.class)</code></li>
* <li>Invoking <code>{@link MockitoAnnotations#initMocks(Object)}</code> in the <code>@{@link org.junit.Before}</code> method</li>
* </ul>
*
* Now you can choose to use a rule :
*
* <pre class="code"><code class="java">
* @RunWith(YetAnotherRunner.class)
* public class TheTest {
* @Rule public MockitoRule mockito = MockitoJUnit.rule();
* // ...
* }
* </code></pre>
*
* For more information see {@link MockitoJUnit#rule()}.
*
*
*
*
* <h3 id="34">34. <a class="meaningful_link" href="#plugin_switch" name="plugin_switch">Switch <em>on</em> or <em>off</em> plugins (Since 1.10.15)</a></h3>
*
* An incubating feature made it's way in mockito that will allow to toggle a mockito-plugin.
*
* More information here {@link org.mockito.plugins.PluginSwitch}.
*
*
* <h3 id="35">35. <a class="meaningful_link" href="#BDD_behavior_verification" name="BDD_behavior_verification">Custom verification failure message</a> (Since 2.1.0)</h3>
* <p>
* Allows specifying a custom message to be printed if verification fails.
* <p>
* Examples:
* <p>
* <pre class="code"><code class="java">
*
* // will print a custom message on verification failure
* verify(mock, description("This will print on failure")).someMethod();
*
* // will work with any verification mode
* verify(mock, times(2).description("someMethod should be called twice")).someMethod();
* </code></pre>
*
* <h3 id="36">36. <a class="meaningful_link" href="#Java_8_Lambda_Matching" name="Java_8_Lambda_Matching">Java 8 Lambda Matcher Support</a> (Since 2.1.0)</h3>
* <p>
* You can use Java 8 lambda expressions with {@link ArgumentMatcher} to reduce the dependency on {@link ArgumentCaptor}.
* If you need to verify that the input to a function call on a mock was correct, then you would normally
* use the {@link ArgumentCaptor} to find the operands used and then do subsequent assertions on them. While
* for complex examples this can be useful, it's also long-winded.<p>
* Writing a lambda to express the match is quite easy. The argument to your function, when used in conjunction
* with argThat, will be passed to the ArgumentMatcher as a strongly typed object, so it is possible
* to do anything with it.
* <p>
* Examples:
* <p>
* <pre class="code"><code class="java">
*
* // verify a list only had strings of a certain length added to it
* // note - this will only compile under Java 8
* verify(list, times(2)).add(argThat(string -> string.length() < 5));
*
* // Java 7 equivalent - not as neat
* verify(list, times(2)).add(argThat(new ArgumentMatcher<String>(){
* public boolean matches(String arg) {
* return arg.length() < 5;
* }
* }));
*
* // more complex Java 8 example - where you can specify complex verification behaviour functionally
* verify(target, times(1)).receiveComplexObject(argThat(obj -> obj.getSubObject().get(0).equals("expected")));
*
* // this can also be used when defining the behaviour of a mock under different inputs
* // in this case if the input list was fewer than 3 items the mock returns null
* when(mock.someMethod(argThat(list -> list.size()<3))).willReturn(null);
* </code></pre>
*
* <h3 id="37">37. <a class="meaningful_link" href="#Java_8_Custom_Answers" name="Java_8_Custom_Answers">Java 8 Custom Answer Support</a> (Since 2.1.0)</h3>
* <p>
* As the {@link Answer} interface has just one method it is already possible to implement it in Java 8 using
* a lambda expression for very simple situations. The more you need to use the parameters of the method call,
* the more you need to typecast the arguments from {@link org.mockito.invocation.InvocationOnMock}.
*
* <p>
* Examples:
* <p>
* <pre class="code"><code class="java">
* // answer by returning 12 every time
* doAnswer(invocation -> 12).when(mock).doSomething();
*
* // answer by using one of the parameters - converting into the right
* // type as your go - in this case, returning the length of the second string parameter
* // as the answer. This gets long-winded quickly, with casting of parameters.
* doAnswer(invocation -> ((String)invocation.getArgument(1)).length())
* .when(mock).doSomething(anyString(), anyString(), anyString());
* </code></pre>
*
* For convenience it is possible to write custom answers/actions, which use the parameters to the method call,
* as Java 8 lambdas. Even in Java 7 and lower these custom answers based on a typed interface can reduce boilerplate.
* In particular, this approach will make it easier to test functions which use callbacks.
*
* The methods {@link AdditionalAnswers#answer(Answer1) answer} and {@link AdditionalAnswers#answerVoid(VoidAnswer1) answerVoid}
* can be used to create the answer. They rely on the related answer interfaces in {@link org.mockito.stubbing} that
* support answers up to 5 parameters.
*
* <p>
* Examples:
* <p>
* <pre class="code"><code class="java">
*
* // Example interface to be mocked has a function like:
* void execute(String operand, Callback callback);
*
* // the example callback has a function and the class under test
* // will depend on the callback being invoked
* void receive(String item);
*
* // Java 8 - style 1
* doAnswer(AdditionalAnswers.<String,Callback>answerVoid((operand, callback) -> callback.receive("dummy"))
* .when(mock).execute(anyString(), any(Callback.class));
*
* // Java 8 - style 2 - assuming static import of AdditionalAnswers
* doAnswer(answerVoid((String operand, Callback callback) -> callback.receive("dummy"))
* .when(mock).execute(anyString(), any(Callback.class));
*
* // Java 8 - style 3 - where mocking function to is a static member of test class
* private static void dummyCallbackImpl(String operation, Callback callback) {
* callback.receive("dummy");
* }
*
* doAnswer(answerVoid(TestClass::dummyCallbackImpl)
* .when(mock).execute(anyString(), any(Callback.class));
*
* // Java 7
* doAnswer(answerVoid(new VoidAnswer2<String, Callback>() {
* public void answer(String operation, Callback callback) {
* callback.receive("dummy");
* }})).when(mock).execute(anyString(), any(Callback.class));
*
* // returning a value is possible with the answer() function
* // and the non-void version of the functional interfaces
* // so if the mock interface had a method like
* boolean isSameString(String input1, String input2);
*
* // this could be mocked
* // Java 8
* doAnswer(AdditionalAnswers.<Boolean,String,String>answer((input1, input2) -> input1.equals(input2))))
* .when(mock).execute(anyString(), anyString());
*
* // Java 7
* doAnswer(answer(new Answer2<String, String, String>() {
* public String answer(String input1, String input2) {
* return input1 + input2;
* }})).when(mock).execute(anyString(), anyString());
* </code></pre>
*
* <h3 id="38">38. <a class="meaningful_link" href="#Meta_Data_And_Generics" name="Meta_Data_And_Generics">Meta data and generic type retention</a> (Since 2.1.0)</h3>
*
* <p>
* Mockito now preserves annotations on mocked methods and types as well as generic meta data. Previously, a mock type did not preserve
* annotations on types unless they were explicitly inherited and never retained annotations on methods. As a consequence, the following
* conditions now hold true:
*
* <pre class="code"><code class="java">
* {@literal @}{@code MyAnnotation
* class Foo {
* List<String> bar() { ... }
* }
*
* Class<?> mockType = mock(Foo.class).getClass();
* assert mockType.isAnnotationPresent(MyAnnotation.class);
* assert mockType.getDeclaredMethod("bar").getGenericReturnType() instanceof ParameterizedType;
* }</code></pre>
*
* <p>
* When using Java 8, Mockito now also preserves type annotations. This is default behavior and might not hold <a href="#28">if an
* alternative {@link org.mockito.plugins.MockMaker} is used</a>.
*
* <h3 id="39">39. <a class="meaningful_link" href="#Mocking_Final" name="Mocking_Final">Mocking final types, enums and final methods</a> (Since 2.1.0)</h3>
*
* Mockito now offers an {@link Incubating}, optional support for mocking final classes and methods.
* This is a fantastic improvement that demonstrates Mockito's everlasting quest for improving testing experience.
* Our ambition is that Mockito "just works" with final classes and methods.
* Previously they were considered <em>unmockable</em>, preventing the user from mocking.
* We already started discussing how to make this feature enabled by default.
* Currently, the feature is still optional as we wait for more feedback from the community.
*
* <p>
* This feature is turned off by default because it is based on completely different mocking mechanism
* that requires more feedback from the community.
*
* <p>
* This alternative mock maker which uses
* a combination of both Java instrumentation API and sub-classing rather than creating a new class to represent
* a mock. This way, it becomes possible to mock final types and methods.
*
* <p>
* This mock maker is <strong>turned off by default</strong> because it is based on completely different mocking mechanism
* that requires more feedback from the community. It can be activated explicitly by the mockito extension mechanism,
* just create in the classpath a file <code>/mockito-extensions/org.mockito.plugins.MockMaker</code>
* containing the value <code>mock-maker-inline</code>.
*
* <p>
* As a convenience, the Mockito team provides an artifact where this mock maker is preconfigured. Instead of using the
* <i>mockito-core</i> artifact, include the <i>mockito-inline</i> artifact in your project. Note that this artifact is
* likely to be discontinued once mocking of final classes and methods gets integrated into the default mock maker.
*
* <p>
* Some noteworthy notes about this mock maker:
* <ul>
* <li>Mocking final types and enums is incompatible with mock settings like :
* <ul>
* <li>explicitly serialization support <code>withSettings().serializable()</code></li>
* <li>extra-interfaces <code>withSettings().extraInterfaces()</code></li>
* </ul>
* </li>
* <li>Some methods cannot be mocked
* <ul>
* <li>Package-visible methods of <code>java.*</code></li>
* <li><code>native</code> methods</li>
* </ul>
* </li>
* <li>This mock maker has been designed around Java Agent runtime attachment ; this require a compatible JVM,
* that is part of the JDK (or Java 9 VM). When running on a non-JDK VM prior to Java 9, it is however possible to
* manually add the <a href="http://bytebuddy.net">Byte Buddy Java agent jar</a> using the <code>-javaagent</code>
* parameter upon starting the JVM.
* </li>
* </ul>
*
* <p>
* If you are interested in more details of this feature please read the javadoc of
* <code>org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker</code>
*
* <h3 id="40">40. <a class="meaningful_link" href="#strict_mockito" name="strict_mockito">
* (**new**) Improved productivity and cleaner tests with "stricter" Mockito</a> (Since 2.+)</h3>
*
* To quickly find out how "stricter" Mockito can make you more productive and get your tests cleaner, see:
* <ul>
* <li>Strict stubbing with JUnit Rules - {@link MockitoRule#strictness(Strictness)} with {@link Strictness#STRICT_STUBS}</li>
* <li>Strict stubbing with JUnit Runner - {@link MockitoJUnitRunner.StrictStubs.class}</li>
* <li>Strict stubbing if you cannot use runner/rule (like TestNG) - {@link MockitoSession}</li>
* <li>Unnecessary stubbing detection with {@link MockitoJUnitRunner}</li>
* <li>Stubbing argument mismatch warnings, documented in {@link MockitoHint}</li>
* </ul>
*
* Mockito is a "loose" mocking framework by default.
* Mocks can be interacted with without setting any expectations beforehand.
* This is intentional and it improves the quality of tests by forcing users to be explicit about what they want to stub / verify.
* It is also very intuitive, easy to use and blends nicely with "given", "when", "then" template of clean test code.
* This is also different from the classic mocking frameworks of the past, they were "strict" by default.
* <p>
* Being "loose" by default makes Mockito tests harder to debug at times.
* There are scenarios where misconfigured stubbing (like using a wrong argument) forces the user to run the test with a debugger.
* Ideally, tests failures are immediately obvious and don't require debugger to identify the root cause.
* Starting with version 2.1 Mockito has been getting new features that nudge the framework towards "strictness".
* We want Mockito to offer fantastic debuggability while not losing its core mocking style, optimized for
* intuitiveness, explicitness and clean test code.
* <p>
* Help Mockito! Try the new features, give us feedback, join the discussion about Mockito strictness at GitHub
* <a href="https://github.com/mockito/mockito/issues/769">issue 769</a>.
*/
@SuppressWarnings("unchecked")
public class Mockito extends ArgumentMatchers {
static final MockitoCore MOCKITO_CORE = new MockitoCore();
/**
* The default <code>Answer</code> of every mock <b>if</b> the mock was not stubbed.
*
* Typically it just returns some empty value.
* <p>
* {@link Answer} can be used to define the return values of unstubbed invocations.
* <p>
* This implementation first tries the global configuration and if there is no global configuration then
* it will use a default answer that returns zeros, empty collections, nulls, etc.
*/
public static final Answer<Object> RETURNS_DEFAULTS = Answers.RETURNS_DEFAULTS;
/**
* Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}.
* <p>
* {@link Answer} can be used to define the return values of unstubbed invocations.
* <p>
* This implementation can be helpful when working with legacy code.
* Unstubbed methods often return null. If your code uses the object returned by an unstubbed call you get a NullPointerException.
* This implementation of Answer <b>returns SmartNull instead of null</b>.
* <code>SmartNull</code> gives nicer exception message than NPE because it points out the line where unstubbed method was called. You just click on the stack trace.
* <p>
* <code>ReturnsSmartNulls</code> first tries to return ordinary values (zeros, empty collections, empty string, etc.)
* then it tries to return SmartNull. If the return type is final then plain <code>null</code> is returned.
* <p>
* <code>ReturnsSmartNulls</code> will be probably the default return values strategy in Mockito 3.0.0
* <p>
* Example:
* <pre class="code"><code class="java">
* Foo mock = mock(Foo.class, RETURNS_SMART_NULLS);
*
* //calling unstubbed method here:
* Stuff stuff = mock.getStuff();
*
* //using object returned by unstubbed call:
* stuff.doSomething();
*
* //Above doesn't yield NullPointerException this time!
* //Instead, SmartNullPointerException is thrown.
* //Exception's cause links to unstubbed <i>mock.getStuff()</i> - just click on the stack trace.
* </code></pre>
*/
public static final Answer<Object> RETURNS_SMART_NULLS = Answers.RETURNS_SMART_NULLS;
/**
* Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}
* <p>
* {@link Answer} can be used to define the return values of unstubbed invocations.
* <p>
* This implementation can be helpful when working with legacy code.
* <p>
* ReturnsMocks first tries to return ordinary values (zeros, empty collections, empty string, etc.)
* then it tries to return mocks. If the return type cannot be mocked (e.g. is final) then plain <code>null</code> is returned.
* <p>
*/
public static final Answer<Object> RETURNS_MOCKS = Answers.RETURNS_MOCKS;
/**
* Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}.
* <p>
* Example that shows how deep stub works:
* <pre class="code"><code class="java">
* Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS);
*
* // note that we're stubbing a chain of methods here: getBar().getName()
* when(mock.getBar().getName()).thenReturn("deep");
*
* // note that we're chaining method calls: getBar().getName()
* assertEquals("deep", mock.getBar().getName());
* </code></pre>
* </p>
*
* <p>
* <strong>WARNING: </strong>
* This feature should rarely be required for regular clean code! Leave it for legacy code.
* Mocking a mock to return a mock, to return a mock, (...), to return something meaningful
* hints at violation of Law of Demeter or mocking a value object (a well known anti-pattern).
* </p>
*
* <p>
* Good quote I've seen one day on the web: <strong>every time a mock returns a mock a fairy dies</strong>.
* </p>
*
* <p>
* Please note that this answer will return existing mocks that matches the stub. This
* behavior is ok with deep stubs and allows verification to work on the last mock of the chain.
* <pre class="code"><code class="java">
* when(mock.getBar(anyString()).getThingy().getName()).thenReturn("deep");
*
* mock.getBar("candy bar").getThingy().getName();
*
* assertSame(mock.getBar(anyString()).getThingy().getName(), mock.getBar(anyString()).getThingy().getName());
* verify(mock.getBar("candy bar").getThingy()).getName();
* verify(mock.getBar(anyString()).getThingy()).getName();
* </code></pre>
* </p>
*
* <p>
* Verification only works with the last mock in the chain. You can use verification modes.
* <pre class="code"><code class="java">
* when(person.getAddress(anyString()).getStreet().getName()).thenReturn("deep");
* when(person.getAddress(anyString()).getStreet(Locale.ITALIAN).getName()).thenReturn("deep");
* when(person.getAddress(anyString()).getStreet(Locale.CHINESE).getName()).thenReturn("deep");
*
* person.getAddress("the docks").getStreet().getName();
* person.getAddress("the docks").getStreet().getLongName();
* person.getAddress("the docks").getStreet(Locale.ITALIAN).getName();
* person.getAddress("the docks").getStreet(Locale.CHINESE).getName();
*
* // note that we are actually referring to the very last mock in the stubbing chain.
* InOrder inOrder = inOrder(
* person.getAddress("the docks").getStreet(),
* person.getAddress("the docks").getStreet(Locale.CHINESE),
* person.getAddress("the docks").getStreet(Locale.ITALIAN)
* );
* inOrder.verify(person.getAddress("the docks").getStreet(), times(1)).getName();
* inOrder.verify(person.getAddress("the docks").getStreet()).getLongName();
* inOrder.verify(person.getAddress("the docks").getStreet(Locale.ITALIAN), atLeast(1)).getName();
* inOrder.verify(person.getAddress("the docks").getStreet(Locale.CHINESE)).getName();
* </code></pre>
* </p>
*
* <p>
* How deep stub work internally?
* <pre class="code"><code class="java">
* //this:
* Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS);
* when(mock.getBar().getName(), "deep");
*
* //is equivalent of
* Foo foo = mock(Foo.class);
* Bar bar = mock(Bar.class);
* when(foo.getBar()).thenReturn(bar);
* when(bar.getName()).thenReturn("deep");
* </code></pre>
* </p>
*
* <p>
* This feature will not work when any return type of methods included in the chain cannot be mocked
* (for example: is a primitive or a final class). This is because of java type system.
* </p>
*/
public static final Answer<Object> RETURNS_DEEP_STUBS = Answers.RETURNS_DEEP_STUBS;
/**
* Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}
* <p>
* {@link Answer} can be used to define the return values of unstubbed invocations.
* <p>
* This implementation can be helpful when working with legacy code.
* When this implementation is used, unstubbed methods will delegate to the real implementation.
* This is a way to create a partial mock object that calls real methods by default.
* <p>
* As usual you are going to read <b>the partial mock warning</b>:
* Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
* How does partial mock fit into this paradigm? Well, it just doesn't...
* Partial mock usually means that the complexity has been moved to a different method on the same object.
* In most cases, this is not the way you want to design your application.
* <p>
* However, there are rare cases when partial mocks come handy:
* dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
* However, I wouldn't use partial mocks for new, test-driven & well-designed code.
* <p>
* Example:
* <pre class="code"><code class="java">
* Foo mock = mock(Foo.class, CALLS_REAL_METHODS);
*
* // this calls the real implementation of Foo.getSomething()
* value = mock.getSomething();
*
* when(mock.getSomething()).thenReturn(fakeValue);
*
* // now fakeValue is returned
* value = mock.getSomething();
* </code></pre>
*/
public static final Answer<Object> CALLS_REAL_METHODS = Answers.CALLS_REAL_METHODS;
/**
* Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}.
*
* Allows Builder mocks to return itself whenever a method is invoked that returns a Type equal
* to the class or a superclass.
*
* <p><b>Keep in mind this answer uses the return type of a method.
* If this type is assignable to the class of the mock, it will return the mock.
* Therefore if you have a method returning a superclass (for example {@code Object}) it will match and return the mock.</b></p>
*
* Consider a HttpBuilder used in a HttpRequesterWithHeaders.
*
* <pre class="code"><code class="java">
* public class HttpRequesterWithHeaders {
*
* private HttpBuilder builder;
*
* public HttpRequesterWithHeaders(HttpBuilder builder) {
* this.builder = builder;
* }
*
* public String request(String uri) {
* return builder.withUrl(uri)
* .withHeader("Content-type: application/json")
* .withHeader("Authorization: Bearer")
* .request();
* }
* }
*
* private static class HttpBuilder {
*
* private String uri;
* private List<String> headers;
*
* public HttpBuilder() {
* this.headers = new ArrayList<String>();
* }
*
* public HttpBuilder withUrl(String uri) {
* this.uri = uri;
* return this;
* }
*
* public HttpBuilder withHeader(String header) {
* this.headers.add(header);
* return this;
* }
*
* public String request() {
* return uri + headers.toString();
* }
* }
* </code></pre>
*
* The following test will succeed
*
* <pre><code>
* @Test
* public void use_full_builder_with_terminating_method() {
* HttpBuilder builder = mock(HttpBuilder.class, RETURNS_SELF);
* HttpRequesterWithHeaders requester = new HttpRequesterWithHeaders(builder);
* String response = "StatusCode: 200";
*
* when(builder.request()).thenReturn(response);
*
* assertThat(requester.request("URI")).isEqualTo(response);
* }
* </code></pre>
*/
public static final Answer<Object> RETURNS_SELF = Answers.RETURNS_SELF;
/**
* Creates mock object of given class or interface.
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param classToMock class or interface to mock
* @return mock object
*/
public static <T> T mock(Class<T> classToMock) {
return mock(classToMock, withSettings());
}
/**
* Specifies mock name. Naming mocks can be helpful for debugging - the name is used in all verification errors.
* <p>
* Beware that naming mocks is not a solution for complex code which uses too many mocks or collaborators.
* <b>If you have too many mocks then refactor the code</b> so that it's easy to test/debug without necessity of naming mocks.
* <p>
* <b>If you use <code>@Mock</code> annotation then you've got naming mocks for free!</b> <code>@Mock</code> uses field name as mock name. {@link Mock Read more.}
* <p>
*
* See examples in javadoc for {@link Mockito} class
*
* @param classToMock class or interface to mock
* @param name of the mock
* @return mock object
*/
public static <T> T mock(Class<T> classToMock, String name) {
return mock(classToMock, withSettings()
.name(name)
.defaultAnswer(RETURNS_DEFAULTS));
}
/**
* Returns a MockingDetails instance that enables inspecting a particular object for Mockito related information.
* Can be used to find out if given object is a Mockito mock
* or to find out if a given mock is a spy or mock.
* <p>
* In future Mockito versions MockingDetails may grow and provide other useful information about the mock,
* e.g. invocations, stubbing info, etc.
*
* @param toInspect - object to inspect. null input is allowed.
* @return A {@link org.mockito.MockingDetails} instance.
* @since 1.9.5
*/
public static MockingDetails mockingDetails(Object toInspect) {
return MOCKITO_CORE.mockingDetails(toInspect);
}
/**
* Creates mock with a specified strategy for its answers to interactions.
* It's quite an advanced feature and typically you don't need it to write decent tests.
* However it can be helpful when working with legacy systems.
* <p>
* It is the default answer so it will be used <b>only when you don't</b> stub the method call.
*
* <pre class="code"><code class="java">
* Foo mock = mock(Foo.class, RETURNS_SMART_NULLS);
* Foo mockTwo = mock(Foo.class, new YourOwnAnswer());
* </code></pre>
*
* <p>See examples in javadoc for {@link Mockito} class</p>
*
* @param classToMock class or interface to mock
* @param defaultAnswer default answer for unstubbed methods
*
* @return mock object
*/
public static <T> T mock(Class<T> classToMock, Answer defaultAnswer) {
return mock(classToMock, withSettings().defaultAnswer(defaultAnswer));
}
/**
* Creates a mock with some non-standard settings.
* <p>
* The number of configuration points for a mock grows
* so we need a fluent way to introduce new configuration without adding more and more overloaded Mockito.mock() methods.
* Hence {@link MockSettings}.
* <pre class="code"><code class="java">
* Listener mock = mock(Listener.class, withSettings()
* .name("firstListner").defaultBehavior(RETURNS_SMART_NULLS));
* );
* </code></pre>
* <b>Use it carefully and occasionally</b>. What might be reason your test needs non-standard mocks?
* Is the code under test so complicated that it requires non-standard mocks?
* Wouldn't you prefer to refactor the code under test so it is testable in a simple way?
* <p>
* See also {@link Mockito#withSettings()}
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param classToMock class or interface to mock
* @param mockSettings additional mock settings
* @return mock object
*/
public static <T> T mock(Class<T> classToMock, MockSettings mockSettings) {
return MOCKITO_CORE.mock(classToMock, mockSettings);
}
/**
* Creates a spy of the real object. The spy calls <b>real</b> methods unless they are stubbed.
* <p>
* Real spies should be used <b>carefully and occasionally</b>, for example when dealing with legacy code.
* <p>
* As usual you are going to read <b>the partial mock warning</b>:
* Object oriented programming tackles complexity by dividing the complexity into separate, specific, SRPy objects.
* How does partial mock fit into this paradigm? Well, it just doesn't...
* Partial mock usually means that the complexity has been moved to a different method on the same object.
* In most cases, this is not the way you want to design your application.
* <p>
* However, there are rare cases when partial mocks come handy:
* dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
* However, I wouldn't use partial mocks for new, test-driven & well-designed code.
* <p>
* Example:
*
* <pre class="code"><code class="java">
* List list = new LinkedList();
* List spy = spy(list);
*
* //optionally, you can stub out some methods:
* when(spy.size()).thenReturn(100);
*
* //using the spy calls <b>real</b> methods
* spy.add("one");
* spy.add("two");
*
* //prints "one" - the first element of a list
* System.out.println(spy.get(0));
*
* //size() method was stubbed - 100 is printed
* System.out.println(spy.size());
*
* //optionally, you can verify
* verify(spy).add("one");
* verify(spy).add("two");
* </code></pre>
*
* <h4>Important gotcha on spying real objects!</h4>
* <ol>
* <li>Sometimes it's impossible or impractical to use {@link Mockito#when(Object)} for stubbing spies.
* Therefore for spies it is recommended to always use <code>doReturn</code>|<code>Answer</code>|<code>Throw()</code>|<code>CallRealMethod</code>
* family of methods for stubbing. Example:
*
* <pre class="code"><code class="java">
* List list = new LinkedList();
* List spy = spy(list);
*
* //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
* when(spy.get(0)).thenReturn("foo");
*
* //You have to use doReturn() for stubbing
* doReturn("foo").when(spy).get(0);
* </code></pre>
* </li>
*
* <li>Mockito <b>*does not*</b> delegate calls to the passed real instance, instead it actually creates a copy of it.
* So if you keep the real instance and interact with it, don't expect the spied to be aware of those interaction
* and their effect on real instance state.
* The corollary is that when an <b>*unstubbed*</b> method is called <b>*on the spy*</b> but <b>*not on the real instance*</b>,
* you won't see any effects on the real instance.</li>
*
* <li>Watch out for final methods.
* Mockito doesn't mock final methods so the bottom line is: when you spy on real objects + you try to stub a final method = trouble.
* Also you won't be able to verify those method as well.
* </li>
* </ol>
* <p>
* See examples in javadoc for {@link Mockito} class
*
* <p>Note that the spy won't have any annotations of the spied type, because CGLIB won't rewrite them.
* It may troublesome for code that rely on the spy to have these annotations.</p>
*
*
* @param object
* to spy on
* @return a spy of the real object
*/
public static <T> T spy(T object) {
return MOCKITO_CORE.mock((Class<T>) object.getClass(), withSettings()
.spiedInstance(object)
.defaultAnswer(CALLS_REAL_METHODS));
}
/**
* Please refer to the documentation of {@link #spy(Object)}.
* Overusing spies hints at code design smells.
* <p>
* This method, in contrast to the original {@link #spy(Object)}, creates a spy based on class instead of an object.
* Sometimes it is more convenient to create spy based on the class and avoid providing an instance of a spied object.
* This is particularly useful for spying on abstract classes because they cannot be instantiated.
* See also {@link MockSettings#useConstructor()}.
* <p>
* Examples:
* <pre class="code"><code class="java">
* SomeAbstract spy = spy(SomeAbstract.class);
*
* //Robust API, via settings builder:
* OtherAbstract spy = mock(OtherAbstract.class, withSettings()
* .useConstructor().defaultAnswer(CALLS_REAL_METHODS));
*
* //Mocking a non-static inner abstract class:
* InnerAbstract spy = mock(InnerAbstract.class, withSettings()
* .useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS));
* </code></pre>
*
* @param classToSpy the class to spy
* @param <T> type of the spy
* @return a spy of the provided class
* @since 1.10.12
*/
@Incubating
public static <T> T spy(Class<T> classToSpy) {
return MOCKITO_CORE.mock(classToSpy, withSettings()
.useConstructor()
.defaultAnswer(CALLS_REAL_METHODS));
}
/**
* Enables stubbing methods. Use it when you want the mock to return particular value when particular method is called.
* <p>
* Simply put: "<b>When</b> the x method is called <b>then</b> return y".
*
* <p>
* Examples:
*
* <pre class="code"><code class="java">
* <b>when</b>(mock.someMethod()).<b>thenReturn</b>(10);
*
* //you can use flexible argument matchers, e.g:
* when(mock.someMethod(<b>anyString()</b>)).thenReturn(10);
*
* //setting exception to be thrown:
* when(mock.someMethod("some arg")).thenThrow(new RuntimeException());
*
* //you can set different behavior for consecutive method calls.
* //Last stubbing (e.g: thenReturn("foo")) determines the behavior of further consecutive calls.
* when(mock.someMethod("some arg"))
* .thenThrow(new RuntimeException())
* .thenReturn("foo");
*
* //Alternative, shorter version for consecutive stubbing:
* when(mock.someMethod("some arg"))
* .thenReturn("one", "two");
* //is the same as:
* when(mock.someMethod("some arg"))
* .thenReturn("one")
* .thenReturn("two");
*
* //shorter version for consecutive method calls throwing exceptions:
* when(mock.someMethod("some arg"))
* .thenThrow(new RuntimeException(), new NullPointerException();
*
* </code></pre>
*
* For stubbing void methods with throwables see: {@link Mockito#doThrow(Throwable...)}
* <p>
* Stubbing can be overridden: for example common stubbing can go to fixture
* setup but the test methods can override it.
* Please note that overridding stubbing is a potential code smell that points out too much stubbing.
* <p>
* Once stubbed, the method will always return stubbed value regardless
* of how many times it is called.
* <p>
* Last stubbing is more important - when you stubbed the same method with
* the same arguments many times.
* <p>
* Although it is possible to verify a stubbed invocation, usually <b>it's just redundant</b>.
* Let's say you've stubbed <code>foo.bar()</code>.
* If your code cares what <code>foo.bar()</code> returns then something else breaks(often before even <code>verify()</code> gets executed).
* If your code doesn't care what <code>get(0)</code> returns then it should not be stubbed.
* Not convinced? See <a href="http://monkeyisland.pl/2008/04/26/asking-and-telling">here</a>.
*
* <p>
* See examples in javadoc for {@link Mockito} class
* @param methodCall method to be stubbed
* @return OngoingStubbing object used to stub fluently.
* <strong>Do not</strong> create a reference to this returned object.
*/
public static <T> OngoingStubbing<T> when(T methodCall) {
return MOCKITO_CORE.when(methodCall);
}
/**
* Verifies certain behavior <b>happened once</b>.
* <p>
* Alias to <code>verify(mock, times(1))</code> E.g:
* <pre class="code"><code class="java">
* verify(mock).someMethod("some arg");
* </code></pre>
* Above is equivalent to:
* <pre class="code"><code class="java">
* verify(mock, times(1)).someMethod("some arg");
* </code></pre>
* <p>
* Arguments passed are compared using <code>equals()</code> method.
* Read about {@link ArgumentCaptor} or {@link ArgumentMatcher} to find out other ways of matching / asserting arguments passed.
* <p>
* Although it is possible to verify a stubbed invocation, usually <b>it's just redundant</b>.
* Let's say you've stubbed <code>foo.bar()</code>.
* If your code cares what <code>foo.bar()</code> returns then something else breaks(often before even <code>verify()</code> gets executed).
* If your code doesn't care what <code>get(0)</code> returns then it should not be stubbed.
* Not convinced? See <a href="http://monkeyisland.pl/2008/04/26/asking-and-telling">here</a>.
*
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param mock to be verified
* @return mock object itself
*/
public static <T> T verify(T mock) {
return MOCKITO_CORE.verify(mock, times(1));
}
/**
* Verifies certain behavior happened at least once / exact number of times / never. E.g:
* <pre class="code"><code class="java">
* verify(mock, times(5)).someMethod("was called five times");
*
* verify(mock, atLeast(2)).someMethod("was called at least two times");
*
* //you can use flexible argument matchers, e.g:
* verify(mock, atLeastOnce()).someMethod(<b>anyString()</b>);
* </code></pre>
*
* <b>times(1) is the default</b> and can be omitted
* <p>
* Arguments passed are compared using <code>equals()</code> method.
* Read about {@link ArgumentCaptor} or {@link ArgumentMatcher} to find out other ways of matching / asserting arguments passed.
* <p>
*
* @param mock to be verified
* @param mode times(x), atLeastOnce() or never()
*
* @return mock object itself
*/
public static <T> T verify(T mock, VerificationMode mode) {
return MOCKITO_CORE.verify(mock, mode);
}
/**
* Smart Mockito users hardly use this feature because they know it could be a sign of poor tests.
* Normally, you don't need to reset your mocks, just create new mocks for each test method.
* <p>
* Instead of <code>#reset()</code> please consider writing simple, small and focused test methods over lengthy, over-specified tests.
* <b>First potential code smell is <code>reset()</code> in the middle of the test method.</b> This probably means you're testing too much.
* Follow the whisper of your test methods: "Please keep us small & focused on single behavior".
* There are several threads about it on mockito mailing list.
* <p>
* The only reason we added <code>reset()</code> method is to
* make it possible to work with container-injected mocks.
* For more information see the FAQ (<a href="https://github.com/mockito/mockito/wiki/FAQ">here</a>).
* <p>
* <b>Don't harm yourself.</b> <code>reset()</code> in the middle of the test method is a code smell (you're probably testing too much).
* <pre class="code"><code class="java">
* List mock = mock(List.class);
* when(mock.size()).thenReturn(10);
* mock.add(1);
*
* reset(mock);
* //at this point the mock forgot any interactions & stubbing
* </code></pre>
*
* @param <T> The Type of the mocks
* @param mocks to be reset
*/
public static <T> void reset(T ... mocks) {
MOCKITO_CORE.reset(mocks);
}
/**
* Use this method in order to only clear invocations, when stubbing is non-trivial. Use-cases can be:
* <ul>
* <li>You are using a dependency injection framework to inject your mocks.</li>
* <li>The mock is used in a stateful scenario. For example a class is Singleton which depends on your mock.</li>
* </ul>
*
* <b>Try to avoid this method at all costs. Only clear invocations if you are unable to efficiently test your program.</b>
* @param <T> The type of the mocks
* @param mocks The mocks to clear the invocations for
*/
public static <T> void clearInvocations(T ... mocks) {
MOCKITO_CORE.clearInvocations(mocks);
}
/**
* Checks if any of given mocks has any unverified interaction.
* <p>
* You can use this method after you verified your mocks - to make sure that nothing
* else was invoked on your mocks.
* <p>
* See also {@link Mockito#never()} - it is more explicit and communicates the intent well.
* <p>
* Stubbed invocations (if called) are also treated as interactions.
* <p>
* A word of <b>warning</b>:
* Some users who did a lot of classic, expect-run-verify mocking tend to use <code>verifyNoMoreInteractions()</code> very often, even in every test method.
* <code>verifyNoMoreInteractions()</code> is not recommended to use in every test method.
* <code>verifyNoMoreInteractions()</code> is a handy assertion from the interaction testing toolkit. Use it only when it's relevant.
* Abusing it leads to overspecified, less maintainable tests. You can find further reading
* <a href="http://monkeyisland.pl/2008/07/12/should-i-worry-about-the-unexpected/">here</a>.
* <p>
* This method will also detect unverified invocations that occurred before the test method,
* for example: in <code>setUp()</code>, <code>@Before</code> method or in constructor.
* Consider writing nice code that makes interactions only in test methods.
*
* <p>
* Example:
*
* <pre class="code"><code class="java">
* //interactions
* mock.doSomething();
* mock.doSomethingUnexpected();
*
* //verification
* verify(mock).doSomething();
*
* //following will fail because 'doSomethingUnexpected()' is unexpected
* verifyNoMoreInteractions(mock);
*
* </code></pre>
*
* See examples in javadoc for {@link Mockito} class
*
* @param mocks to be verified
*/
public static void verifyNoMoreInteractions(Object... mocks) {
MOCKITO_CORE.verifyNoMoreInteractions(mocks);
}
/**
* Verifies that no interactions happened on given mocks.
* <pre class="code"><code class="java">
* verifyZeroInteractions(mockOne, mockTwo);
* </code></pre>
* This method will also detect invocations
* that occurred before the test method, for example: in <code>setUp()</code>, <code>@Before</code> method or in constructor.
* Consider writing nice code that makes interactions only in test methods.
* <p>
* See also {@link Mockito#never()} - it is more explicit and communicates the intent well.
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param mocks to be verified
*/
public static void verifyZeroInteractions(Object... mocks) {
MOCKITO_CORE.verifyNoMoreInteractions(mocks);
}
/**
* Use <code>doThrow()</code> when you want to stub the void method with an exception.
* <p>
* Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler
* does not like void methods inside brackets...
* <p>
* Example:
*
* <pre class="code"><code class="java">
* doThrow(new RuntimeException()).when(mock).someVoidMethod();
* </code></pre>
*
* @param toBeThrown to be thrown when the stubbed method is called
* @return stubber - to select a method for stubbing
*/
public static Stubber doThrow(Throwable... toBeThrown) {
return MOCKITO_CORE.stubber().doThrow(toBeThrown);
}
/**
* Use <code>doThrow()</code> when you want to stub the void method with an exception.
* <p>
* A new exception instance will be created for each method invocation.
* <p>
* Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler
* does not like void methods inside brackets...
* <p>
* Example:
*
* <pre class="code"><code class="java">
* doThrow(RuntimeException.class).when(mock).someVoidMethod();
* </code></pre>
*
* @param toBeThrown to be thrown when the stubbed method is called
* @return stubber - to select a method for stubbing
* @since 2.1.0
*/
public static Stubber doThrow(Class<? extends Throwable> toBeThrown) {
return MOCKITO_CORE.stubber().doThrow(toBeThrown);
}
/**
* Same as {@link #doThrow(Class)} but sets consecutive exception classes to be thrown. Remember to use
* <code>doThrow()</code> when you want to stub the void method to throw several exception of specified class.
* <p>
* A new exception instance will be created for each method invocation.
* <p>
* Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler
* does not like void methods inside brackets...
* <p>
* Example:
*
* <pre class="code"><code class="java">
* doThrow(RuntimeException.class, BigFailure.class).when(mock).someVoidMethod();
* </code></pre>
*
* @param toBeThrown to be thrown when the stubbed method is called
* @param toBeThrownNext next to be thrown when the stubbed method is called
* @return stubber - to select a method for stubbing
* @since 2.1.0
*/
// Additional method helps users of JDK7+ to hide heap pollution / unchecked generics array creation
@SuppressWarnings ({"unchecked", "varargs"})
public static Stubber doThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... toBeThrownNext) {
return MOCKITO_CORE.stubber().doThrow(toBeThrown, toBeThrownNext);
}
/**
* Use <code>doCallRealMethod()</code> when you want to call the real implementation of a method.
* <p>
* As usual you are going to read <b>the partial mock warning</b>:
* Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
* How does partial mock fit into this paradigm? Well, it just doesn't...
* Partial mock usually means that the complexity has been moved to a different method on the same object.
* In most cases, this is not the way you want to design your application.
* <p>
* However, there are rare cases when partial mocks come handy:
* dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
* However, I wouldn't use partial mocks for new, test-driven & well-designed code.
* <p>
* See also javadoc {@link Mockito#spy(Object)} to find out more about partial mocks.
* <b>Mockito.spy() is a recommended way of creating partial mocks.</b>
* The reason is it guarantees real methods are called against correctly constructed object because you're responsible for constructing the object passed to spy() method.
* <p>
* Example:
* <pre class="code"><code class="java">
* Foo mock = mock(Foo.class);
* doCallRealMethod().when(mock).someVoidMethod();
*
* // this will call the real implementation of Foo.someVoidMethod()
* mock.someVoidMethod();
* </code></pre>
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @return stubber - to select a method for stubbing
* @since 1.9.5
*/
public static Stubber doCallRealMethod() {
return MOCKITO_CORE.stubber().doCallRealMethod();
}
/**
* Use <code>doAnswer()</code> when you want to stub a void method with generic {@link Answer}.
* <p>
* Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler does not like void methods inside brackets...
* <p>
* Example:
*
* <pre class="code"><code class="java">
* doAnswer(new Answer() {
* public Object answer(InvocationOnMock invocation) {
* Object[] args = invocation.getArguments();
* Mock mock = invocation.getMock();
* return null;
* }})
* .when(mock).someMethod();
* </code></pre>
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param answer to answer when the stubbed method is called
* @return stubber - to select a method for stubbing
*/
public static Stubber doAnswer(Answer answer) {
return MOCKITO_CORE.stubber().doAnswer(answer);
}
/**
* Use <code>doNothing()</code> for setting void methods to do nothing. <b>Beware that void methods on mocks do nothing by default!</b>
* However, there are rare situations when doNothing() comes handy:
* <p>
* <ol>
* <li>Stubbing consecutive calls on a void method:
* <pre class="code"><code class="java">
* doNothing().
* doThrow(new RuntimeException())
* .when(mock).someVoidMethod();
*
* //does nothing the first time:
* mock.someVoidMethod();
*
* //throws RuntimeException the next time:
* mock.someVoidMethod();
* </code></pre>
* </li>
* <li>When you spy real objects and you want the void method to do nothing:
* <pre class="code"><code class="java">
* List list = new LinkedList();
* List spy = spy(list);
*
* //let's make clear() do nothing
* doNothing().when(spy).clear();
*
* spy.add("one");
*
* //clear() does nothing, so the list still contains "one"
* spy.clear();
* </code></pre>
* </li>
* </ol>
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @return stubber - to select a method for stubbing
*/
public static Stubber doNothing() {
return MOCKITO_CORE.stubber().doNothing();
}
/**
* Use <code>doReturn()</code> in those rare occasions when you cannot use {@link Mockito#when(Object)}.
* <p>
* <b>Beware that {@link Mockito#when(Object)} is always recommended for stubbing because it is argument type-safe
* and more readable</b> (especially when stubbing consecutive calls).
* <p>
* Here are those rare occasions when doReturn() comes handy:
* <p>
*
* <ol>
* <li>When spying real objects and calling real methods on a spy brings side effects
*
* <pre class="code"><code class="java">
* List list = new LinkedList();
* List spy = spy(list);
*
* //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
* when(spy.get(0)).thenReturn("foo");
*
* //You have to use doReturn() for stubbing:
* doReturn("foo").when(spy).get(0);
* </code></pre>
* </li>
*
* <li>Overriding a previous exception-stubbing:
* <pre class="code"><code class="java">
* when(mock.foo()).thenThrow(new RuntimeException());
*
* //Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown.
* when(mock.foo()).thenReturn("bar");
*
* //You have to use doReturn() for stubbing:
* doReturn("bar").when(mock).foo();
* </code></pre>
* </li>
* </ol>
*
* Above scenarios shows a tradeoff of Mockito's elegant syntax. Note that the scenarios are very rare, though.
* Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general
* overridding stubbing is a potential code smell that points out too much stubbing.
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param toBeReturned to be returned when the stubbed method is called
* @return stubber - to select a method for stubbing
*/
public static Stubber doReturn(Object toBeReturned) {
return MOCKITO_CORE.stubber().doReturn(toBeReturned);
}
/**
* Same as {@link #doReturn(Object)} but sets consecutive values to be returned. Remember to use
* <code>doReturn()</code> in those rare occasions when you cannot use {@link Mockito#when(Object)}.
* <p>
* <b>Beware that {@link Mockito#when(Object)} is always recommended for stubbing because it is argument type-safe
* and more readable</b> (especially when stubbing consecutive calls).
* <p>
* Here are those rare occasions when doReturn() comes handy:
* <p>
*
* <ol>
* <li>When spying real objects and calling real methods on a spy brings side effects
*
* <pre class="code"><code class="java">
* List list = new LinkedList();
* List spy = spy(list);
*
* //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
* when(spy.get(0)).thenReturn("foo", "bar", "qix");
*
* //You have to use doReturn() for stubbing:
* doReturn("foo", "bar", "qix").when(spy).get(0);
* </code></pre>
* </li>
*
* <li>Overriding a previous exception-stubbing:
* <pre class="code"><code class="java">
* when(mock.foo()).thenThrow(new RuntimeException());
*
* //Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown.
* when(mock.foo()).thenReturn("bar", "foo", "qix");
*
* //You have to use doReturn() for stubbing:
* doReturn("bar", "foo", "qix").when(mock).foo();
* </code></pre>
* </li>
* </ol>
*
* Above scenarios shows a trade-off of Mockito's elegant syntax. Note that the scenarios are very rare, though.
* Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general
* overridding stubbing is a potential code smell that points out too much stubbing.
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param toBeReturned to be returned when the stubbed method is called
* @param toBeReturnedNext to be returned in consecutive calls when the stubbed method is called
* @return stubber - to select a method for stubbing
* @since 2.1.0
*/
@SuppressWarnings({"unchecked", "varargs"})
public static Stubber doReturn(Object toBeReturned, Object... toBeReturnedNext) {
return MOCKITO_CORE.stubber().doReturn(toBeReturned, toBeReturnedNext);
}
/**
* Creates {@link org.mockito.InOrder} object that allows verifying mocks in order.
*
* <pre class="code"><code class="java">
* InOrder inOrder = inOrder(firstMock, secondMock);
*
* inOrder.verify(firstMock).add("was called first");
* inOrder.verify(secondMock).add("was called second");
* </code></pre>
*
* Verification in order is flexible - <b>you don't have to verify all interactions</b> one-by-one
* but only those that you are interested in testing in order.
* <p>
* Also, you can create InOrder object passing only mocks that are relevant for in-order verification.
* <p>
* <code>InOrder</code> verification is 'greedy', but you will hardly ever notice it.
* If you want to find out more, read
* <a href="https://github.com/mockito/mockito/wiki/Greedy-algorithm-of-verfication-InOrder">this wiki page</a>.
* <p>
* As of Mockito 1.8.4 you can verifyNoMoreInvocations() in order-sensitive way. Read more: {@link InOrder#verifyNoMoreInteractions()}
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param mocks to be verified in order
*
* @return InOrder object to be used to verify in order
*/
public static InOrder inOrder(Object... mocks) {
return MOCKITO_CORE.inOrder(mocks);
}
/**
* Ignores stubbed methods of given mocks for the sake of verification.
* Sometimes useful when coupled with <code>verifyNoMoreInteractions()</code> or verification <code>inOrder()</code>.
* Helps avoiding redundant verification of stubbed calls - typically we're not interested in verifying stubs.
* <p>
* <b>Warning</b>, <code>ignoreStubs()</code> might lead to overuse of <code>verifyNoMoreInteractions(ignoreStubs(...));</code>
* Bear in mind that Mockito does not recommend bombarding every test with <code>verifyNoMoreInteractions()</code>
* for the reasons outlined in javadoc for {@link Mockito#verifyNoMoreInteractions(Object...)}
* Other words: all <b>*stubbed*</b> methods of given mocks are marked <b>*verified*</b> so that they don't get in a way during verifyNoMoreInteractions().
* <p>
* This method <b>changes the input mocks</b>! This method returns input mocks just for convenience.
* <p>
* Ignored stubs will also be ignored for verification inOrder, including {@link org.mockito.InOrder#verifyNoMoreInteractions()}.
* See the second example.
* <p>
* Example:
* <pre class="code"><code class="java">
* //mocking lists for the sake of the example (if you mock List in real you will burn in hell)
* List mock1 = mock(List.class), mock2 = mock(List.class);
*
* //stubbing mocks:
* when(mock1.get(0)).thenReturn(10);
* when(mock2.get(0)).thenReturn(20);
*
* //using mocks by calling stubbed get(0) methods:
* System.out.println(mock1.get(0)); //prints 10
* System.out.println(mock2.get(0)); //prints 20
*
* //using mocks by calling clear() methods:
* mock1.clear();
* mock2.clear();
*
* //verification:
* verify(mock1).clear();
* verify(mock2).clear();
*
* //verifyNoMoreInteractions() fails because get() methods were not accounted for.
* try { verifyNoMoreInteractions(mock1, mock2); } catch (NoInteractionsWanted e);
*
* //However, if we ignore stubbed methods then we can verifyNoMoreInteractions()
* verifyNoMoreInteractions(ignoreStubs(mock1, mock2));
*
* //Remember that ignoreStubs() <b>*changes*</b> the input mocks and returns them for convenience.
* </code></pre>
* Ignoring stubs can be used with <b>verification in order</b>:
* <pre class="code"><code class="java">
* List list = mock(List.class);
* when(mock.get(0)).thenReturn("foo");
*
* list.add(0);
* System.out.println(list.get(0)); //we don't want to verify this
* list.clear();
*
* InOrder inOrder = inOrder(ignoreStubs(list));
* inOrder.verify(list).add(0);
* inOrder.verify(list).clear();
* inOrder.verifyNoMoreInteractions();
* </code></pre>
*
* @since 1.9.0
* @param mocks input mocks that will be changed
* @return the same mocks that were passed in as parameters
*/
public static Object[] ignoreStubs(Object... mocks) {
return MOCKITO_CORE.ignoreStubs(mocks);
}
/**
* Allows verifying exact number of invocations. E.g:
* <pre class="code"><code class="java">
* verify(mock, times(2)).someMethod("some arg");
* </code></pre>
*
* See examples in javadoc for {@link Mockito} class
*
* @param wantedNumberOfInvocations wanted number of invocations
*
* @return verification mode
*/
public static VerificationMode times(int wantedNumberOfInvocations) {
return VerificationModeFactory.times(wantedNumberOfInvocations);
}
/**
* Alias to <code>times(0)</code>, see {@link Mockito#times(int)}
* <p>
* Verifies that interaction did not happen. E.g:
* <pre class="code"><code class="java">
* verify(mock, never()).someMethod();
* </code></pre>
*
* <p>
* If you want to verify there were NO interactions with the mock
* check out {@link Mockito#verifyZeroInteractions(Object...)}
* or {@link Mockito#verifyNoMoreInteractions(Object...)}
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @return verification mode
*/
public static VerificationMode never() {
return times(0);
}
/**
* Allows at-least-once verification. E.g:
* <pre class="code"><code class="java">
* verify(mock, atLeastOnce()).someMethod("some arg");
* </code></pre>
* Alias to <code>atLeast(1)</code>.
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @return verification mode
*/
public static VerificationMode atLeastOnce() {
return VerificationModeFactory.atLeastOnce();
}
/**
* Allows at-least-x verification. E.g:
* <pre class="code"><code class="java">
* verify(mock, atLeast(3)).someMethod("some arg");
* </code></pre>
*
* See examples in javadoc for {@link Mockito} class
*
* @param minNumberOfInvocations minimum number of invocations
*
* @return verification mode
*/
public static VerificationMode atLeast(int minNumberOfInvocations) {
return VerificationModeFactory.atLeast(minNumberOfInvocations);
}
/**
* Allows at-most-x verification. E.g:
* <pre class="code"><code class="java">
* verify(mock, atMost(3)).someMethod("some arg");
* </code></pre>
*
* See examples in javadoc for {@link Mockito} class
*
* @param maxNumberOfInvocations max number of invocations
*
* @return verification mode
*/
public static VerificationMode atMost(int maxNumberOfInvocations) {
return VerificationModeFactory.atMost(maxNumberOfInvocations);
}
/**
* Allows non-greedy verification in order. For example
* <pre class="code"><code class="java">
* inOrder.verify( mock, calls( 2 )).someMethod( "some arg" );
* </code></pre>
* <ul>
* <li>will not fail if the method is called 3 times, unlike times( 2 )</li>
* <li>will not mark the third invocation as verified, unlike atLeast( 2 )</li>
* </ul>
* This verification mode can only be used with in order verification.
* @param wantedNumberOfInvocations number of invocations to verify
* @return verification mode
*/
public static VerificationMode calls( int wantedNumberOfInvocations ){
return VerificationModeFactory.calls( wantedNumberOfInvocations );
}
/**
* Allows checking if given method was the only one invoked. E.g:
* <pre class="code"><code class="java">
* verify(mock, only()).someMethod();
* //above is a shorthand for following 2 lines of code:
* verify(mock).someMethod();
* verifyNoMoreInvocations(mock);
* </code></pre>
*
* <p>
* See also {@link Mockito#verifyNoMoreInteractions(Object...)}
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @return verification mode
*/
public static VerificationMode only() {
return VerificationModeFactory.only();
}
/**
* Allows verifying with timeout. It causes a verify to wait for a specified period of time for a desired
* interaction rather than fails immediately if has not already happened. May be useful for testing in concurrent
* conditions.
* <p>
* This differs from {@link Mockito#after after()} in that after() will wait the full period, unless
* the final test result is known early (e.g. if a never() fails), whereas timeout() will stop early as soon
* as verification passes, producing different behaviour when used with times(2), for example, which can pass
* and then later fail. In that case, timeout would pass as soon as times(2) passes, whereas after would run until
* times(2) failed, and then fail.
* <p>
* This feature should be used rarely - figure out a better way of testing your multi-threaded system.
* <pre class="code"><code class="java">
* //passes when someMethod() is called within given time span
* verify(mock, timeout(100)).someMethod();
* //above is an alias to:
* verify(mock, timeout(100).times(1)).someMethod();
*
* //passes as soon as someMethod() has been called 2 times before the given timeout
* verify(mock, timeout(100).times(2)).someMethod();
*
* //equivalent: this also passes as soon as someMethod() has been called 2 times before the given timeout
* verify(mock, timeout(100).atLeast(2)).someMethod();
*
* //verifies someMethod() within given time span using given verification mode
* //useful only if you have your own custom verification modes.
* verify(mock, new Timeout(100, yourOwnVerificationMode)).someMethod();
* </code></pre>
*
* See examples in javadoc for {@link Mockito} class
*
* @param millis - time span in milliseconds
*
* @return verification mode
*/
public static VerificationWithTimeout timeout(long millis) {
return new Timeout(millis, VerificationModeFactory.times(1));
}
/**
* Allows verifying over a given period. It causes a verify to wait for a specified period of time for a desired
* interaction rather than failing immediately if has not already happened. May be useful for testing in concurrent
* conditions.
* <p>
* This differs from {@link Mockito#timeout timeout()} in that after() will wait the full period, whereas timeout()
* will stop early as soon as verification passes, producing different behaviour when used with times(2), for example,
* which can pass and then later fail. In that case, timeout would pass as soon as times(2) passes, whereas after would
* run the full time, which point it will fail, as times(2) has failed.
* <p>
* This feature should be used rarely - figure out a better way of testing your multi-threaded system.
* <p>
* Not yet implemented to work with InOrder verification.
* <pre class="code"><code class="java">
* //passes after 100ms, if someMethod() has only been called once at that time.
* verify(mock, after(100)).someMethod();
* //above is an alias to:
* verify(mock, after(100).times(1)).someMethod();
*
* //passes if someMethod() is called <b>*exactly*</b> 2 times after the given timespan
* verify(mock, after(100).times(2)).someMethod();
*
* //passes if someMethod() has not been called after the given timespan
* verify(mock, after(100).never()).someMethod();
*
* //verifies someMethod() after a given time span using given verification mode
* //useful only if you have your own custom verification modes.
* verify(mock, new After(100, yourOwnVerificationMode)).someMethod();
* </code></pre>
*
* See examples in javadoc for {@link Mockito} class
*
* @param millis - time span in milliseconds
*
* @return verification mode
*/
public static VerificationAfterDelay after(long millis) {
return new After(millis, VerificationModeFactory.times(1));
}
/**
* First of all, in case of any trouble, I encourage you to read the Mockito FAQ: <a href="https://github.com/mockito/mockito/wiki/FAQ">https://github.com/mockito/mockito/wiki/FAQ</a>
* <p>
* In case of questions you may also post to mockito mailing list: <a href="http://groups.google.com/group/mockito">http://groups.google.com/group/mockito</a>
* <p>
* <code>validateMockitoUsage()</code> <b>explicitly validates</b> the framework state to detect invalid use of Mockito.
* However, this feature is optional <b>because Mockito validates the usage all the time...</b> but there is a gotcha so read on.
* <p>
* Examples of incorrect use:
* <pre class="code"><code class="java">
* //Oops, thenReturn() part is missing:
* when(mock.get());
*
* //Oops, verified method call is inside verify() where it should be on the outside:
* verify(mock.execute());
*
* //Oops, missing method to verify:
* verify(mock);
* </code></pre>
*
* Mockito throws exceptions if you misuse it so that you know if your tests are written correctly.
* The gotcha is that Mockito does the validation <b>next time</b> you use the framework (e.g. next time you verify, stub, call mock etc.).
* But even though the exception might be thrown in the next test,
* the exception <b>message contains a navigable stack trace element</b> with location of the defect.
* Hence you can click and find the place where Mockito was misused.
* <p>
* Sometimes though, you might want to validate the framework usage explicitly.
* For example, one of the users wanted to put <code>validateMockitoUsage()</code> in his <code>@After</code> method
* so that he knows immediately when he misused Mockito.
* Without it, he would have known about it not sooner than <b>next time</b> he used the framework.
* One more benefit of having <code>validateMockitoUsage()</code> in <code>@After</code> is that jUnit runner and rule will always fail in the test method with defect
* whereas ordinary 'next-time' validation might fail the <b>next</b> test method.
* But even though JUnit might report next test as red, don't worry about it
* and just click at navigable stack trace element in the exception message to instantly locate the place where you misused mockito.
* <p>
* <b>Both built-in runner: {@link MockitoJUnitRunner} and rule: {@link MockitoRule}</b> do validateMockitoUsage() after each test method.
* <p>
* Bear in mind that <b>usually you don't have to <code>validateMockitoUsage()</code></b>
* and framework validation triggered on next-time basis should be just enough,
* mainly because of enhanced exception message with clickable location of defect.
* However, I would recommend validateMockitoUsage() if you already have sufficient test infrastructure
* (like your own runner or base class for all tests) because adding a special action to <code>@After</code> has zero cost.
* <p>
* See examples in javadoc for {@link Mockito} class
*/
public static void validateMockitoUsage() {
MOCKITO_CORE.validateMockitoUsage();
}
/**
* Allows mock creation with additional mock settings.
* <p>
* Don't use it too often.
* Consider writing simple tests that use simple mocks.
* Repeat after me: simple tests push simple, KISSy, readable & maintainable code.
* If you cannot write a test in a simple way - refactor the code under test.
* <p>
* Examples of mock settings:
* <pre class="code"><code class="java">
* //Creates mock with different default answer & name
* Foo mock = mock(Foo.class, withSettings()
* .defaultAnswer(RETURNS_SMART_NULLS)
* .name("cool mockie"));
*
* //Creates mock with different default answer, descriptive name and extra interfaces
* Foo mock = mock(Foo.class, withSettings()
* .defaultAnswer(RETURNS_SMART_NULLS)
* .name("cool mockie")
* .extraInterfaces(Bar.class));
* </code></pre>
* {@link MockSettings} has been introduced for two reasons.
* Firstly, to make it easy to add another mock settings when the demand comes.
* Secondly, to enable combining different mock settings without introducing zillions of overloaded mock() methods.
* <p>
* See javadoc for {@link MockSettings} to learn about possible mock settings.
* <p>
*
* @return mock settings instance with defaults.
*/
public static MockSettings withSettings() {
return new MockSettingsImpl().defaultAnswer(RETURNS_DEFAULTS);
}
/**
* Adds a description to be printed if verification fails.
* <pre class="code"><code class="java">
* verify(mock, description("This will print on failure")).someMethod("some arg");
* </code></pre>
* @param description The description to print on failure.
* @return verification mode
* @since 2.1.0
*/
public static VerificationMode description(String description) {
return times(1).description(description);
}
/**
* @deprecated - please use {@link MockingDetails#printInvocations()}.
*/
@Deprecated
static MockitoDebugger debug() {
return new MockitoDebuggerImpl();
}
/**
* For advanced users or framework integrators. See {@link MockitoFramework} class.
*
* @since 2.1.0
*/
@Incubating
public static MockitoFramework framework() {
return new DefaultMockitoFramework();
}
/**
* {@code MockitoSession} is an optional, highly recommended feature
* that helps driving cleaner tests by eliminating boilerplate code and adding extra validation.
* <p>
* For more information, including use cases and sample code, see the javadoc for {@link MockitoSession}.
*
* @since 2.7.0
*/
@Incubating
public static MockitoSessionBuilder mockitoSession() {
return new DefaultMockitoSessionBuilder();
}
}
| Fix broken link in Mockito javadoc
Commit 6a82c0 (included in Mockito 2.7.14) changed
MockSetting#useConstructor's signature to accept an Object...
argument. While this change is backwards compatible (as calls can
continue passing an empty argument list), it broke the javadoc
reference to useConstructor() in Mockito's javadoc.
This patch fixes that broken link.
| src/main/java/org/mockito/Mockito.java | Fix broken link in Mockito javadoc |
|
Java | mit | 4f1792d5c7461ae611e2a4ad18e20a4d35c9c0db | 0 | tedliang/osworkflow,tedliang/osworkflow,tedliang/osworkflow,tedliang/osworkflow | /*
* Copyright (c) 2002-2003 by OpenSymphony
* All rights reserved.
*/
package com.opensymphony.workflow.spi.jdbc;
import com.opensymphony.workflow.StoreException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
/**
* @author Christopher Farnham
* Created on Feb 27, 2004
*/
public class MySQLWorkflowStore extends JDBCWorkflowStore {
//~ Instance fields ////////////////////////////////////////////////////////
protected String entrySequenceIncrement = null;
protected String entrySequenceRetrieve = null;
protected String stepSequenceIncrement = null;
protected String stepSequenceRetrieve = null;
//~ Methods ////////////////////////////////////////////////////////////////
public void init(Map props) throws StoreException {
super.init(props);
stepSequenceIncrement = (String) props.get("step.sequence.increment");
stepSequenceRetrieve = (String) props.get("step.sequence.retrieve");
entrySequenceIncrement = (String) props.get("entry.sequence.increment");
entrySequenceRetrieve = (String) props.get("entry.sequence.retrieve");
}
protected long getNextEntrySequence(Connection c) throws SQLException {
PreparedStatement stmt = null;
ResultSet rset = null;
try {
stmt = c.prepareStatement(entrySequenceIncrement);
stmt.executeUpdate();
rset = stmt.executeQuery(entrySequenceRetrieve);
rset.next();
long id = rset.getLong(1);
return id;
} finally {
cleanup(null, stmt, rset);
}
}
protected long getNextStepSequence(Connection c) throws SQLException {
PreparedStatement stmt = null;
ResultSet rset = null;
try {
stmt = c.prepareStatement(stepSequenceIncrement);
stmt.executeUpdate();
rset = stmt.executeQuery(stepSequenceRetrieve);
rset.next();
long id = rset.getLong(1);
return id;
} finally {
cleanup(null, stmt, rset);
}
}
}
| src/java/com/opensymphony/workflow/spi/jdbc/MySQLWorkflowStore.java | /*
* Copyright (c) 2002-2003 by OpenSymphony
* All rights reserved.
*/
package com.opensymphony.workflow.spi.jdbc;
import com.opensymphony.workflow.StoreException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
/**
* @author Christopher Farnham
* Created on Feb 27, 2004
*/
public class MySQLWorkflowStore extends JDBCWorkflowStore {
//~ Instance fields ////////////////////////////////////////////////////////
private String entrySequenceIncrement = null;
private String entrySequenceRetrieve = null;
private String stepSequenceIncrement = null;
private String stepSequenceRetrieve = null;
//~ Methods ////////////////////////////////////////////////////////////////
public void init(Map props) throws StoreException {
super.init(props);
stepSequenceIncrement = (String) props.get("step.sequence.increment");
stepSequenceRetrieve = (String) props.get("step.sequence.retrieve");
entrySequenceIncrement = (String) props.get("entry.sequence.increment");
entrySequenceRetrieve = (String) props.get("entry.sequence.retrieve");
}
protected long getNextEntrySequence(Connection c) throws SQLException {
PreparedStatement stmt = null;
ResultSet rset = null;
try {
stmt = c.prepareStatement(entrySequenceIncrement);
stmt.executeUpdate();
rset = stmt.executeQuery(entrySequenceRetrieve);
rset.next();
long id = rset.getLong(1);
return id;
} finally {
cleanup(null, stmt, rset);
}
}
protected long getNextStepSequence(Connection c) throws SQLException {
PreparedStatement stmt = null;
ResultSet rset = null;
try {
stmt = c.prepareStatement(stepSequenceIncrement);
stmt.executeUpdate();
rset = stmt.executeQuery(stepSequenceRetrieve);
rset.next();
long id = rset.getLong(1);
return id;
} finally {
cleanup(null, stmt, rset);
}
}
}
| Fix for WF-396
| src/java/com/opensymphony/workflow/spi/jdbc/MySQLWorkflowStore.java | Fix for WF-396 |
|
Java | epl-1.0 | e8872372ead26ae48f05d612216cf1817dd4cb8e | 0 | bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs,bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs,bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | /*******************************************************************************
* Copyright (c) 1998, 2008 Oracle. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
*
* 05/28/2008-1.0M8 Andrei Ilitchev
* - 224964: Provide support for Proxy Authentication through JPA.
* Added updateConnectionPolicy method to support EXCLUSIVE_CONNECTION property.
* Some methods, like setSessionEventListener called from deploy still used predeploy properties,
* that meant it was impossible to set listener through createEMF property in SE case with an agent - fixed that.
* Also if creating / closing the same emSetupImpl many times (24 in my case) "java.lang.OutOfMemoryError: PermGen space" resulted:
* partially fixed partially worked around this - see a big comment in predeploy method.
******************************************************************************/
package org.eclipse.persistence.internal.jpa;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.util.*;
import java.io.FileWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import javax.persistence.spi.PersistenceUnitInfo;
import javax.persistence.spi.ClassTransformer;
import javax.persistence.PersistenceException;
import org.eclipse.persistence.internal.databaseaccess.DatasourcePlatform;
import org.eclipse.persistence.internal.weaving.TransformerFactory;
import org.eclipse.persistence.sessions.JNDIConnector;
import org.eclipse.persistence.logging.AbstractSessionLog;
import org.eclipse.persistence.logging.SessionLog;
import org.eclipse.persistence.internal.security.PrivilegedAccessHelper;
import org.eclipse.persistence.internal.security.PrivilegedClassForName;
import org.eclipse.persistence.internal.sessions.AbstractSession;
import org.eclipse.persistence.internal.sessions.PropertiesHandler;
import org.eclipse.persistence.sequencing.Sequence;
import org.eclipse.persistence.sessions.*;
import org.eclipse.persistence.sessions.server.ConnectionPolicy;
import org.eclipse.persistence.sessions.server.ReadConnectionPool;
import org.eclipse.persistence.sessions.server.ServerSession;
import org.eclipse.persistence.internal.jpa.metadata.MetadataProcessor;
import org.eclipse.persistence.sessions.factories.SessionManager;
import org.eclipse.persistence.sessions.factories.XMLSessionConfigLoader;
import org.eclipse.persistence.config.BatchWriting;
import org.eclipse.persistence.config.DescriptorCustomizer;
import org.eclipse.persistence.config.ExclusiveConnectionMode;
import org.eclipse.persistence.config.LoggerType;
import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.eclipse.persistence.config.ProfilerType;
import org.eclipse.persistence.config.SessionCustomizer;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.platform.server.CustomServerPlatform;
import org.eclipse.persistence.platform.server.ServerPlatform;
import org.eclipse.persistence.exceptions.*;
import org.eclipse.persistence.internal.helper.JPAClassLoaderHolder;
import org.eclipse.persistence.internal.helper.JPAConversionManager;
import javax.persistence.spi.PersistenceUnitTransactionType;
import org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor;
import org.eclipse.persistence.internal.helper.Helper;
import org.eclipse.persistence.internal.security.PrivilegedNewInstanceFromClass;
import org.eclipse.persistence.internal.jpa.jdbc.DataSourceImpl;
import org.eclipse.persistence.internal.security.SecurableObjectHolder;
import org.eclipse.persistence.platform.database.converters.StructConverter;
import org.eclipse.persistence.platform.server.ServerPlatformBase;
import org.eclipse.persistence.tools.profiler.PerformanceProfiler;
import org.eclipse.persistence.tools.profiler.QueryMonitor;
import static org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider.*;
/**
* INTERNAL:
* An EclipseLink specific implementer of the EntityManagerInitializer interface.
* This class handles deployment of a persistence unit.
* In predeploy the meta-data is processed and weaver transformer is returned to allow weaving of the persistent classes.
* In deploy the project and session are initialize and registered.
*/
public class EntityManagerSetupImpl {
/*
* Design Pattern in use: Builder pattern
* EntityManagerSetupImpl, MetadataProcessor and MetadataProject
* play the role of director, builder and product respectively.
* See processORMetadata which is the factory method.
*
*/
protected MetadataProcessor processor = null;
protected PersistenceUnitInfo persistenceUnitInfo = null;
protected Map predeployProperties = null;
// count a number of open factories that use this object.
protected int factoryCount = 0;
protected ServerSession session = null;
// true if predeploy called by createContainerEntityManagerFactory; false - createEntityManagerFactory
protected boolean isInContainerMode = false;
protected boolean isSessionLoadedFromSessionsXML=false;
// indicates whether weaving was used on the first run through predeploy (in STATE_INITIAL)
protected Boolean enableWeaving = null;
// indicates that classes have already been woven
protected boolean isWeavingStatic = false;
protected SecurableObjectHolder securableObjectHolder = new SecurableObjectHolder();
// factoryCount==0; session==null
public static final String STATE_INITIAL = "Initial";
// session != null
public static final String STATE_PREDEPLOYED = "Predeployed";
// factoryCount>0; session != null; session stored in SessionManager
public static final String STATE_DEPLOYED = "Deployed";
// factoryCount==0; session==null
public static final String STATE_PREDEPLOY_FAILED="PredeployFailed";
// factoryCount>0; session != null
public static final String STATE_DEPLOY_FAILED = "DeployFailed";
// factoryCount==0; session==null
public static final String STATE_UNDEPLOYED = "Undeployed";
protected String state = STATE_INITIAL;
/**
* Initial -----> PredeployFailed
* | |
* V V
* |-> Predeployed --> DeployFailed
* | | | |
* | V V V
* | Deployed -> Undeployed-->|
* | |
* |<-------------------------V
*/
public static final String ERROR_LOADING_XML_FILE = "error_loading_xml_file";
public static final String EXCEPTION_LOADING_ENTITY_CLASS = "exception_loading_entity_class";
/**
* This method can be used to ensure the session represented by emSetupImpl
* is removed from the SessionManager.
*/
protected void removeSessionFromGlobalSessionManager() {
if (session != null){
if(session.isConnected()) {
session.logout();
}
SessionManager.getManager().getSessions().remove(session.getName());
}
}
/**
* Deploy a persistence session and return an EntityManagerFactory.
*
* Deployment takes a session that was partially created in the predeploy call and makes it whole.
*
* This means doing any configuration that requires the real class definitions for the entities. In
* the predeploy phase we were in a stage where we were not let allowed to load the real classes.
*
* Deploy could be called several times - but only the first call does the actual deploying -
* additional calls allow to update session properties (in case the session is not connected).
*
* Note that there is no need to synchronize deploy method - it doesn't alter factoryCount
* and while deploy is executed no other method can alter the current state
* (predeploy call would just increment factoryCount; undeploy call would not drop factoryCount to 0).
* However precautions should be taken to handle concurrent calls to deploy, because those may
* alter the current state or connect the session.
*
* @param realClassLoader The class loader that was used to load the entity classes. This loader
* will be maintained for the lifespan of the loaded classes.
* @param additionalProperties added to predeployProperties for updateServerSession overriding existing properties.
* In JSE case it allows to alter properties in main (as opposed to preMain where preDeploy is called).
* @return An EntityManagerFactory to be used by the Container to obtain EntityManagers
*/
public ServerSession deploy(ClassLoader realClassLoader, Map additionalProperties) {
if (state != STATE_PREDEPLOYED && state != STATE_DEPLOYED) {
throw new PersistenceException(EntityManagerSetupException.cannotDeployWithoutPredeploy(persistenceUnitInfo.getPersistenceUnitName(), state));
}
// state is PREDEPLOYED or DEPLOYED
session.log(SessionLog.FINEST, SessionLog.PROPERTIES, "deploy_begin", new Object[]{getPersistenceUnitInfo().getPersistenceUnitName(), state, factoryCount});
List<StructConverter> structConverters = null;
try {
Map deployProperties = mergeMaps(additionalProperties, predeployProperties);
translateOldProperties(deployProperties, session);
if (state == STATE_PREDEPLOYED) {
synchronized (session) {
if (state == STATE_PREDEPLOYED) {
try {
// The project is initially created using class names rather than classes. This call will make the conversion.
// If the session was loaded from sessions.xml this will also converter the descriptor classes to the correct class loader.
session.getProject().convertClassNamesToClasses(realClassLoader);
if (!isSessionLoadedFromSessionsXML) {
// listeners and queries require the real classes and are therefore built during deploy using the realClassLoader
processor.setClassLoader(realClassLoader);
processor.addEntityListeners();
processor.addNamedQueries();
// Process the customizers last.
processor.processCustomizers();
structConverters = processor.getStructConverters();
processor = null;
}
initServerSession(deployProperties);
if (session.getIntegrityChecker().hasErrors()){
session.handleException(new IntegrityException(session.getIntegrityChecker()));
}
session.getDatasourcePlatform().getConversionManager().setLoader(realClassLoader);
state = STATE_DEPLOYED;
} catch (RuntimeException ex) {
state = STATE_DEPLOY_FAILED;
// session not discarded here only because it will be used in undeploy method for debug logging.
throw new PersistenceException(EntityManagerSetupException.deployFailed(persistenceUnitInfo.getPersistenceUnitName(), ex));
}
}
}
}
// state is DEPLOYED
if (!session.isConnected()) {
synchronized (session) {
if(!session.isConnected()) {
session.setProperties(deployProperties);
updateServerSession(deployProperties, realClassLoader);
if (isValidationOnly(deployProperties, false)) {
session.initializeDescriptors();
} else {
if (isSessionLoadedFromSessionsXML) {
if (!session.isConnected()) {
session.login();
}
} else {
login(session, deployProperties);
}
if (!isSessionLoadedFromSessionsXML) {
addStructConverters(session, structConverters);
}
generateDDL(session, deployProperties);
}
}
}
}
return session;
} catch (Exception exception) {
PersistenceException persistenceException = null;
if (exception instanceof PersistenceException) {
persistenceException = (PersistenceException)exception;
persistenceException = new PersistenceException(exception);
} else {
persistenceException = new PersistenceException(exception);
}
session.logThrowable(SessionLog.SEVERE, SessionLog.EJB, exception);
throw persistenceException;
} finally {
session.log(SessionLog.FINEST, SessionLog.PROPERTIES, "deploy_end", new Object[]{getPersistenceUnitInfo().getPersistenceUnitName(), state, factoryCount});
}
}
/**
* Adds descriptors plus sequencing info found on the project to the session.
*/
protected void addProjectToSession(ServerSession session, Project project) {
DatasourcePlatform sessionPlatform = (DatasourcePlatform)session.getDatasourceLogin().getDatasourcePlatform();
DatasourcePlatform projectPlatform = (DatasourcePlatform)project.getDatasourceLogin().getDatasourcePlatform();
if (!sessionPlatform.hasDefaultSequence() && projectPlatform.hasDefaultSequence()) {
sessionPlatform.setDefaultSequence(projectPlatform.getDefaultSequence());
}
if ((sessionPlatform.getSequences() == null) || sessionPlatform.getSequences().isEmpty()) {
if ((projectPlatform.getSequences() != null) && !projectPlatform.getSequences().isEmpty()) {
sessionPlatform.setSequences(projectPlatform.getSequences());
}
} else {
if ((projectPlatform.getSequences() != null) && !projectPlatform.getSequences().isEmpty()) {
Iterator itProjectSequences = projectPlatform.getSequences().values().iterator();
while (itProjectSequences.hasNext()) {
Sequence sequence = (Sequence)itProjectSequences.next();
if (!sessionPlatform.getSequences().containsKey(sequence.getName())) {
sessionPlatform.addSequence(sequence);
}
}
}
}
session.addDescriptors(project);
}
/**
* Put the given session into the session manager so it can be looked up later
*/
protected void addSessionToGlobalSessionManager() {
AbstractSession oldSession = (AbstractSession)SessionManager.getManager().getSessions().get(session.getName());
if(oldSession != null) {
throw new PersistenceException(EntityManagerSetupException.attemptedRedeployWithoutClose(session.getName()));
}
SessionManager.getManager().addSession(session);
}
/**
* Add the StructConverters that were specified by annotation on the DatabasePlatform
* This method must be called after the DatabasePlatform has been detected
* @param session
* @param structConverters
*/
public void addStructConverters(Session session, List<StructConverter> structConverters){
for (StructConverter structConverter : structConverters){
if (session.getPlatform().getTypeConverters().get(structConverter.getJavaType()) != null){
throw ValidationException.twoStructConvertersAddedForSameClass(structConverter.getJavaType().getName());
}
session.getPlatform().addStructConverter(structConverter);
}
}
/**
* Assign a CMP3Policy to each descriptor
*/
protected void assignCMP3Policy() {
// all descriptors assigned CMP3Policy
Project project = session.getProject();
for (Iterator iterator = project.getDescriptors().values().iterator(); iterator.hasNext();){
//bug:4406101 changed class cast to base class, which is used in projects generated from 904 xml
ClassDescriptor descriptor = (ClassDescriptor)iterator.next();
if(descriptor.getCMPPolicy() == null) {
descriptor.setCMPPolicy(new CMP3Policy());
}
}
}
/**
* Updates the EclipseLink ServerPlatform class for use with this platform.
* @return true if the ServerPlatform has changed.
*/
protected boolean updateServerPlatform(Map m, ClassLoader loader) {
String serverPlatformClassName = PropertiesHandler.getPropertyValueLogDebug(PersistenceUnitProperties.TARGET_SERVER, m, session);
if(serverPlatformClassName == null) {
// property is not specified - nothing to do.
return false;
}
// originalServerPlatform is always non-null - Session's constructor sets serverPlatform to NoServerPlatform
ServerPlatform originalServerPlatform = session.getServerPlatform();
String originalServerPlatformClassName = originalServerPlatform.getClass().getName();
if(originalServerPlatformClassName.equals(serverPlatformClassName)) {
// nothing to do - use the same value as before
return false;
}
// the new serverPlatform
ServerPlatform serverPlatform = null;
// New platform - create the new instance and set it.
Class cls = findClassForProperty(serverPlatformClassName, PersistenceUnitProperties.TARGET_SERVER, loader);
try {
Constructor constructor = cls.getConstructor(new Class[]{org.eclipse.persistence.sessions.DatabaseSession.class});
serverPlatform = (ServerPlatform)constructor.newInstance(new Object[]{session});
} catch (Exception ex) {
if(ExternalTransactionController.class.isAssignableFrom(cls)) {
// the new serverPlatform is CustomServerPlatform, cls is its ExternalTransactionController class
if(originalServerPlatform.getClass().equals(CustomServerPlatform.class)) {
// both originalServerPlatform and the new serverPlatform are Custom,
// just set externalTransactionController class (if necessary) into
// originalServerPlatform
CustomServerPlatform originalCustomServerPlatform = (CustomServerPlatform)originalServerPlatform;
if(cls.equals(originalCustomServerPlatform.getExternalTransactionControllerClass())) {
// externalTransactionController classes are the same - nothing to do
} else {
originalCustomServerPlatform.setExternalTransactionControllerClass(cls);
}
} else {
// originalServerPlatform is not custom - need a new one.
CustomServerPlatform customServerPlatform = new CustomServerPlatform(session);
customServerPlatform.setExternalTransactionControllerClass(cls);
serverPlatform = customServerPlatform;
}
} else {
throw EntityManagerSetupException.failedToInstantiateServerPlatform(serverPlatformClassName, PersistenceUnitProperties.TARGET_SERVER, ex);
}
}
if (serverPlatform != null){
session.setServerPlatform(serverPlatform);
return true;
}
return false;
}
/**
* Update loggers and settings for the singleton logger and the session logger.
* @param persistenceProperties the properties map
* @param serverPlatformChanged the boolean that denotes a serverPlatform change in the session.
* @param sessionNameChanged the boolean that denotes a sessionNameChanged change in the session.
*/
protected void updateLoggers(Map persistenceProperties, boolean serverPlatformChanged, boolean sessionNameChanged, ClassLoader loader) {
// Logger(SessionLog type) can be specified by the logger property or ServerPlatform.getServerLog().
// The logger property has a higher priority to ServerPlatform.getServerLog().
String loggerClassName = PropertiesHandler.getPropertyValueLogDebug(PersistenceUnitProperties.LOGGING_LOGGER, persistenceProperties, session);
// The sessionLog instance should be different from the singletonLog because they have
// different state.
SessionLog singletonLog = null, sessionLog = null;
if (loggerClassName != null) {
SessionLog currentLog = session.getSessionLog();
if(loggerClassName.equals(LoggerType.ServerLogger)){
ServerPlatform serverPlatform = session.getServerPlatform();
singletonLog = serverPlatform.getServerLog();
sessionLog = serverPlatform.getServerLog();
} else if (!currentLog.getClass().getName().equals(loggerClassName)) {
// Logger class was specified and it's not what's already there.
Class sessionLogClass = findClassForProperty(loggerClassName, PersistenceUnitProperties.LOGGING_LOGGER, loader);
try {
singletonLog = (SessionLog)sessionLogClass.newInstance();
sessionLog = (SessionLog)sessionLogClass.newInstance();
} catch (Exception ex) {
throw EntityManagerSetupException.failedToInstantiateLogger(loggerClassName, PersistenceUnitProperties.LOGGING_LOGGER, ex);
}
}
} else if (serverPlatformChanged) {
ServerPlatform serverPlatform = session.getServerPlatform();
singletonLog = serverPlatform.getServerLog();
sessionLog = serverPlatform.getServerLog();
}
// Don't change default loggers if the new loggers have not been created.
if (singletonLog != null && sessionLog != null) {
AbstractSessionLog.setLog(singletonLog);
session.setSessionLog(sessionLog);
} else if (sessionNameChanged) {
// In JavaLog this will result in logger name changes,
// but won't affect DefaultSessionLog.
// Note, that the session hasn't change, only its name.
session.getSessionLog().setSession(session);
}
// Bug5389828. Update the logging settings for the singleton logger.
initOrUpdateLogging(persistenceProperties, AbstractSessionLog.getLog());
initOrUpdateLogging(persistenceProperties, session.getSessionLog());
// Set logging file.
String loggingFileString = (String)persistenceProperties.get(PersistenceUnitProperties.LOGGING_FILE);
if (loggingFileString != null) {
if (!loggingFileString.trim().equals("")) {
try {
if (sessionLog!=null){
if (sessionLog instanceof AbstractSessionLog) {
FileOutputStream fos = new FileOutputStream(loggingFileString);
((AbstractSessionLog)sessionLog).setWriter(fos);
} else {
FileWriter fw = new FileWriter(loggingFileString);
sessionLog.setWriter(fw);
}
}
} catch (IOException e) {
session.handleException(ValidationException.invalidLoggingFile(loggingFileString,e));
}
} else {
session.handleException(ValidationException.invalidLoggingFile());
}
}
}
/**
* Check for the PROFILER persistence or system property and set the Session's profiler.
* This can also set the QueryMonitor.
*/
protected void updateProfiler(Map persistenceProperties,ClassLoader loader) {
// This must use config property as the profiler is not in the PropertiesHandler and requires
// supporting generic profiler classes.
String newProfilerClassName = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.PROFILER, persistenceProperties, session);
if (newProfilerClassName == null) {
((ServerPlatformBase)session.getServerPlatform()).configureProfiler(session);
} else {
if (newProfilerClassName.equals(ProfilerType.NoProfiler)) {
session.setProfiler(null);
return;
}
if (newProfilerClassName.equals(ProfilerType.QueryMonitor)) {
session.setProfiler(null);
QueryMonitor.shouldMonitor=true;
return;
}
if (newProfilerClassName.equals(ProfilerType.PerformanceProfiler)) {
session.setProfiler(new PerformanceProfiler());
return;
}
String originalProfilerClassNamer = null;
if (session.getProfiler() != null) {
originalProfilerClassNamer = session.getProfiler().getClass().getName();
if (originalProfilerClassNamer.equals(newProfilerClassName)) {
return;
}
}
// New profiler - create the new instance and set it.
try {
Class newProfilerClass = findClassForProperty(newProfilerClassName, PersistenceUnitProperties.PROFILER, loader);
SessionProfiler sessionProfiler = (SessionProfiler)buildObjectForClass(newProfilerClass, SessionProfiler.class);
if (sessionProfiler != null) {
session.setProfiler(sessionProfiler);
} else {
session.handleException(ValidationException.invalidProfilerClass(newProfilerClassName));
}
} catch (IllegalAccessException e) {
session.handleException(ValidationException.cannotInstantiateProfilerClass(newProfilerClassName,e));
} catch (PrivilegedActionException e) {
session.handleException(ValidationException.cannotInstantiateProfilerClass(newProfilerClassName,e));
} catch (InstantiationException e) {
session.handleException(ValidationException.cannotInstantiateProfilerClass(newProfilerClassName,e));
}
}
}
protected static Class findClass(String className, ClassLoader loader) throws ClassNotFoundException, PrivilegedActionException {
if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()){
return (Class)AccessController.doPrivileged(new PrivilegedClassForName(className, true, loader));
} else {
return org.eclipse.persistence.internal.security.PrivilegedAccessHelper.getClassForName(className, true, loader);
}
}
protected static Class findClassForProperty(String className, String propertyName, ClassLoader loader) {
try {
return findClass(className, loader);
} catch (PrivilegedActionException exception1) {
throw EntityManagerSetupException.classNotFoundForProperty(className, propertyName, exception1.getException());
} catch (ClassNotFoundException exception2) {
throw EntityManagerSetupException.classNotFoundForProperty(className, propertyName, exception2);
}
}
/**
* This method will be used to validate the specified class and return it's instance.
*/
protected static Object buildObjectForClass(Class clazz, Class mustBeImplementedInterface) throws IllegalAccessException, PrivilegedActionException,InstantiationException {
if(clazz!=null && Helper.classImplementsInterface(clazz,mustBeImplementedInterface)){
if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()){
return AccessController.doPrivileged(new PrivilegedNewInstanceFromClass(clazz));
} else {
return PrivilegedAccessHelper.newInstanceFromClass(clazz);
}
} else {
return null;
}
}
protected void updateDescriptorCacheSettings(Map m, ClassLoader loader) {
Map typeMap = PropertiesHandler.getPrefixValuesLogDebug(PersistenceUnitProperties.CACHE_TYPE_, m, session);
Map sizeMap = PropertiesHandler.getPrefixValuesLogDebug(PersistenceUnitProperties.CACHE_SIZE_, m, session);
Map sharedMap = PropertiesHandler.getPrefixValuesLogDebug(PersistenceUnitProperties.CACHE_SHARED_, m, session);
if(typeMap.isEmpty() && sizeMap.isEmpty() && sharedMap.isEmpty()) {
return;
}
boolean hasDefault = false;
String defaultTypeName = (String)typeMap.remove(PersistenceUnitProperties.DEFAULT);
Class defaultType = null;
if(defaultTypeName != null) {
defaultType = findClassForProperty(defaultTypeName, PersistenceUnitProperties.CACHE_TYPE_DEFAULT, loader);
hasDefault = true;
}
String defaultSizeString = (String)sizeMap.remove(PersistenceUnitProperties.DEFAULT);
Integer defaultSize = null;
if(defaultSizeString != null) {
defaultSize = Integer.parseInt(defaultSizeString);
hasDefault = true;
}
String defaultSharedString = (String)sharedMap.remove(PersistenceUnitProperties.DEFAULT);
Boolean defaultShared = null;
if(defaultSharedString != null) {
defaultShared = Boolean.parseBoolean(defaultSharedString);
hasDefault = true;
}
Iterator it = session.getDescriptors().values().iterator();
while (it.hasNext() && (hasDefault || !typeMap.isEmpty() || !sizeMap.isEmpty() || !sharedMap.isEmpty())) {
ClassDescriptor descriptor = (ClassDescriptor)it.next();
if(descriptor.isAggregateDescriptor() || descriptor.isAggregateCollectionDescriptor()) {
continue;
}
String entityName = descriptor.getAlias();
String className = descriptor.getJavaClass().getName();
String name;
Class type = defaultType;
name = entityName;
String typeName = (String)typeMap.remove(name);
if(typeName == null) {
name = className;
typeName = (String)typeMap.remove(name);
}
if(typeName != null) {
type = findClassForProperty(typeName, PersistenceUnitProperties.CACHE_TYPE_ + name, loader);
}
if(type != null) {
descriptor.setIdentityMapClass(type);
}
Integer size = defaultSize;
name = entityName;
String sizeString = (String)sizeMap.remove(name);
if(sizeString == null) {
name = className;
sizeString = (String)sizeMap.remove(name);
}
if(sizeString != null) {
size = Integer.parseInt(sizeString);
}
if(size != null) {
descriptor.setIdentityMapSize(size.intValue());
}
Boolean shared = defaultShared;
name = entityName;
String sharedString = (String)sharedMap.remove(name);
if(sharedString == null) {
name = className;
sharedString = (String)sharedMap.remove(name);
}
if(sharedString != null) {
shared = Boolean.parseBoolean(sharedString);
}
if(shared != null) {
descriptor.setIsIsolated(!shared.booleanValue());
}
}
}
protected void updateConnectionPolicy(Map m) {
String isLazyString = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.EXCLUSIVE_CONNECTION_IS_LAZY, m, session);
if(isLazyString != null) {
session.getDefaultConnectionPolicy().setIsLazy(Boolean.parseBoolean(isLazyString));
}
ConnectionPolicy.ExclusiveMode exclusiveMode = getConnectionPolicyExclusiveModeFromProperties(m, session, true);
if(exclusiveMode != null) {
session.getDefaultConnectionPolicy().setExclusiveMode(exclusiveMode);
}
}
public static ConnectionPolicy.ExclusiveMode getConnectionPolicyExclusiveModeFromProperties(Map m, AbstractSession abstractSession, boolean useSystemAsDefault) {
String exclusiveConnectionModeString = PropertiesHandler.getPropertyValueLogDebug(PersistenceUnitProperties.EXCLUSIVE_CONNECTION_MODE, m, abstractSession, useSystemAsDefault);
if(exclusiveConnectionModeString != null) {
if(exclusiveConnectionModeString == ExclusiveConnectionMode.Isolated) {
return ConnectionPolicy.ExclusiveMode.Isolated;
} else if(exclusiveConnectionModeString == ExclusiveConnectionMode.Always) {
return ConnectionPolicy.ExclusiveMode.Always;
} else {
return ConnectionPolicy.ExclusiveMode.Transactional;
}
} else {
return null;
}
}
/**
* Perform any steps necessary prior to actual deployment. This includes any steps in the session
* creation that do not require the real loaded domain classes.
*
* The first call to this method caches persistenceUnitInfo which is reused in the following calls.
*
* Note that in JSE case factoryCount is NOT incremented on the very first call
* (by JavaSECMPInitializer.callPredeploy, typically in preMain).
* That provides 1 to 1 correspondence between factoryCount and the number of open factories.
*
* In case factoryCount > 0 the method just increments factoryCount.
* factory == 0 triggers creation of a new session.
*
* This method and undeploy - the only methods altering factoryCount - should be synchronized.
*
* @return A transformer (which may be null) that should be plugged into the proper
* classloader to allow classes to be transformed as they get loaded.
* @see #deploy(ClassLoader, Map)
*/
public synchronized ClassTransformer predeploy(PersistenceUnitInfo info, Map extendedProperties) {
ClassLoader privateClassLoader = null;
if (state == STATE_DEPLOY_FAILED) {
throw new PersistenceException(EntityManagerSetupException.cannotPredeploy(persistenceUnitInfo.getPersistenceUnitName(), state));
}
if (state == STATE_PREDEPLOYED || state == STATE_DEPLOYED) {
session.log(SessionLog.FINEST, SessionLog.PROPERTIES, "predeploy_begin", new Object[]{getPersistenceUnitInfo().getPersistenceUnitName(), state, factoryCount});
factoryCount++;
session.log(SessionLog.FINEST, SessionLog.PROPERTIES, "predeploy_end", new Object[]{getPersistenceUnitInfo().getPersistenceUnitName(), state, factoryCount});
return null;
} else if(state == STATE_INITIAL || state == STATE_UNDEPLOYED) {
persistenceUnitInfo = info;
}
// state is INITIAL, PREDEPLOY_FAILED or UNDEPLOYED
try {
predeployProperties = mergeMaps(extendedProperties, persistenceUnitInfo.getProperties());
// Translate old properties.
// This should be done before using properties (i.e. ServerPlatform).
translateOldProperties(predeployProperties, null);
String sessionsXMLStr = (String)predeployProperties.get(PersistenceUnitProperties.SESSIONS_XML);
String sessionNameStr = (String)predeployProperties.get(PersistenceUnitProperties.SESSION_NAME);
if (sessionsXMLStr != null) {
isSessionLoadedFromSessionsXML = true;
}
// Create server session (it needs to be done before initializing ServerPlatform and logging).
// If a sessions-xml is used this will get replaced later, but is required for logging.
session = new ServerSession(new Project(new DatabaseLogin()));
// ServerSession name and ServerPlatform must be set prior to setting the loggers.
setServerSessionName(predeployProperties);
ClassLoader realClassLoader = persistenceUnitInfo.getClassLoader();
updateServerPlatform(predeployProperties, realClassLoader);
// Update loggers and settings for the singleton logger and the session logger.
updateLoggers(predeployProperties, true, false, realClassLoader);
// If it's SE case and the pu has been undeployed weaving again here is impossible:
// the classes were loaded already. Therefore using temporaryClassLoader is no longer required.
// Moreover, it causes problem in case the same factory is opened and closed many times:
// eventually it causes "java.lang.OutOfMemoryError: PermGen space".
// It seems that tempLoaders are not garbage collected, therefore each predeploy would add new
// classes to Permanent Generation heap.
// Therefore this doesn't really fix the problem but rather makes it less severe: in case of
// the factory opened / closed 20 times only one temp. class loader may be left behind - not 20.
// Another workaround would be increasing Permanent Generation Heap size by adding VM argument -XX:MaxPermSize=256m.
if(!this.isInContainerMode && state==STATE_UNDEPLOYED) {
privateClassLoader = realClassLoader;
} else {
// Get the temporary classLoader based on the platform
JPAClassLoaderHolder privateClassLoaderHolder = session.getServerPlatform().getNewTempClassLoader(info);
privateClassLoader = privateClassLoaderHolder.getClassLoader();
// Bug 229634: If we switched to using the non-temporary classLoader then disable weaving
if(!privateClassLoaderHolder.isTempClassLoader()) {
// Disable dynamic weaving for the duration of this predeploy()
enableWeaving = Boolean.FALSE;
}
}
//Update performance profiler
updateProfiler(predeployProperties,realClassLoader);
// Cannot start logging until session and log and initialized, so log start of predeploy here.
session.log(SessionLog.FINEST, SessionLog.PROPERTIES, "predeploy_begin", new Object[]{getPersistenceUnitInfo().getPersistenceUnitName(), state, factoryCount});
if (isSessionLoadedFromSessionsXML) {
// Loading session from sessions-xml.
session.log(SessionLog.FINEST, SessionLog.PROPERTIES, "loading_session_xml", sessionsXMLStr, sessionNameStr);
if (sessionNameStr == null) {
throw new PersistenceException(EntityManagerSetupException.sessionNameNeedBeSpecified(info.getPersistenceUnitName(), sessionsXMLStr));
}
XMLSessionConfigLoader xmlLoader = new XMLSessionConfigLoader(sessionsXMLStr);
// Do not register the session with the SessionManager at this point, create temporary session using a local SessionManager and private class loader.
// This allows for the project to be accessed without loading any of the classes to allow weaving.
Session tempSession = new SessionManager().getSession(xmlLoader, sessionNameStr, privateClassLoader, false, false);
// Load path of sessions-xml resource before throwing error so user knows which sessions-xml file was found (may be multiple).
session.log(SessionLog.FINEST, SessionLog.PROPERTIES, "sessions_xml_path_where_session_load_from", xmlLoader.getSessionName(), xmlLoader.getResourcePath());
if (tempSession == null) {
throw new PersistenceException(ValidationException.noSessionFound(sessionNameStr, sessionsXMLStr));
}
if (tempSession.isServerSession()) {
session = (ServerSession) tempSession;
} else {
throw new PersistenceException(EntityManagerSetupException.sessionLoadedFromSessionsXMLMustBeServerSession(info.getPersistenceUnitName(), (String)predeployProperties.get(PersistenceUnitProperties.SESSIONS_XML), tempSession));
}
// Must now reset logging and server-platform on the loaded session.
// ServerSession name and ServerPlatform must be set prior to setting the loggers.
setServerSessionName(predeployProperties);
updateServerPlatform(predeployProperties, privateClassLoader);
// Update loggers and settings for the singleton logger and the session logger.
updateLoggers(predeployProperties, true, false, privateClassLoader);
}
warnOldProperties(predeployProperties, session);
session.getPlatform().setConversionManager(new JPAConversionManager());
PersistenceUnitTransactionType transactionType=null;
//bug 5867753: find and override the transaction type
String transTypeString = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.TRANSACTION_TYPE, predeployProperties, session);
if ( transTypeString != null ){
transactionType=PersistenceUnitTransactionType.valueOf(transTypeString);
} else if (persistenceUnitInfo!=null){
transactionType=persistenceUnitInfo.getTransactionType();
}
if (!isValidationOnly(predeployProperties, false) && persistenceUnitInfo != null && transactionType == PersistenceUnitTransactionType.JTA) {
if (predeployProperties.get(PersistenceUnitProperties.JTA_DATASOURCE) == null && persistenceUnitInfo.getJtaDataSource() == null) {
throw new PersistenceException(EntityManagerSetupException.jtaPersistenceUnitInfoMissingJtaDataSource(persistenceUnitInfo.getPersistenceUnitName()));
}
}
// this flag is used to disable work done as a result of the LAZY hint on OneToOne and ManyToOne mappings
if((state == STATE_INITIAL || state == STATE_UNDEPLOYED)) {
if(null == enableWeaving) {
enableWeaving = Boolean.TRUE;
}
isWeavingStatic = false;
String weaving = getConfigPropertyAsString(PersistenceUnitProperties.WEAVING);
if (weaving != null && weaving.equalsIgnoreCase("false")) {
enableWeaving = Boolean.FALSE;
}else if (weaving != null && weaving.equalsIgnoreCase("static")) {
isWeavingStatic = true;
}
}
boolean throwExceptionOnFail = "true".equalsIgnoreCase(
EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.THROW_EXCEPTIONS, predeployProperties, "true", session));
ClassTransformer transformer = null;
boolean weaveChangeTracking = false;
boolean weaveLazy = false;
boolean weaveEager = false;
boolean weaveFetchGroups = false;
boolean weaveInternal = false;
if (enableWeaving) {
weaveChangeTracking = "true".equalsIgnoreCase(EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.WEAVING_CHANGE_TRACKING, predeployProperties, "true", session));
weaveLazy = "true".equalsIgnoreCase(EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.WEAVING_LAZY, predeployProperties, "true", session));
weaveEager = "true".equalsIgnoreCase(EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.WEAVING_EAGER, predeployProperties, "false", session));
weaveFetchGroups = "true".equalsIgnoreCase(EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.WEAVING_FETCHGROUPS, predeployProperties, "true", session));
weaveInternal = "true".equalsIgnoreCase(EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.WEAVING_INTERNAL, predeployProperties, "true", session));
}
if (!isSessionLoadedFromSessionsXML ) {
// Create an instance of MetadataProcessor for specified persistence unit info
processor = new MetadataProcessor(persistenceUnitInfo, session, privateClassLoader, enableWeaving, weaveEager);
// Process the Object/relational metadata from XML and annotations.
PersistenceUnitProcessor.processORMetadata(processor, throwExceptionOnFail);
if (session.getIntegrityChecker().hasErrors()){
session.handleException(new IntegrityException(session.getIntegrityChecker()));
}
// The transformer is capable of altering domain classes to handle a LAZY hint for OneToOne mappings. It will only
// be returned if we we are mean to process these mappings
if (enableWeaving) {
// build a list of entities the persistence unit represented by this EntityManagerSetupImpl will use
Collection entities = PersistenceUnitProcessor.buildEntityList(processor.getProject(), privateClassLoader);
transformer = TransformerFactory.createTransformerAndModifyProject(session, entities, privateClassLoader, weaveLazy, weaveChangeTracking, weaveFetchGroups, weaveInternal);
}
} else {
// The transformer is capable of altering domain classes to handle a LAZY hint for OneToOne mappings. It will only
// be returned if we we are meant to process these mappings.
if (enableWeaving) {
// If deploying from a sessions-xml it is still desirable to allow the classes to be weaved.
// build a list of entities the persistence unit represented by this EntityManagerSetupImpl will use
Collection persistenceClasses = new ArrayList(session.getProject().getDescriptors().keySet());
transformer = TransformerFactory.createTransformerAndModifyProject(session, persistenceClasses, privateClassLoader, weaveLazy, weaveChangeTracking, weaveFetchGroups, weaveInternal);
}
}
// factoryCount is not incremented only in case of a first call to preDeploy
// in non-container mode: this call is not associated with a factory
// but rather done by JavaSECMPInitializer.callPredeploy (typically in preMain).
if((state != STATE_INITIAL && state != STATE_UNDEPLOYED) || this.isInContainerMode()) {
factoryCount++;
}
state = STATE_PREDEPLOYED;
session.log(SessionLog.FINEST, SessionLog.PROPERTIES, "predeploy_end", new Object[]{getPersistenceUnitInfo().getPersistenceUnitName(), state, factoryCount});
//gf3146: if static weaving is used, we should not return a transformer. Transformer should still be created though as it modifies descriptors
if (isWeavingStatic) {
return null;
} else {
return transformer;
}
} catch (RuntimeException ex) {
state = STATE_PREDEPLOY_FAILED;
session = null;
throw new PersistenceException(EntityManagerSetupException.predeployFailed(persistenceUnitInfo.getPersistenceUnitName(), ex));
}
}
/**
* Check the provided map for an object with the given key. If that object is not available, check the
* System properties. If it is not available from either location, return the default value.
*/
public String getConfigPropertyAsString(String propertyKey, String defaultValue){
return getConfigPropertyAsStringLogDebug(propertyKey, predeployProperties, defaultValue, session);
}
public String getConfigPropertyAsString(String propertyKey){
return getConfigPropertyAsStringLogDebug(propertyKey, predeployProperties, session);
}
/**
* Return the name of the session this SetupImpl is building. The session name is only known at deploy
* time and if this method is called prior to that, this method will return null.
*/
public String getDeployedSessionName(){
return session != null ? session.getName() : null;
}
public PersistenceUnitInfo getPersistenceUnitInfo(){
return persistenceUnitInfo;
}
public boolean isValidationOnly(Map m) {
return isValidationOnly(m, true);
}
protected boolean isValidationOnly(Map m, boolean shouldMergeMap) {
if (shouldMergeMap) {
m = mergeWithExistingMap(m);
}
String validationOnlyString = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.VALIDATION_ONLY_PROPERTY, m, session);
if (validationOnlyString != null) {
return Boolean.parseBoolean(validationOnlyString);
} else {
return false;
}
}
public boolean shouldGetSessionOnCreateFactory(Map m) {
m = mergeWithExistingMap(m);
return isValidationOnly(m, false);
}
protected Map mergeWithExistingMap(Map m) {
if(predeployProperties != null) {
return mergeMaps(m, predeployProperties);
} else if(persistenceUnitInfo != null) {
return mergeMaps(m, persistenceUnitInfo.getProperties());
} else {
return m;
}
}
public boolean isInContainerMode(){
return isInContainerMode;
}
/**
* Override the default login creation method.
* If persistenceInfo is available, use the information from it to setup the login
* and possibly to set readConnectionPool.
*/
protected void updateLogins(Map m){
DatasourceLogin login = session.getLogin();
// Note: This call does not checked the stored persistenceUnitInfo or extended properties because
// the map passed into this method should represent the full set of properties we expect to process
String user = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_USER, m, session);
String password = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_PASSWORD, m, session);
if(user != null) {
login.setUserName(user);
}
if (password != null) {
login.setPassword(securableObjectHolder.getSecurableObject().decryptPassword(password));
}
String eclipselinkPlatform = PropertiesHandler.getPropertyValueLogDebug(PersistenceUnitProperties.TARGET_DATABASE, m, session);
if (eclipselinkPlatform != null) {
login.setPlatformClassName(eclipselinkPlatform, persistenceUnitInfo.getClassLoader());
}
PersistenceUnitTransactionType transactionType = persistenceUnitInfo.getTransactionType();
//bug 5867753: find and override the transaction type using properties
String transTypeString = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.TRANSACTION_TYPE, m, session);
if (transTypeString != null) {
transactionType = PersistenceUnitTransactionType.valueOf(transTypeString);
}
//find the jta datasource
javax.sql.DataSource jtaDatasource = getDatasourceFromProperties(m, PersistenceUnitProperties.JTA_DATASOURCE, persistenceUnitInfo.getJtaDataSource());
//find the non jta datasource
javax.sql.DataSource nonjtaDatasource = getDatasourceFromProperties(m, PersistenceUnitProperties.NON_JTA_DATASOURCE, persistenceUnitInfo.getNonJtaDataSource());
if (isValidationOnly(m, false) && transactionType == PersistenceUnitTransactionType.JTA && jtaDatasource == null) {
updateLoginDefaultConnector(login, m);
return;
}
login.setUsesExternalTransactionController(transactionType == PersistenceUnitTransactionType.JTA);
javax.sql.DataSource mainDatasource = null;
javax.sql.DataSource readDatasource = null;
if (login.shouldUseExternalTransactionController()) {
// JtaDataSource is guaranteed to be non null - otherwise exception would've been thrown earlier
mainDatasource = jtaDatasource;
// only define readDatasource if there is jta mainDatasource
readDatasource = nonjtaDatasource;
} else {
// JtaDataSource will be ignored because transactionType is RESOURCE_LOCAL
if (jtaDatasource != null) {
session.log(SessionLog.WARNING, SessionLog.TRANSACTION, "resource_local_persistence_init_info_ignores_jta_data_source", persistenceUnitInfo.getPersistenceUnitName());
}
if (nonjtaDatasource != null) {
mainDatasource = nonjtaDatasource;
} else {
updateLoginDefaultConnector(login, m);
return;
}
}
// mainDatasource is guaranteed to be non null
if (!(login.getConnector() instanceof JNDIConnector)) {
JNDIConnector jndiConnector;
if (mainDatasource instanceof DataSourceImpl) {
//Bug5209363 Pass in the datasource name instead of the dummy datasource
jndiConnector = new JNDIConnector(((DataSourceImpl)mainDatasource).getName());
} else {
jndiConnector = new JNDIConnector(mainDatasource);
}
login.setConnector(jndiConnector);
login.setUsesExternalConnectionPooling(true);
}
// set readLogin
if(readDatasource != null) {
DatasourceLogin readLogin = (DatasourceLogin)login.clone();
readLogin.dontUseExternalTransactionController();
JNDIConnector jndiConnector;
if (readDatasource instanceof DataSourceImpl) {
//Bug5209363 Pass in the datasource name instead of the dummy datasource
jndiConnector = new JNDIConnector(((DataSourceImpl)readDatasource).getName());
} else {
jndiConnector = new JNDIConnector(readDatasource);
}
readLogin.setConnector(jndiConnector);
session.setReadConnectionPool(readLogin);
}
}
/**
* This is used to return either the defaultDatasource or, if one exists, a datasource
* defined under the property from the Map m. This method will build a DataSourceImpl
* object to hold the url if the property in Map m defines a string instead of a datasource.
*/
protected javax.sql.DataSource getDatasourceFromProperties(Map m, String property, javax.sql.DataSource defaultDataSource){
Object datasource = getConfigPropertyLogDebug(property, m, session);
if ( datasource == null ){
return defaultDataSource;
}
if ( datasource instanceof String){
// Create a dummy DataSource that will throw an exception on access
return new DataSourceImpl((String)datasource, null, null, null);
}
if ( !(datasource instanceof javax.sql.DataSource) ){
//A warning should be enough. Though an error might be better, the properties passed in could contain anything
session.log(SessionLog.WARNING, SessionLog.PROPERTIES, "invalid_datasource_property_value", property, datasource);
return defaultDataSource;
}
return (javax.sql.DataSource)datasource;
}
/**
* In cases where there is no data source, we will use properties to configure the login for
* our session. This method gets those properties and sets them on the login.
*/
protected void updateLoginDefaultConnector(DatasourceLogin login, Map m){
//Login info might be already set with sessions.xml and could be overrided by session customizer after this
//If login has default connector then JDBC properties update(override) the login info
if ((login.getConnector() instanceof DefaultConnector)) {
DatabaseLogin dbLogin = (DatabaseLogin)login;
// Note: This call does not checked the stored persistenceUnitInfo or extended properties because
// the map passed into this method should represent the full set of properties we expect to process
String jdbcDriver = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_DRIVER, m, session);
String connectionString = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_URL, m, session);
if(connectionString != null) {
dbLogin.setConnectionString(connectionString);
}
if(jdbcDriver != null) {
dbLogin.setDriverClassName(jdbcDriver);
}
}
}
protected void updatePools(Map m) {
// Sizes are irrelevant for external connection pool
if(!session.getDefaultConnectionPool().getLogin().shouldUseExternalConnectionPooling()) {
String strWriteMin = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_WRITE_CONNECTIONS_MIN, m, session);
if(strWriteMin != null) {
session.getDefaultConnectionPool().setMinNumberOfConnections(Integer.parseInt(strWriteMin));
}
String strWriteMax = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_WRITE_CONNECTIONS_MAX, m, session);
if(strWriteMax != null) {
session.getDefaultConnectionPool().setMaxNumberOfConnections(Integer.parseInt(strWriteMax));
}
}
// Sizes and shared option are irrelevant for external connection pool
if (!session.getReadConnectionPool().getLogin().shouldUseExternalConnectionPooling()) {
String strReadMin = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_READ_CONNECTIONS_MIN, m, session);
if(strReadMin != null) {
session.getReadConnectionPool().setMinNumberOfConnections(Integer.parseInt(strReadMin));
}
String strReadMax = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_READ_CONNECTIONS_MAX, m, session);
if (strReadMax != null) {
session.getReadConnectionPool().setMaxNumberOfConnections(Integer.parseInt(strReadMax));
}
String strShouldUseShared = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_READ_CONNECTIONS_SHARED, m,session);
if(strShouldUseShared != null) {
boolean shouldUseShared = Boolean.parseBoolean(strShouldUseShared);
boolean sessionUsesShared = session.getReadConnectionPool() instanceof ReadConnectionPool;
if(shouldUseShared != sessionUsesShared) {
Login readLogin = session.getReadConnectionPool().getLogin();
int nReadMin = session.getReadConnectionPool().getMinNumberOfConnections();
int nReadMax = session.getReadConnectionPool().getMaxNumberOfConnections();
if(shouldUseShared) {
session.useReadConnectionPool(nReadMin, nReadMax);
} else {
session.useExclusiveReadConnectionPool(nReadMin, nReadMax);
}
// keep original readLogin
session.getReadConnectionPool().setLogin(readLogin);
}
}
}
}
/**
* Normally when a property is missing nothing should be applied to the session.
* However there are several session attributes that defaulted in EJB3 to the values
* different from EclipseLink defaults.
* This function applies defaults for such properties and registers the session.
* All other session-related properties are applied in updateServerSession.
* Note that updateServerSession may be called several times on the same session
* (before login), but initServerSession is called just once - before the first call
* to updateServerSession.
* @param properties the persistence unit properties.
*/
protected void initServerSession(Map properties) {
assignCMP3Policy();
// This server session could have been initialized in predeploy with
// another set of properties that would have set the session name to
// something else. We need to verify session name here.
String newName = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.SESSION_NAME, properties, session);
if (newName != null && !(newName.equals(session.getName()))) {
session.setName(newName);
}
// Register session that has been created earlier.
addSessionToGlobalSessionManager();
}
/**
* Set ServerSession name but do not register the session.
* The session registration should be done in sync
* with increment of the deployment counter, as otherwise the
* undeploy will not behave correctly in case of a more
* than one predeploy request for the same session name.
* @param m the combined properties map.
*/
protected void setServerSessionName(Map m) {
// use default session name if none is provided
String name = EntityManagerFactoryProvider.getConfigPropertyAsString(PersistenceUnitProperties.SESSION_NAME, m);
if(name == null) {
if (persistenceUnitInfo.getPersistenceUnitRootUrl() != null){
name = persistenceUnitInfo.getPersistenceUnitRootUrl().toString() + "-" + persistenceUnitInfo.getPersistenceUnitName();
} else {
name = persistenceUnitInfo.getPersistenceUnitName();
}
}
session.setName(name);
}
/**
* Make any changes to our ServerSession that can be made after it is created.
*/
protected void updateServerSession(Map m, ClassLoader loader) {
if (session == null || session.isConnected()) {
return;
}
// In deploy Session name and ServerPlatform could've changed which will affect the loggers.
boolean serverPlatformChanged = updateServerPlatform(m, loader);
boolean sessionNameChanged = updateSessionName(m);
updateLoggers(m, serverPlatformChanged, sessionNameChanged, loader);
updateProfiler(m,loader);
String shouldBindString = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_BIND_PARAMETERS, m, session);
if (shouldBindString != null) {
session.getPlatform().setShouldBindAllParameters(Boolean.parseBoolean(shouldBindString));
}
updateLogins(m);
if (!session.getLogin().shouldUseExternalTransactionController()) {
session.getServerPlatform().disableJTA();
}
setSessionEventListener(m, loader);
setExceptionHandler(m, loader);
updatePools(m);
if (!isSessionLoadedFromSessionsXML) {
updateDescriptorCacheSettings(m, loader);
}
updateConnectionPolicy(m);
updateBatchWritingSetting(m);
updateNativeSQLSetting(m);
updateCacheStatementSettings(m);
updateTemporalMutableSetting(m);
// Customizers should be processed last
processDescriptorCustomizers(m, loader);
processSessionCustomizer(m, loader);
setDescriptorNamedQueries(m);
}
/**
* This sets the isInContainerMode flag.
* "true" indicates container case, "false" - SE.
*/
public void setIsInContainerMode(boolean isInContainerMode) {
this.isInContainerMode = isInContainerMode;
}
protected void processSessionCustomizer(Map m, ClassLoader loader) {
String sessionCustomizerClassName = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.SESSION_CUSTOMIZER, m, session);
if (sessionCustomizerClassName == null) {
return;
}
Class sessionCustomizerClass = findClassForProperty(sessionCustomizerClassName, PersistenceUnitProperties.SESSION_CUSTOMIZER, loader);
SessionCustomizer sessionCustomizer;
try {
sessionCustomizer = (SessionCustomizer)sessionCustomizerClass.newInstance();
sessionCustomizer.customize(session);
} catch (Exception ex) {
throw EntityManagerSetupException.failedWhileProcessingProperty(PersistenceUnitProperties.SESSION_CUSTOMIZER, sessionCustomizerClassName, ex);
}
}
protected void initOrUpdateLogging(Map m, SessionLog log) {
String logLevelString = PropertiesHandler.getPropertyValueLogDebug(PersistenceUnitProperties.LOGGING_LEVEL, m, session);
if (logLevelString != null) {
log.setLevel(AbstractSessionLog.translateStringToLoggingLevel(logLevelString));
}
// category-specific logging level
Map categoryLogLevelMap = PropertiesHandler.getPrefixValuesLogDebug(PersistenceUnitProperties.CATEGORY_LOGGING_LEVEL_, m, session);
if(!categoryLogLevelMap.isEmpty()) {
Iterator it = categoryLogLevelMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String category = (String)entry.getKey();
String value = (String)entry.getValue();
log.setLevel(AbstractSessionLog.translateStringToLoggingLevel(value), category);
}
}
String tsString = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.LOGGING_TIMESTAMP, m, session);
if (tsString != null) {
log.setShouldPrintDate(Boolean.parseBoolean(tsString));
}
String threadString = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.LOGGING_THREAD, m, session);
if (threadString != null) {
log.setShouldPrintThread(Boolean.parseBoolean(threadString));
}
String sessionString = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.LOGGING_SESSION, m, session);
if (sessionString != null) {
log.setShouldPrintSession(Boolean.parseBoolean(sessionString));
}
String exString = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.LOGGING_EXCEPTIONS, m, session);
if (exString != null) {
log.setShouldLogExceptionStackTrace(Boolean.parseBoolean(exString));
}
}
/**
* Updates server session name if changed.
* @return true if the name has changed.
*/
protected boolean updateSessionName(Map m) {
String newName = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.SESSION_NAME, m, session);
if(newName == null || newName.equals(session.getName())) {
return false;
}
removeSessionFromGlobalSessionManager();
session.setName(newName);
addSessionToGlobalSessionManager();
return true;
}
protected void processDescriptorCustomizers(Map m, ClassLoader loader) {
Map customizerMap = PropertiesHandler.getPrefixValuesLogDebug(PersistenceUnitProperties.DESCRIPTOR_CUSTOMIZER_, m, session);
if (customizerMap.isEmpty()) {
return;
}
Iterator it = customizerMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String name = (String)entry.getKey();
ClassDescriptor descriptor = session.getDescriptorForAlias(name);
if (descriptor == null) {
try {
Class javaClass = findClass(name, loader);
descriptor = session.getDescriptor(javaClass);
} catch (Exception ex) {
// Ignore exception
}
}
if (descriptor != null) {
String customizerClassName = (String)entry.getValue();
Class customizerClass = findClassForProperty(customizerClassName, PersistenceUnitProperties.DESCRIPTOR_CUSTOMIZER_ + name, loader);
try {
DescriptorCustomizer customizer = (DescriptorCustomizer)customizerClass.newInstance();
customizer.customize(descriptor);
} catch (Exception ex) {
throw EntityManagerSetupException.failedWhileProcessingProperty(PersistenceUnitProperties.DESCRIPTOR_CUSTOMIZER_ + name, customizerClassName, ex);
}
}
}
}
public boolean isInitial() {
return state == STATE_INITIAL;
}
public boolean isPredeployed() {
return state == STATE_PREDEPLOYED;
}
public boolean isDeployed() {
return state == STATE_DEPLOYED;
}
public boolean isUndeployed() {
return state == STATE_UNDEPLOYED;
}
public boolean isPredeployFailed() {
return state == STATE_PREDEPLOY_FAILED;
}
public boolean isDeployFailed() {
return state == STATE_DEPLOY_FAILED;
}
public int getFactoryCount() {
return factoryCount;
}
public boolean shouldRedeploy() {
return state == STATE_UNDEPLOYED || state == STATE_PREDEPLOY_FAILED;
}
/**
* Undeploy may be called several times, but only the call that decreases
* factoryCount to 0 disconnects the session and removes it from the session manager.
* This method and predeploy - the only methods altering factoryCount - should be synchronized.
* After undeploy call that turns factoryCount to 0:
* session==null;
* PREDEPLOYED, DEPLOYED and DEPLOYED_FAILED states change to UNDEPLOYED state.
*/
public synchronized void undeploy() {
if (state == STATE_INITIAL || state == STATE_PREDEPLOY_FAILED || state == STATE_UNDEPLOYED) {
// must already have factoryCount==0 and session==null
return;
}
// state is PREDEPLOYED, DEPLOYED or DEPLOY_FAILED
session.log(SessionLog.FINEST, SessionLog.PROPERTIES, "undeploy_begin", new Object[]{getPersistenceUnitInfo().getPersistenceUnitName(), state, factoryCount});
try {
factoryCount--;
if(factoryCount > 0) {
return;
}
state = STATE_UNDEPLOYED;
removeSessionFromGlobalSessionManager();
} finally {
session.log(SessionLog.FINEST, SessionLog.PROPERTIES, "undeploy_end", new Object[]{getPersistenceUnitInfo().getPersistenceUnitName(), state, factoryCount});
if(state == STATE_UNDEPLOYED) {
session = null;
}
}
}
/**
* Allow customized session event listener to be added into session.
* The method needs to be called in deploy stage.
*/
protected void setSessionEventListener(Map m, ClassLoader loader){
//Set event listener if it has been specified.
String sessionEventListenerClassName = EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.SESSION_EVENT_LISTENER_CLASS, m, session);
if(sessionEventListenerClassName!=null){
Class sessionEventListenerClass = findClassForProperty(sessionEventListenerClassName,PersistenceUnitProperties.SESSION_EVENT_LISTENER_CLASS, loader);
try {
SessionEventListener sessionEventListener = (SessionEventListener)buildObjectForClass(sessionEventListenerClass, SessionEventListener.class);
if(sessionEventListener!=null){
session.getEventManager().getListeners().add(sessionEventListener);
} else {
session.handleException(ValidationException.invalidSessionEventListenerClass(sessionEventListenerClassName));
}
} catch (IllegalAccessException e) {
session.handleException(ValidationException.cannotInstantiateSessionEventListenerClass(sessionEventListenerClassName,e));
} catch (PrivilegedActionException e) {
session.handleException(ValidationException.cannotInstantiateSessionEventListenerClass(sessionEventListenerClassName,e));
} catch (InstantiationException e) {
session.handleException(ValidationException.cannotInstantiateSessionEventListenerClass(sessionEventListenerClassName,e));
}
}
}
/**
* Allow customized exception handler to be added into session.
* The method needs to be called in deploy and pre-deploy stage.
*/
protected void setExceptionHandler(Map m, ClassLoader loader){
//Set exception handler if it was specified.
String exceptionHandlerClassName = EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.EXCEPTION_HANDLER_CLASS, m, session);
if(exceptionHandlerClassName!=null){
Class exceptionHandlerClass = findClassForProperty(exceptionHandlerClassName,PersistenceUnitProperties.EXCEPTION_HANDLER_CLASS, loader);
try {
ExceptionHandler exceptionHandler = (ExceptionHandler)buildObjectForClass(exceptionHandlerClass, ExceptionHandler.class);
if (exceptionHandler!=null){
session.setExceptionHandler(exceptionHandler);
} else {
session.handleException(ValidationException.invalidExceptionHandlerClass(exceptionHandlerClassName));
}
} catch (IllegalAccessException e) {
session.handleException(ValidationException.cannotInstantiateExceptionHandlerClass(exceptionHandlerClassName,e));
} catch (PrivilegedActionException e) {
session.handleException(ValidationException.cannotInstantiateExceptionHandlerClass(exceptionHandlerClassName,e));
} catch (InstantiationException e) {
session.handleException(ValidationException.cannotInstantiateExceptionHandlerClass(exceptionHandlerClassName,e));
}
}
}
/**
* Update batch writing setting.
* The method needs to be called in deploy stage.
*/
protected void updateBatchWritingSetting(Map persistenceProperties) {
String batchWritingSettingString = PropertiesHandler.getPropertyValueLogDebug(PersistenceUnitProperties.BATCH_WRITING, persistenceProperties, session);
if (batchWritingSettingString != null) {
session.getPlatform().setUsesBatchWriting(batchWritingSettingString != BatchWriting.None);
if (batchWritingSettingString == BatchWriting.JDBC) {
session.getPlatform().setUsesJDBCBatchWriting(true);
session.getPlatform().setUsesNativeBatchWriting(false);
} else if (batchWritingSettingString == BatchWriting.Buffered) {
session.getPlatform().setUsesJDBCBatchWriting(false);
session.getPlatform().setUsesNativeBatchWriting(false);
} else if (batchWritingSettingString == BatchWriting.OracleJDBC) {
session.getPlatform().setUsesNativeBatchWriting(true);
session.getPlatform().setUsesJDBCBatchWriting(true);
}
}
}
/**
* Enable or disable the capability of Native SQL function.
* The method needs to be called in deploy stage.
*/
protected void updateNativeSQLSetting(Map m){
//Set Native SQL flag if it was specified.
String nativeSQLString = EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.NATIVE_SQL, m, session);
if(nativeSQLString!=null){
if(nativeSQLString.equalsIgnoreCase("true") ){
session.getProject().getLogin().useNativeSQL();
}else if (nativeSQLString.equalsIgnoreCase("false")){
session.getProject().getLogin().dontUseNativeSQL();
}else{
session.handleException(ValidationException.invalidBooleanValueForSettingNativeSQL(nativeSQLString));
}
}
}
/**
* Enable or disable statements cached, update statements cache size.
* The method needs to be called in deploy stage.
*/
protected void updateCacheStatementSettings(Map m){
// Cache statements if flag was specified.
String statmentsNeedBeCached = EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.CACHE_STATEMENTS, m, session);
if (statmentsNeedBeCached!=null) {
if (statmentsNeedBeCached.equalsIgnoreCase("true")) {
if (session.getConnectionPools().size()>0){//And if connection pooling is configured,
session.getProject().getLogin().setShouldCacheAllStatements(true);
} else {
session.log(SessionLog.WARNING, SessionLog.PROPERTIES, "persistence_unit_ignores_statments_cache_setting", new Object[]{null});
}
} else if (statmentsNeedBeCached.equalsIgnoreCase("false")) {
session.getProject().getLogin().setShouldCacheAllStatements(false);
} else {
session.handleException(ValidationException.invalidBooleanValueForEnableStatmentsCached(statmentsNeedBeCached));
}
}
// Set statement cache size if specified.
String cacheStatementsSize = EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.CACHE_STATEMENTS_SIZE, m, session);
if (cacheStatementsSize!=null) {
try {
session.getProject().getLogin().setStatementCacheSize(Integer.parseInt(cacheStatementsSize));
} catch (NumberFormatException e) {
session.handleException(ValidationException.invalidCacheStatementsSize(cacheStatementsSize,e.getMessage()));
}
}
}
/**
* Enable or disable default temporal mutable setting.
* The method needs to be called in deploy stage.
*/
protected void updateTemporalMutableSetting(Map m) {
// Cache statements if flag was specified.
String temporalMutable = EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.TEMPORAL_MUTABLE, m, session);
if (temporalMutable != null) {
if (temporalMutable.equalsIgnoreCase("true")) {
session.getProject().setDefaultTemporalMutable(true);
} else if (temporalMutable.equalsIgnoreCase("false")) {
session.getProject().setDefaultTemporalMutable(false);
} else {
session.handleException(ValidationException.invalidBooleanValueForProperty(temporalMutable, PersistenceUnitProperties.TEMPORAL_MUTABLE));
}
}
}
/**
* Copy named queries defined in EclipseLink descriptor into the session if it was indicated to do so.
*/
protected void setDescriptorNamedQueries(Map m) {
// Copy named queries to session if the flag has been specified.
String addNamedQueriesString = EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.INCLUDE_DESCRIPTOR_QUERIES, m, session);
if (addNamedQueriesString!=null) {
if (addNamedQueriesString.equalsIgnoreCase("true")) {
session.copyDescriptorNamedQueries(false);
} else {
if (!addNamedQueriesString.equalsIgnoreCase("false")) {
session.handleException(ValidationException.invalidBooleanValueForAddingNamedQueries(addNamedQueriesString));
}
}
}
}
}
| jpa/org.eclipse.persistence.jpa/src/org/eclipse/persistence/internal/jpa/EntityManagerSetupImpl.java | /*******************************************************************************
* Copyright (c) 1998, 2008 Oracle. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
*
* 05/28/2008-1.0M8 Andrei Ilitchev
* - 224964: Provide support for Proxy Authentication through JPA.
* Added updateConnectionPolicy method to support EXCLUSIVE_CONNECTION property.
* Some methods, like setSessionEventListener called from deploy still used predeploy properties,
* that meant it was impossible to set listener through createEMF property in SE case with an agent - fixed that.
* Also if creating / closing the same emSetupImpl many times (24 in my case) "java.lang.OutOfMemoryError: PermGen space" resulted:
* partially fixed partially worked around this - see a big comment in predeploy method.
******************************************************************************/
package org.eclipse.persistence.internal.jpa;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.util.*;
import java.io.FileWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import javax.persistence.spi.PersistenceUnitInfo;
import javax.persistence.spi.ClassTransformer;
import javax.persistence.PersistenceException;
import org.eclipse.persistence.internal.databaseaccess.DatasourcePlatform;
import org.eclipse.persistence.internal.weaving.TransformerFactory;
import org.eclipse.persistence.sessions.JNDIConnector;
import org.eclipse.persistence.logging.AbstractSessionLog;
import org.eclipse.persistence.logging.SessionLog;
import org.eclipse.persistence.internal.security.PrivilegedAccessHelper;
import org.eclipse.persistence.internal.security.PrivilegedClassForName;
import org.eclipse.persistence.internal.sessions.AbstractSession;
import org.eclipse.persistence.internal.sessions.PropertiesHandler;
import org.eclipse.persistence.sequencing.Sequence;
import org.eclipse.persistence.sessions.*;
import org.eclipse.persistence.sessions.server.ConnectionPolicy;
import org.eclipse.persistence.sessions.server.ReadConnectionPool;
import org.eclipse.persistence.sessions.server.ServerSession;
import org.eclipse.persistence.internal.jpa.metadata.MetadataProcessor;
import org.eclipse.persistence.sessions.factories.SessionManager;
import org.eclipse.persistence.sessions.factories.XMLSessionConfigLoader;
import org.eclipse.persistence.config.BatchWriting;
import org.eclipse.persistence.config.DescriptorCustomizer;
import org.eclipse.persistence.config.ExclusiveConnectionMode;
import org.eclipse.persistence.config.LoggerType;
import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.eclipse.persistence.config.ProfilerType;
import org.eclipse.persistence.config.SessionCustomizer;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.platform.server.CustomServerPlatform;
import org.eclipse.persistence.platform.server.ServerPlatform;
import org.eclipse.persistence.exceptions.*;
import org.eclipse.persistence.internal.helper.JPAClassLoaderHolder;
import org.eclipse.persistence.internal.helper.JPAConversionManager;
import javax.persistence.spi.PersistenceUnitTransactionType;
import org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor;
import org.eclipse.persistence.internal.helper.Helper;
import org.eclipse.persistence.internal.security.PrivilegedNewInstanceFromClass;
import org.eclipse.persistence.internal.jpa.jdbc.DataSourceImpl;
import org.eclipse.persistence.internal.security.SecurableObjectHolder;
import org.eclipse.persistence.platform.database.converters.StructConverter;
import org.eclipse.persistence.platform.server.ServerPlatformBase;
import org.eclipse.persistence.tools.profiler.PerformanceProfiler;
import org.eclipse.persistence.tools.profiler.QueryMonitor;
import static org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider.*;
/**
* INTERNAL:
* An EclipseLink specific implementer of the EntityManagerInitializer interface.
* This class handles deployment of a persistence unit.
* In predeploy the meta-data is processed and weaver transformer is returned to allow weaving of the persistent classes.
* In deploy the project and session are initialize and registered.
*/
public class EntityManagerSetupImpl {
/*
* Design Pattern in use: Builder pattern
* EntityManagerSetupImpl, MetadataProcessor and MetadataProject
* play the role of director, builder and product respectively.
* See processORMetadata which is the factory method.
*
*/
protected MetadataProcessor processor = null;
protected PersistenceUnitInfo persistenceUnitInfo = null;
protected Map predeployProperties = null;
// count a number of open factories that use this object.
protected int factoryCount = 0;
protected ServerSession session = null;
// true if predeploy called by createContainerEntityManagerFactory; false - createEntityManagerFactory
protected boolean isInContainerMode = false;
protected boolean isSessionLoadedFromSessionsXML=false;
// indicates whether weaving was used on the first run through predeploy (in STATE_INITIAL)
protected Boolean enableWeaving = null;
// indicates that classes have already been woven
protected boolean isWeavingStatic = false;
protected SecurableObjectHolder securableObjectHolder = new SecurableObjectHolder();
// factoryCount==0; session==null
public static final String STATE_INITIAL = "Initial";
// session != null
public static final String STATE_PREDEPLOYED = "Predeployed";
// factoryCount>0; session != null; session stored in SessionManager
public static final String STATE_DEPLOYED = "Deployed";
// factoryCount==0; session==null
public static final String STATE_PREDEPLOY_FAILED="PredeployFailed";
// factoryCount>0; session != null
public static final String STATE_DEPLOY_FAILED = "DeployFailed";
// factoryCount==0; session==null
public static final String STATE_UNDEPLOYED = "Undeployed";
protected String state = STATE_INITIAL;
/**
* Initial -----> PredeployFailed
* | |
* V V
* |-> Predeployed --> DeployFailed
* | | | |
* | V V V
* | Deployed -> Undeployed-->|
* | |
* |<-------------------------V
*/
public static final String ERROR_LOADING_XML_FILE = "error_loading_xml_file";
public static final String EXCEPTION_LOADING_ENTITY_CLASS = "exception_loading_entity_class";
/**
* This method can be used to ensure the session represented by emSetupImpl
* is removed from the SessionManager.
*/
protected void removeSessionFromGlobalSessionManager() {
if (session != null){
if(session.isConnected()) {
session.logout();
}
SessionManager.getManager().getSessions().remove(session.getName());
}
}
/**
* Deploy a persistence session and return an EntityManagerFactory.
*
* Deployment takes a session that was partially created in the predeploy call and makes it whole.
*
* This means doing any configuration that requires the real class definitions for the entities. In
* the predeploy phase we were in a stage where we were not let allowed to load the real classes.
*
* Deploy could be called several times - but only the first call does the actual deploying -
* additional calls allow to update session properties (in case the session is not connected).
*
* Note that there is no need to synchronize deploy method - it doesn't alter factoryCount
* and while deploy is executed no other method can alter the current state
* (predeploy call would just increment factoryCount; undeploy call would not drop factoryCount to 0).
* However precautions should be taken to handle concurrent calls to deploy, because those may
* alter the current state or connect the session.
*
* @param realClassLoader The class loader that was used to load the entity classes. This loader
* will be maintained for the lifespan of the loaded classes.
* @param additionalProperties added to predeployProperties for updateServerSession overriding existing properties.
* In JSE case it allows to alter properties in main (as opposed to preMain where preDeploy is called).
* @return An EntityManagerFactory to be used by the Container to obtain EntityManagers
*/
public ServerSession deploy(ClassLoader realClassLoader, Map additionalProperties) {
if (state != STATE_PREDEPLOYED && state != STATE_DEPLOYED) {
throw new PersistenceException(EntityManagerSetupException.cannotDeployWithoutPredeploy(persistenceUnitInfo.getPersistenceUnitName(), state));
}
// state is PREDEPLOYED or DEPLOYED
session.log(SessionLog.FINEST, SessionLog.PROPERTIES, "deploy_begin", new Object[]{getPersistenceUnitInfo().getPersistenceUnitName(), state, factoryCount});
List<StructConverter> structConverters = null;
try {
Map deployProperties = mergeMaps(additionalProperties, predeployProperties);
translateOldProperties(deployProperties, session);
if (state == STATE_PREDEPLOYED) {
synchronized (session) {
if (state == STATE_PREDEPLOYED) {
try {
// The project is initially created using class names rather than classes. This call will make the conversion.
// If the session was loaded from sessions.xml this will also converter the descriptor classes to the correct class loader.
session.getProject().convertClassNamesToClasses(realClassLoader);
if (!isSessionLoadedFromSessionsXML) {
// listeners and queries require the real classes and are therefore built during deploy using the realClassLoader
processor.setClassLoader(realClassLoader);
processor.addEntityListeners();
processor.addNamedQueries();
// Process the customizers last.
processor.processCustomizers();
structConverters = processor.getStructConverters();
processor = null;
}
initServerSession(deployProperties);
if (session.getIntegrityChecker().hasErrors()){
session.handleException(new IntegrityException(session.getIntegrityChecker()));
}
session.getDatasourcePlatform().getConversionManager().setLoader(realClassLoader);
state = STATE_DEPLOYED;
} catch (RuntimeException ex) {
state = STATE_DEPLOY_FAILED;
// session not discarded here only because it will be used in undeploy method for debug logging.
throw new PersistenceException(EntityManagerSetupException.deployFailed(persistenceUnitInfo.getPersistenceUnitName(), ex));
}
}
}
}
// state is DEPLOYED
if (!session.isConnected()) {
synchronized (session) {
if(!session.isConnected()) {
session.setProperties(deployProperties);
updateServerSession(deployProperties, realClassLoader);
if (isValidationOnly(deployProperties, false)) {
session.initializeDescriptors();
} else {
if (isSessionLoadedFromSessionsXML) {
if (!session.isConnected()) {
session.login();
}
} else {
login(session, deployProperties);
}
if (!isSessionLoadedFromSessionsXML) {
addStructConverters(session, structConverters);
}
generateDDL(session, deployProperties);
}
}
}
}
return session;
} catch (Exception exception) {
PersistenceException persistenceException = null;
if (exception instanceof PersistenceException) {
persistenceException = (PersistenceException)exception;
persistenceException = new PersistenceException(exception);
} else {
persistenceException = new PersistenceException(exception);
}
session.logThrowable(SessionLog.SEVERE, SessionLog.EJB, exception);
throw persistenceException;
} finally {
session.log(SessionLog.FINEST, SessionLog.PROPERTIES, "deploy_end", new Object[]{getPersistenceUnitInfo().getPersistenceUnitName(), state, factoryCount});
}
}
/**
* Adds descriptors plus sequencing info found on the project to the session.
*/
protected void addProjectToSession(ServerSession session, Project project) {
DatasourcePlatform sessionPlatform = (DatasourcePlatform)session.getDatasourceLogin().getDatasourcePlatform();
DatasourcePlatform projectPlatform = (DatasourcePlatform)project.getDatasourceLogin().getDatasourcePlatform();
if (!sessionPlatform.hasDefaultSequence() && projectPlatform.hasDefaultSequence()) {
sessionPlatform.setDefaultSequence(projectPlatform.getDefaultSequence());
}
if ((sessionPlatform.getSequences() == null) || sessionPlatform.getSequences().isEmpty()) {
if ((projectPlatform.getSequences() != null) && !projectPlatform.getSequences().isEmpty()) {
sessionPlatform.setSequences(projectPlatform.getSequences());
}
} else {
if ((projectPlatform.getSequences() != null) && !projectPlatform.getSequences().isEmpty()) {
Iterator itProjectSequences = projectPlatform.getSequences().values().iterator();
while (itProjectSequences.hasNext()) {
Sequence sequence = (Sequence)itProjectSequences.next();
if (!sessionPlatform.getSequences().containsKey(sequence.getName())) {
sessionPlatform.addSequence(sequence);
}
}
}
}
session.addDescriptors(project);
}
/**
* Put the given session into the session manager so it can be looked up later
*/
protected void addSessionToGlobalSessionManager() {
AbstractSession oldSession = (AbstractSession)SessionManager.getManager().getSessions().get(session.getName());
if(oldSession != null) {
throw new PersistenceException(EntityManagerSetupException.attemptedRedeployWithoutClose(session.getName()));
}
SessionManager.getManager().addSession(session);
}
/**
* Add the StructConverters that were specified by annotation on the DatabasePlatform
* This method must be called after the DatabasePlatform has been detected
* @param session
* @param structConverters
*/
public void addStructConverters(Session session, List<StructConverter> structConverters){
for (StructConverter structConverter : structConverters){
if (session.getPlatform().getTypeConverters().get(structConverter.getJavaType()) != null){
throw ValidationException.twoStructConvertersAddedForSameClass(structConverter.getJavaType().getName());
}
session.getPlatform().addStructConverter(structConverter);
}
}
/**
* Assign a CMP3Policy to each descriptor
*/
protected void assignCMP3Policy() {
// all descriptors assigned CMP3Policy
Project project = session.getProject();
for (Iterator iterator = project.getDescriptors().values().iterator(); iterator.hasNext();){
//bug:4406101 changed class cast to base class, which is used in projects generated from 904 xml
ClassDescriptor descriptor = (ClassDescriptor)iterator.next();
if(descriptor.getCMPPolicy() == null) {
descriptor.setCMPPolicy(new CMP3Policy());
}
}
}
/**
* Updates the EclipseLink ServerPlatform class for use with this platform.
* @return true if the ServerPlatform has changed.
*/
protected boolean updateServerPlatform(Map m, ClassLoader loader) {
String serverPlatformClassName = PropertiesHandler.getPropertyValueLogDebug(PersistenceUnitProperties.TARGET_SERVER, m, session);
if(serverPlatformClassName == null) {
// property is not specified - nothing to do.
return false;
}
// originalServerPlatform is always non-null - Session's constructor sets serverPlatform to NoServerPlatform
ServerPlatform originalServerPlatform = session.getServerPlatform();
String originalServerPlatformClassName = originalServerPlatform.getClass().getName();
if(originalServerPlatformClassName.equals(serverPlatformClassName)) {
// nothing to do - use the same value as before
return false;
}
// the new serverPlatform
ServerPlatform serverPlatform = null;
// New platform - create the new instance and set it.
Class cls = findClassForProperty(serverPlatformClassName, PersistenceUnitProperties.TARGET_SERVER, loader);
try {
Constructor constructor = cls.getConstructor(new Class[]{org.eclipse.persistence.sessions.DatabaseSession.class});
serverPlatform = (ServerPlatform)constructor.newInstance(new Object[]{session});
} catch (Exception ex) {
if(ExternalTransactionController.class.isAssignableFrom(cls)) {
// the new serverPlatform is CustomServerPlatform, cls is its ExternalTransactionController class
if(originalServerPlatform.getClass().equals(CustomServerPlatform.class)) {
// both originalServerPlatform and the new serverPlatform are Custom,
// just set externalTransactionController class (if necessary) into
// originalServerPlatform
CustomServerPlatform originalCustomServerPlatform = (CustomServerPlatform)originalServerPlatform;
if(cls.equals(originalCustomServerPlatform.getExternalTransactionControllerClass())) {
// externalTransactionController classes are the same - nothing to do
} else {
originalCustomServerPlatform.setExternalTransactionControllerClass(cls);
}
} else {
// originalServerPlatform is not custom - need a new one.
CustomServerPlatform customServerPlatform = new CustomServerPlatform(session);
customServerPlatform.setExternalTransactionControllerClass(cls);
serverPlatform = customServerPlatform;
}
} else {
throw EntityManagerSetupException.failedToInstantiateServerPlatform(serverPlatformClassName, PersistenceUnitProperties.TARGET_SERVER, ex);
}
}
if (serverPlatform != null){
session.setServerPlatform(serverPlatform);
return true;
}
return false;
}
/**
* Update loggers and settings for the singleton logger and the session logger.
* @param persistenceProperties the properties map
* @param serverPlatformChanged the boolean that denotes a serverPlatform change in the session.
* @param sessionNameChanged the boolean that denotes a sessionNameChanged change in the session.
*/
protected void updateLoggers(Map persistenceProperties, boolean serverPlatformChanged, boolean sessionNameChanged, ClassLoader loader) {
// Logger(SessionLog type) can be specified by the logger property or ServerPlatform.getServerLog().
// The logger property has a higher priority to ServerPlatform.getServerLog().
String loggerClassName = PropertiesHandler.getPropertyValueLogDebug(PersistenceUnitProperties.LOGGING_LOGGER, persistenceProperties, session);
// The sessionLog instance should be different from the singletonLog because they have
// different state.
SessionLog singletonLog = null, sessionLog = null;
if (loggerClassName != null) {
SessionLog currentLog = session.getSessionLog();
if(loggerClassName.equals(LoggerType.ServerLogger)){
ServerPlatform serverPlatform = session.getServerPlatform();
singletonLog = serverPlatform.getServerLog();
sessionLog = serverPlatform.getServerLog();
} else if (!currentLog.getClass().getName().equals(loggerClassName)) {
// Logger class was specified and it's not what's already there.
Class sessionLogClass = findClassForProperty(loggerClassName, PersistenceUnitProperties.LOGGING_LOGGER, loader);
try {
singletonLog = (SessionLog)sessionLogClass.newInstance();
sessionLog = (SessionLog)sessionLogClass.newInstance();
} catch (Exception ex) {
throw EntityManagerSetupException.failedToInstantiateLogger(loggerClassName, PersistenceUnitProperties.LOGGING_LOGGER, ex);
}
}
} else if (serverPlatformChanged) {
ServerPlatform serverPlatform = session.getServerPlatform();
singletonLog = serverPlatform.getServerLog();
sessionLog = serverPlatform.getServerLog();
}
// Don't change default loggers if the new loggers have not been created.
if (singletonLog != null && sessionLog != null) {
AbstractSessionLog.setLog(singletonLog);
session.setSessionLog(sessionLog);
} else if (sessionNameChanged) {
// In JavaLog this will result in logger name changes,
// but won't affect DefaultSessionLog.
// Note, that the session hasn't change, only its name.
session.getSessionLog().setSession(session);
}
// Bug5389828. Update the logging settings for the singleton logger.
initOrUpdateLogging(persistenceProperties, AbstractSessionLog.getLog());
initOrUpdateLogging(persistenceProperties, session.getSessionLog());
// Set logging file.
String loggingFileString = (String)persistenceProperties.get(PersistenceUnitProperties.LOGGING_FILE);
if (loggingFileString != null) {
if (!loggingFileString.trim().equals("")) {
try {
if (sessionLog!=null){
if (sessionLog instanceof AbstractSessionLog) {
FileOutputStream fos = new FileOutputStream(loggingFileString);
((AbstractSessionLog)sessionLog).setWriter(fos);
} else {
FileWriter fw = new FileWriter(loggingFileString);
sessionLog.setWriter(fw);
}
}
} catch (IOException e) {
session.handleException(ValidationException.invalidLoggingFile(loggingFileString,e));
}
} else {
session.handleException(ValidationException.invalidLoggingFile());
}
}
}
/**
* Check for the PROFILER persistence or system property and set the Session's profiler.
* This can also set the QueryMonitor.
*/
protected void updateProfiler(Map persistenceProperties,ClassLoader loader) {
// This must use config property as the profiler is not in the PropertiesHandler and requires
// supporting generic profiler classes.
String newProfilerClassName = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.PROFILER, persistenceProperties, session);
if (newProfilerClassName == null) {
((ServerPlatformBase)session.getServerPlatform()).configureProfiler(session);
} else {
if (newProfilerClassName.equals(ProfilerType.NoProfiler)) {
session.setProfiler(null);
return;
}
if (newProfilerClassName.equals(ProfilerType.QueryMonitor)) {
session.setProfiler(null);
QueryMonitor.shouldMonitor=true;
return;
}
if (newProfilerClassName.equals(ProfilerType.PerformanceProfiler)) {
session.setProfiler(new PerformanceProfiler());
return;
}
String originalProfilerClassNamer = null;
if (session.getProfiler() != null) {
originalProfilerClassNamer = session.getProfiler().getClass().getName();
if (originalProfilerClassNamer.equals(newProfilerClassName)) {
return;
}
}
// New profiler - create the new instance and set it.
try {
Class newProfilerClass = findClassForProperty(newProfilerClassName, PersistenceUnitProperties.PROFILER, loader);
SessionProfiler sessionProfiler = (SessionProfiler)buildObjectForClass(newProfilerClass, SessionProfiler.class);
if (sessionProfiler != null) {
session.setProfiler(sessionProfiler);
} else {
session.handleException(ValidationException.invalidProfilerClass(newProfilerClassName));
}
} catch (IllegalAccessException e) {
session.handleException(ValidationException.cannotInstantiateProfilerClass(newProfilerClassName,e));
} catch (PrivilegedActionException e) {
session.handleException(ValidationException.cannotInstantiateProfilerClass(newProfilerClassName,e));
} catch (InstantiationException e) {
session.handleException(ValidationException.cannotInstantiateProfilerClass(newProfilerClassName,e));
}
}
}
protected static Class findClass(String className, ClassLoader loader) throws ClassNotFoundException, PrivilegedActionException {
if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()){
return (Class)AccessController.doPrivileged(new PrivilegedClassForName(className, true, loader));
} else {
return org.eclipse.persistence.internal.security.PrivilegedAccessHelper.getClassForName(className, true, loader);
}
}
protected static Class findClassForProperty(String className, String propertyName, ClassLoader loader) {
try {
return findClass(className, loader);
} catch (PrivilegedActionException exception1) {
throw EntityManagerSetupException.classNotFoundForProperty(className, propertyName, exception1.getException());
} catch (ClassNotFoundException exception2) {
throw EntityManagerSetupException.classNotFoundForProperty(className, propertyName, exception2);
}
}
/**
* This method will be used to validate the specified class and return it's instance.
*/
protected static Object buildObjectForClass(Class clazz, Class mustBeImplementedInterface) throws IllegalAccessException, PrivilegedActionException,InstantiationException {
if(clazz!=null && Helper.classImplementsInterface(clazz,mustBeImplementedInterface)){
if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()){
return AccessController.doPrivileged(new PrivilegedNewInstanceFromClass(clazz));
} else {
return PrivilegedAccessHelper.newInstanceFromClass(clazz);
}
} else {
return null;
}
}
protected void updateDescriptorCacheSettings(Map m, ClassLoader loader) {
Map typeMap = PropertiesHandler.getPrefixValuesLogDebug(PersistenceUnitProperties.CACHE_TYPE_, m, session);
Map sizeMap = PropertiesHandler.getPrefixValuesLogDebug(PersistenceUnitProperties.CACHE_SIZE_, m, session);
Map sharedMap = PropertiesHandler.getPrefixValuesLogDebug(PersistenceUnitProperties.CACHE_SHARED_, m, session);
if(typeMap.isEmpty() && sizeMap.isEmpty() && sharedMap.isEmpty()) {
return;
}
boolean hasDefault = false;
String defaultTypeName = (String)typeMap.remove(PersistenceUnitProperties.DEFAULT);
Class defaultType = null;
if(defaultTypeName != null) {
defaultType = findClassForProperty(defaultTypeName, PersistenceUnitProperties.CACHE_TYPE_DEFAULT, loader);
hasDefault = true;
}
String defaultSizeString = (String)sizeMap.remove(PersistenceUnitProperties.DEFAULT);
Integer defaultSize = null;
if(defaultSizeString != null) {
defaultSize = Integer.parseInt(defaultSizeString);
hasDefault = true;
}
String defaultSharedString = (String)sharedMap.remove(PersistenceUnitProperties.DEFAULT);
Boolean defaultShared = null;
if(defaultSharedString != null) {
defaultShared = Boolean.parseBoolean(defaultSharedString);
hasDefault = true;
}
Iterator it = session.getDescriptors().values().iterator();
while (it.hasNext() && (hasDefault || !typeMap.isEmpty() || !sizeMap.isEmpty() || !sharedMap.isEmpty())) {
ClassDescriptor descriptor = (ClassDescriptor)it.next();
if(descriptor.isAggregateDescriptor() || descriptor.isAggregateCollectionDescriptor()) {
continue;
}
String entityName = descriptor.getAlias();
String className = descriptor.getJavaClass().getName();
String name;
Class type = defaultType;
name = entityName;
String typeName = (String)typeMap.remove(name);
if(typeName == null) {
name = className;
typeName = (String)typeMap.remove(name);
}
if(typeName != null) {
type = findClassForProperty(typeName, PersistenceUnitProperties.CACHE_TYPE_ + name, loader);
}
if(type != null) {
descriptor.setIdentityMapClass(type);
}
Integer size = defaultSize;
name = entityName;
String sizeString = (String)sizeMap.remove(name);
if(sizeString == null) {
name = className;
sizeString = (String)sizeMap.remove(name);
}
if(sizeString != null) {
size = Integer.parseInt(sizeString);
}
if(size != null) {
descriptor.setIdentityMapSize(size.intValue());
}
Boolean shared = defaultShared;
name = entityName;
String sharedString = (String)sharedMap.remove(name);
if(sharedString == null) {
name = className;
sharedString = (String)sharedMap.remove(name);
}
if(sharedString != null) {
shared = Boolean.parseBoolean(sharedString);
}
if(shared != null) {
descriptor.setIsIsolated(!shared.booleanValue());
}
}
}
protected void updateConnectionPolicy(Map m) {
String isLazyString = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.EXCLUSIVE_CONNECTION_IS_LAZY, m, session);
if(isLazyString != null) {
session.getDefaultConnectionPolicy().setIsLazy(Boolean.parseBoolean(isLazyString));
}
ConnectionPolicy.ExclusiveMode exclusiveMode = getConnectionPolicyExclusiveModeFromProperties(m, session, true);
if(exclusiveMode != null) {
session.getDefaultConnectionPolicy().setExclusiveMode(exclusiveMode);
}
}
public static ConnectionPolicy.ExclusiveMode getConnectionPolicyExclusiveModeFromProperties(Map m, AbstractSession abstractSession, boolean useSystemAsDefault) {
String exclusiveConnectionModeString = PropertiesHandler.getPropertyValueLogDebug(PersistenceUnitProperties.EXCLUSIVE_CONNECTION_MODE, m, abstractSession, useSystemAsDefault);
if(exclusiveConnectionModeString != null) {
if(exclusiveConnectionModeString == ExclusiveConnectionMode.Isolated) {
return ConnectionPolicy.ExclusiveMode.Isolated;
} else if(exclusiveConnectionModeString == ExclusiveConnectionMode.Always) {
return ConnectionPolicy.ExclusiveMode.Always;
} else {
return ConnectionPolicy.ExclusiveMode.Transactional;
}
} else {
return null;
}
}
/**
* Perform any steps necessary prior to actual deployment. This includes any steps in the session
* creation that do not require the real loaded domain classes.
*
* The first call to this method caches persistenceUnitInfo which is reused in the following calls.
*
* Note that in JSE case factoryCount is NOT incremented on the very first call
* (by JavaSECMPInitializer.callPredeploy, typically in preMain).
* That provides 1 to 1 correspondence between factoryCount and the number of open factories.
*
* In case factoryCount > 0 the method just increments factoryCount.
* factory == 0 triggers creation of a new session.
*
* This method and undeploy - the only methods altering factoryCount - should be synchronized.
*
* @return A transformer (which may be null) that should be plugged into the proper
* classloader to allow classes to be transformed as they get loaded.
* @see #deploy(ClassLoader, Map)
*/
public synchronized ClassTransformer predeploy(PersistenceUnitInfo info, Map extendedProperties) {
ClassLoader privateClassLoader = null;
if (state == STATE_DEPLOY_FAILED) {
throw new PersistenceException(EntityManagerSetupException.cannotPredeploy(persistenceUnitInfo.getPersistenceUnitName(), state));
}
if (state == STATE_PREDEPLOYED || state == STATE_DEPLOYED) {
session.log(SessionLog.FINEST, SessionLog.PROPERTIES, "predeploy_begin", new Object[]{getPersistenceUnitInfo().getPersistenceUnitName(), state, factoryCount});
factoryCount++;
session.log(SessionLog.FINEST, SessionLog.PROPERTIES, "predeploy_end", new Object[]{getPersistenceUnitInfo().getPersistenceUnitName(), state, factoryCount});
return null;
} else if(state == STATE_INITIAL || state == STATE_UNDEPLOYED) {
persistenceUnitInfo = info;
}
// state is INITIAL, PREDEPLOY_FAILED or UNDEPLOYED
try {
predeployProperties = mergeMaps(extendedProperties, persistenceUnitInfo.getProperties());
// Translate old properties.
// This should be done before using properties (i.e. ServerPlatform).
translateOldProperties(predeployProperties, null);
String sessionsXMLStr = (String)predeployProperties.get(PersistenceUnitProperties.SESSIONS_XML);
String sessionNameStr = (String)predeployProperties.get(PersistenceUnitProperties.SESSION_NAME);
if (sessionsXMLStr != null) {
isSessionLoadedFromSessionsXML = true;
}
// Create server session (it needs to be done before initializing ServerPlatform and logging).
// If a sessions-xml is used this will get replaced later, but is required for logging.
session = new ServerSession(new Project(new DatabaseLogin()));
// ServerSession name and ServerPlatform must be set prior to setting the loggers.
setServerSessionName(predeployProperties);
ClassLoader realClassLoader = persistenceUnitInfo.getClassLoader();
updateServerPlatform(predeployProperties, realClassLoader);
// Update loggers and settings for the singleton logger and the session logger.
updateLoggers(predeployProperties, true, false, realClassLoader);
// If it's SE case and the pu has been undeployed weaving again here is impossible:
// the classes were loaded already. Therefore using temporaryClassLoader is no longer required.
// Moreover, it causes problem in case the same factory is opened and closed many times:
// eventually it causes "java.lang.OutOfMemoryError: PermGen space".
// It seems that tempLoaders are not garbage collected, therefore each predeploy would add new
// classes to Permanent Generation heap.
// Therefore this doesn't really fix the problem but rather makes it less severe: in case of
// the factory opened / closed 20 times only one temp. class loader may be left behind - not 20.
// Another workaround would be increasing Permanent Generation Heap size by adding VM argument -XX:MaxPermSize=256m.
if(!this.isInContainerMode && state==STATE_UNDEPLOYED) {
privateClassLoader = realClassLoader;
} else {
// Get the temporary classLoader based on the platform
JPAClassLoaderHolder privateClassLoaderHolder = session.getServerPlatform().getNewTempClassLoader(info);
privateClassLoader = privateClassLoaderHolder.getClassLoader();
// Bug 229634: If we switched to using the non-temporary classLoader then disable weaving
if(!privateClassLoaderHolder.isTempClassLoader()) {
// Disable dynamic weaving for the duration of this predeploy()
enableWeaving = Boolean.FALSE;
}
}
//Update performance profiler
updateProfiler(predeployProperties,realClassLoader);
// Cannot start logging until session and log and initialized, so log start of predeploy here.
session.log(SessionLog.FINEST, SessionLog.PROPERTIES, "predeploy_begin", new Object[]{getPersistenceUnitInfo().getPersistenceUnitName(), state, factoryCount});
if (isSessionLoadedFromSessionsXML) {
// Loading session from sessions-xml.
session.log(SessionLog.FINEST, SessionLog.PROPERTIES, "loading_session_xml", sessionsXMLStr, sessionNameStr);
if (sessionNameStr == null) {
throw new PersistenceException(EntityManagerSetupException.sessionNameNeedBeSpecified(info.getPersistenceUnitName(), sessionsXMLStr));
}
XMLSessionConfigLoader xmlLoader = new XMLSessionConfigLoader(sessionsXMLStr);
// Do not register the session with the SessionManager at this point, create temporary session using a local SessionManager and private class loader.
// This allows for the project to be accessed without loading any of the classes to allow weaving.
Session tempSession = new SessionManager().getSession(xmlLoader, sessionNameStr, privateClassLoader, false, false);
// Load path of sessions-xml resource before throwing error so user knows which sessions-xml file was found (may be multiple).
session.log(SessionLog.FINEST, SessionLog.PROPERTIES, "sessions_xml_path_where_session_load_from", xmlLoader.getSessionName(), xmlLoader.getResourcePath());
if (tempSession == null) {
throw new PersistenceException(ValidationException.noSessionFound(sessionNameStr, sessionsXMLStr));
}
if (tempSession.isServerSession()) {
session = (ServerSession) tempSession;
} else {
throw new PersistenceException(EntityManagerSetupException.sessionLoadedFromSessionsXMLMustBeServerSession(info.getPersistenceUnitName(), (String)predeployProperties.get(PersistenceUnitProperties.SESSIONS_XML), tempSession));
}
// Must now reset logging and server-platform on the loaded session.
// ServerSession name and ServerPlatform must be set prior to setting the loggers.
setServerSessionName(predeployProperties);
updateServerPlatform(predeployProperties, privateClassLoader);
// Update loggers and settings for the singleton logger and the session logger.
updateLoggers(predeployProperties, true, false, privateClassLoader);
}
warnOldProperties(predeployProperties, session);
session.getPlatform().setConversionManager(new JPAConversionManager());
PersistenceUnitTransactionType transactionType=null;
//bug 5867753: find and override the transaction type
String transTypeString = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.TRANSACTION_TYPE, predeployProperties, session);
if ( transTypeString != null ){
transactionType=PersistenceUnitTransactionType.valueOf(transTypeString);
} else if (persistenceUnitInfo!=null){
transactionType=persistenceUnitInfo.getTransactionType();
}
if (!isValidationOnly(predeployProperties, false) && persistenceUnitInfo != null && transactionType == PersistenceUnitTransactionType.JTA) {
if (predeployProperties.get(PersistenceUnitProperties.JTA_DATASOURCE) == null && persistenceUnitInfo.getJtaDataSource() == null) {
throw new PersistenceException(EntityManagerSetupException.jtaPersistenceUnitInfoMissingJtaDataSource(persistenceUnitInfo.getPersistenceUnitName()));
}
}
// this flag is used to disable work done as a result of the LAZY hint on OneToOne and ManyToOne mappings
if((state == STATE_INITIAL || state == STATE_UNDEPLOYED)) {
if(null == enableWeaving) {
enableWeaving = Boolean.TRUE;
}
isWeavingStatic = false;
String weaving = getConfigPropertyAsString(PersistenceUnitProperties.WEAVING);
if (weaving != null && weaving.equalsIgnoreCase("false")) {
enableWeaving = Boolean.FALSE;
}else if (weaving != null && weaving.equalsIgnoreCase("static")) {
isWeavingStatic = true;
}
}
boolean throwExceptionOnFail = "true".equalsIgnoreCase(
EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.THROW_EXCEPTIONS, predeployProperties, "true", session));
ClassTransformer transformer = null;
boolean weaveChangeTracking = false;
boolean weaveLazy = false;
boolean weaveEager = false;
boolean weaveFetchGroups = false;
boolean weaveInternal = false;
if (enableWeaving) {
weaveChangeTracking = "true".equalsIgnoreCase(EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.WEAVING_CHANGE_TRACKING, predeployProperties, "true", session));
weaveLazy = "true".equalsIgnoreCase(EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.WEAVING_LAZY, predeployProperties, "true", session));
weaveEager = "true".equalsIgnoreCase(EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.WEAVING_EAGER, predeployProperties, "false", session));
weaveFetchGroups = "true".equalsIgnoreCase(EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.WEAVING_FETCHGROUPS, predeployProperties, "true", session));
weaveInternal = "true".equalsIgnoreCase(EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.WEAVING_INTERNAL, predeployProperties, "true", session));
}
if (!isSessionLoadedFromSessionsXML ) {
// Create an instance of MetadataProcessor for specified persistence unit info
processor = new MetadataProcessor(persistenceUnitInfo, session, privateClassLoader, enableWeaving, weaveEager);
// Process the Object/relational metadata from XML and annotations.
PersistenceUnitProcessor.processORMetadata(processor, throwExceptionOnFail);
if (session.getIntegrityChecker().hasErrors()){
session.handleException(new IntegrityException(session.getIntegrityChecker()));
}
// The transformer is capable of altering domain classes to handle a LAZY hint for OneToOne mappings. It will only
// be returned if we we are mean to process these mappings
if (enableWeaving) {
// build a list of entities the persistence unit represented by this EntityManagerSetupImpl will use
Collection entities = PersistenceUnitProcessor.buildEntityList(processor.getProject(), privateClassLoader);
transformer = TransformerFactory.createTransformerAndModifyProject(session, entities, privateClassLoader, weaveLazy, weaveChangeTracking, weaveFetchGroups, weaveInternal);
}
} else {
// The transformer is capable of altering domain classes to handle a LAZY hint for OneToOne mappings. It will only
// be returned if we we are meant to process these mappings.
if (enableWeaving) {
// If deploying from a sessions-xml it is still desirable to allow the classes to be weaved.
// build a list of entities the persistence unit represented by this EntityManagerSetupImpl will use
Collection persistenceClasses = new ArrayList(session.getProject().getDescriptors().keySet());
transformer = TransformerFactory.createTransformerAndModifyProject(session, persistenceClasses, privateClassLoader, weaveLazy, weaveChangeTracking, weaveFetchGroups, weaveInternal);
}
}
// factoryCount is not incremented only in case of a first call to preDeploy
// in non-container mode: this call is not associated with a factory
// but rather done by JavaSECMPInitializer.callPredeploy (typically in preMain).
if((state != STATE_INITIAL && state != STATE_UNDEPLOYED) || this.isInContainerMode()) {
factoryCount++;
}
state = STATE_PREDEPLOYED;
session.log(SessionLog.FINEST, SessionLog.PROPERTIES, "predeploy_end", new Object[]{getPersistenceUnitInfo().getPersistenceUnitName(), state, factoryCount});
//gf3146: if static weaving is used, we should not return a transformer. Transformer should still be created though as it modifies descriptors
if (isWeavingStatic) {
return null;
} else {
return transformer;
}
} catch (RuntimeException ex) {
state = STATE_PREDEPLOY_FAILED;
session = null;
throw new PersistenceException(EntityManagerSetupException.predeployFailed(persistenceUnitInfo.getPersistenceUnitName(), ex));
}
}
/**
* Check the provided map for an object with the given key. If that object is not available, check the
* System properties. If it is not available from either location, return the default value.
*/
public String getConfigPropertyAsString(String propertyKey, String defaultValue){
return getConfigPropertyAsStringLogDebug(propertyKey, predeployProperties, defaultValue, session);
}
public String getConfigPropertyAsString(String propertyKey){
return getConfigPropertyAsStringLogDebug(propertyKey, predeployProperties, session);
}
/**
* Return the name of the session this SetupImpl is building. The session name is only known at deploy
* time and if this method is called prior to that, this method will return null.
*/
public String getDeployedSessionName(){
return session != null ? session.getName() : null;
}
public PersistenceUnitInfo getPersistenceUnitInfo(){
return persistenceUnitInfo;
}
public boolean isValidationOnly(Map m) {
return isValidationOnly(m, true);
}
protected boolean isValidationOnly(Map m, boolean shouldMergeMap) {
if (shouldMergeMap) {
m = mergeWithExistingMap(m);
}
String validationOnlyString = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.VALIDATION_ONLY_PROPERTY, m, session);
if (validationOnlyString != null) {
return Boolean.parseBoolean(validationOnlyString);
} else {
return false;
}
}
public boolean shouldGetSessionOnCreateFactory(Map m) {
m = mergeWithExistingMap(m);
return isValidationOnly(m, false);
}
protected Map mergeWithExistingMap(Map m) {
if(predeployProperties != null) {
return mergeMaps(m, predeployProperties);
} else if(persistenceUnitInfo != null) {
return mergeMaps(m, persistenceUnitInfo.getProperties());
} else {
return m;
}
}
public boolean isInContainerMode(){
return isInContainerMode;
}
/**
* Override the default login creation method.
* If persistenceInfo is available, use the information from it to setup the login
* and possibly to set readConnectionPool.
*/
protected void updateLogins(Map m){
DatasourceLogin login = session.getLogin();
// Note: This call does not checked the stored persistenceUnitInfo or extended properties because
// the map passed into this method should represent the full set of properties we expect to process
String user = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_USER, m, session);
String password = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_PASSWORD, m, session);
if(user != null) {
login.setUserName(user);
}
if (password != null) {
login.setPassword(securableObjectHolder.getSecurableObject().decryptPassword(password));
}
String eclipselinkPlatform = PropertiesHandler.getPropertyValueLogDebug(PersistenceUnitProperties.TARGET_DATABASE, m, session);
if (eclipselinkPlatform != null) {
login.setPlatformClassName(eclipselinkPlatform, persistenceUnitInfo.getClassLoader());
}
PersistenceUnitTransactionType transactionType = persistenceUnitInfo.getTransactionType();
//bug 5867753: find and override the transaction type using properties
String transTypeString = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.TRANSACTION_TYPE, m, session);
if (transTypeString != null) {
transactionType = PersistenceUnitTransactionType.valueOf(transTypeString);
}
//find the jta datasource
javax.sql.DataSource jtaDatasource = getDatasourceFromProperties(m, PersistenceUnitProperties.JTA_DATASOURCE, persistenceUnitInfo.getJtaDataSource());
//find the non jta datasource
javax.sql.DataSource nonjtaDatasource = getDatasourceFromProperties(m, PersistenceUnitProperties.NON_JTA_DATASOURCE, persistenceUnitInfo.getNonJtaDataSource());
if (isValidationOnly(m, false) && transactionType == PersistenceUnitTransactionType.JTA && jtaDatasource == null) {
updateLoginDefaultConnector(login, m);
return;
}
login.setUsesExternalTransactionController(transactionType == PersistenceUnitTransactionType.JTA);
javax.sql.DataSource mainDatasource = null;
javax.sql.DataSource readDatasource = null;
if (login.shouldUseExternalTransactionController()) {
// JtaDataSource is guaranteed to be non null - otherwise exception would've been thrown earlier
mainDatasource = jtaDatasource;
// only define readDatasource if there is jta mainDatasource
readDatasource = nonjtaDatasource;
} else {
// JtaDataSource will be ignored because transactionType is RESOURCE_LOCAL
if (jtaDatasource != null) {
session.log(SessionLog.WARNING, SessionLog.TRANSACTION, "resource_local_persistence_init_info_ignores_jta_data_source", persistenceUnitInfo.getPersistenceUnitName());
}
if (nonjtaDatasource != null) {
mainDatasource = nonjtaDatasource;
} else {
updateLoginDefaultConnector(login, m);
return;
}
}
// mainDatasource is guaranteed to be non null
if (!(login.getConnector() instanceof JNDIConnector)) {
JNDIConnector jndiConnector;
if (mainDatasource instanceof DataSourceImpl) {
//Bug5209363 Pass in the datasource name instead of the dummy datasource
jndiConnector = new JNDIConnector(((DataSourceImpl)mainDatasource).getName());
} else {
jndiConnector = new JNDIConnector(mainDatasource);
}
login.setConnector(jndiConnector);
login.setUsesExternalConnectionPooling(true);
}
// set readLogin
if(readDatasource != null) {
DatasourceLogin readLogin = (DatasourceLogin)login.clone();
readLogin.dontUseExternalTransactionController();
JNDIConnector jndiConnector;
if (readDatasource instanceof DataSourceImpl) {
//Bug5209363 Pass in the datasource name instead of the dummy datasource
jndiConnector = new JNDIConnector(((DataSourceImpl)readDatasource).getName());
} else {
jndiConnector = new JNDIConnector(readDatasource);
}
readLogin.setConnector(jndiConnector);
session.setReadConnectionPool(readLogin);
}
}
/**
* This is used to return either the defaultDatasource or, if one exists, a datasource
* defined under the property from the Map m. This method will build a DataSourceImpl
* object to hold the url if the property in Map m defines a string instead of a datasource.
*/
protected javax.sql.DataSource getDatasourceFromProperties(Map m, String property, javax.sql.DataSource defaultDataSource){
Object datasource = getConfigPropertyLogDebug(property, m, session);
if ( datasource == null ){
return defaultDataSource;
}
if ( datasource instanceof String){
// Create a dummy DataSource that will throw an exception on access
return new DataSourceImpl((String)datasource, null, null, null);
}
if ( !(datasource instanceof javax.sql.DataSource) ){
//A warning should be enough. Though an error might be better, the properties passed in could contain anything
session.log(SessionLog.WARNING, SessionLog.PROPERTIES, "invalid_datasource_property_value", property, datasource);
return defaultDataSource;
}
return (javax.sql.DataSource)datasource;
}
/**
* In cases where there is no data source, we will use properties to configure the login for
* our session. This method gets those properties and sets them on the login.
*/
protected void updateLoginDefaultConnector(DatasourceLogin login, Map m){
//Login info might be already set with sessions.xml and could be overrided by session customizer after this
//If login has default connector then JDBC properties update(override) the login info
if ((login.getConnector() instanceof DefaultConnector)) {
DatabaseLogin dbLogin = (DatabaseLogin)login;
// Note: This call does not checked the stored persistenceUnitInfo or extended properties because
// the map passed into this method should represent the full set of properties we expect to process
String jdbcDriver = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_DRIVER, m, session);
String connectionString = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_URL, m, session);
if(connectionString != null) {
dbLogin.setConnectionString(connectionString);
}
if(jdbcDriver != null) {
dbLogin.setDriverClassName(jdbcDriver);
}
}
}
protected void updatePools(Map m) {
// Sizes are irrelevant for external connection pool
if(!session.getDefaultConnectionPool().getLogin().shouldUseExternalConnectionPooling()) {
String strWriteMin = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_WRITE_CONNECTIONS_MIN, m, session);
if(strWriteMin != null) {
session.getDefaultConnectionPool().setMinNumberOfConnections(Integer.parseInt(strWriteMin));
}
String strWriteMax = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_WRITE_CONNECTIONS_MAX, m, session);
if(strWriteMax != null) {
session.getDefaultConnectionPool().setMaxNumberOfConnections(Integer.parseInt(strWriteMax));
}
}
// Sizes and shared option are irrelevant for external connection pool
if (!session.getReadConnectionPool().getLogin().shouldUseExternalConnectionPooling()) {
String strReadMin = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_READ_CONNECTIONS_MIN, m, session);
if(strReadMin != null) {
session.getReadConnectionPool().setMinNumberOfConnections(Integer.parseInt(strReadMin));
}
String strReadMax = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_READ_CONNECTIONS_MAX, m, session);
if (strReadMax != null) {
session.getReadConnectionPool().setMaxNumberOfConnections(Integer.parseInt(strReadMax));
}
String strShouldUseShared = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_READ_CONNECTIONS_SHARED, m,session);
if(strShouldUseShared != null) {
boolean shouldUseShared = Boolean.parseBoolean(strShouldUseShared);
boolean sessionUsesShared = session.getReadConnectionPool() instanceof ReadConnectionPool;
if(shouldUseShared != sessionUsesShared) {
Login readLogin = session.getReadConnectionPool().getLogin();
int nReadMin = session.getReadConnectionPool().getMinNumberOfConnections();
int nReadMax = session.getReadConnectionPool().getMaxNumberOfConnections();
if(shouldUseShared) {
session.useReadConnectionPool(nReadMin, nReadMax);
} else {
session.useExclusiveReadConnectionPool(nReadMin, nReadMax);
}
// keep original readLogin
session.getReadConnectionPool().setLogin(readLogin);
}
}
}
}
/**
* Normally when a property is missing nothing should be applied to the session.
* However there are several session attributes that defaulted in EJB3 to the values
* different from EclipseLink defaults.
* This function applies defaults for such properties and registers the session.
* All other session-related properties are applied in updateServerSession.
* Note that updateServerSession may be called several times on the same session
* (before login), but initServerSession is called just once - before the first call
* to updateServerSession.
* @param properties the persistence unit properties.
*/
protected void initServerSession(Map properties) {
assignCMP3Policy();
// Register session that has been created earlier.
addSessionToGlobalSessionManager();
}
/**
* Set ServerSession name but do not register the session.
* The session registration should be done in sync
* with increment of the deployment counter, as otherwise the
* undeploy will not behave correctly in case of a more
* than one predeploy request for the same session name.
* @param m the combined properties map.
*/
protected void setServerSessionName(Map m) {
// use default session name if none is provided
String name = EntityManagerFactoryProvider.getConfigPropertyAsString(PersistenceUnitProperties.SESSION_NAME, m);
if(name == null) {
if (persistenceUnitInfo.getPersistenceUnitRootUrl() != null){
name = persistenceUnitInfo.getPersistenceUnitRootUrl().toString() + "-" + persistenceUnitInfo.getPersistenceUnitName();
} else {
name = persistenceUnitInfo.getPersistenceUnitName();
}
}
session.setName(name);
}
/**
* Make any changes to our ServerSession that can be made after it is created.
*/
protected void updateServerSession(Map m, ClassLoader loader) {
if (session == null || session.isConnected()) {
return;
}
// In deploy Session name and ServerPlatform could've changed which will affect the loggers.
boolean serverPlatformChanged = updateServerPlatform(m, loader);
boolean sessionNameChanged = updateSessionName(m);
updateLoggers(m, serverPlatformChanged, sessionNameChanged, loader);
updateProfiler(m,loader);
String shouldBindString = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.JDBC_BIND_PARAMETERS, m, session);
if (shouldBindString != null) {
session.getPlatform().setShouldBindAllParameters(Boolean.parseBoolean(shouldBindString));
}
updateLogins(m);
if (!session.getLogin().shouldUseExternalTransactionController()) {
session.getServerPlatform().disableJTA();
}
setSessionEventListener(m, loader);
setExceptionHandler(m, loader);
updatePools(m);
if (!isSessionLoadedFromSessionsXML) {
updateDescriptorCacheSettings(m, loader);
}
updateConnectionPolicy(m);
updateBatchWritingSetting(m);
updateNativeSQLSetting(m);
updateCacheStatementSettings(m);
updateTemporalMutableSetting(m);
// Customizers should be processed last
processDescriptorCustomizers(m, loader);
processSessionCustomizer(m, loader);
setDescriptorNamedQueries(m);
}
/**
* This sets the isInContainerMode flag.
* "true" indicates container case, "false" - SE.
*/
public void setIsInContainerMode(boolean isInContainerMode) {
this.isInContainerMode = isInContainerMode;
}
protected void processSessionCustomizer(Map m, ClassLoader loader) {
String sessionCustomizerClassName = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.SESSION_CUSTOMIZER, m, session);
if (sessionCustomizerClassName == null) {
return;
}
Class sessionCustomizerClass = findClassForProperty(sessionCustomizerClassName, PersistenceUnitProperties.SESSION_CUSTOMIZER, loader);
SessionCustomizer sessionCustomizer;
try {
sessionCustomizer = (SessionCustomizer)sessionCustomizerClass.newInstance();
sessionCustomizer.customize(session);
} catch (Exception ex) {
throw EntityManagerSetupException.failedWhileProcessingProperty(PersistenceUnitProperties.SESSION_CUSTOMIZER, sessionCustomizerClassName, ex);
}
}
protected void initOrUpdateLogging(Map m, SessionLog log) {
String logLevelString = PropertiesHandler.getPropertyValueLogDebug(PersistenceUnitProperties.LOGGING_LEVEL, m, session);
if (logLevelString != null) {
log.setLevel(AbstractSessionLog.translateStringToLoggingLevel(logLevelString));
}
// category-specific logging level
Map categoryLogLevelMap = PropertiesHandler.getPrefixValuesLogDebug(PersistenceUnitProperties.CATEGORY_LOGGING_LEVEL_, m, session);
if(!categoryLogLevelMap.isEmpty()) {
Iterator it = categoryLogLevelMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String category = (String)entry.getKey();
String value = (String)entry.getValue();
log.setLevel(AbstractSessionLog.translateStringToLoggingLevel(value), category);
}
}
String tsString = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.LOGGING_TIMESTAMP, m, session);
if (tsString != null) {
log.setShouldPrintDate(Boolean.parseBoolean(tsString));
}
String threadString = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.LOGGING_THREAD, m, session);
if (threadString != null) {
log.setShouldPrintThread(Boolean.parseBoolean(threadString));
}
String sessionString = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.LOGGING_SESSION, m, session);
if (sessionString != null) {
log.setShouldPrintSession(Boolean.parseBoolean(sessionString));
}
String exString = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.LOGGING_EXCEPTIONS, m, session);
if (exString != null) {
log.setShouldLogExceptionStackTrace(Boolean.parseBoolean(exString));
}
}
/**
* Updates server session name if changed.
* @return true if the name has changed.
*/
protected boolean updateSessionName(Map m) {
String newName = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.SESSION_NAME, m, session);
if(newName == null || newName.equals(session.getName())) {
return false;
}
removeSessionFromGlobalSessionManager();
session.setName(newName);
addSessionToGlobalSessionManager();
return true;
}
protected void processDescriptorCustomizers(Map m, ClassLoader loader) {
Map customizerMap = PropertiesHandler.getPrefixValuesLogDebug(PersistenceUnitProperties.DESCRIPTOR_CUSTOMIZER_, m, session);
if (customizerMap.isEmpty()) {
return;
}
Iterator it = customizerMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String name = (String)entry.getKey();
ClassDescriptor descriptor = session.getDescriptorForAlias(name);
if (descriptor == null) {
try {
Class javaClass = findClass(name, loader);
descriptor = session.getDescriptor(javaClass);
} catch (Exception ex) {
// Ignore exception
}
}
if (descriptor != null) {
String customizerClassName = (String)entry.getValue();
Class customizerClass = findClassForProperty(customizerClassName, PersistenceUnitProperties.DESCRIPTOR_CUSTOMIZER_ + name, loader);
try {
DescriptorCustomizer customizer = (DescriptorCustomizer)customizerClass.newInstance();
customizer.customize(descriptor);
} catch (Exception ex) {
throw EntityManagerSetupException.failedWhileProcessingProperty(PersistenceUnitProperties.DESCRIPTOR_CUSTOMIZER_ + name, customizerClassName, ex);
}
}
}
}
public boolean isInitial() {
return state == STATE_INITIAL;
}
public boolean isPredeployed() {
return state == STATE_PREDEPLOYED;
}
public boolean isDeployed() {
return state == STATE_DEPLOYED;
}
public boolean isUndeployed() {
return state == STATE_UNDEPLOYED;
}
public boolean isPredeployFailed() {
return state == STATE_PREDEPLOY_FAILED;
}
public boolean isDeployFailed() {
return state == STATE_DEPLOY_FAILED;
}
public int getFactoryCount() {
return factoryCount;
}
public boolean shouldRedeploy() {
return state == STATE_UNDEPLOYED || state == STATE_PREDEPLOY_FAILED;
}
/**
* Undeploy may be called several times, but only the call that decreases
* factoryCount to 0 disconnects the session and removes it from the session manager.
* This method and predeploy - the only methods altering factoryCount - should be synchronized.
* After undeploy call that turns factoryCount to 0:
* session==null;
* PREDEPLOYED, DEPLOYED and DEPLOYED_FAILED states change to UNDEPLOYED state.
*/
public synchronized void undeploy() {
if (state == STATE_INITIAL || state == STATE_PREDEPLOY_FAILED || state == STATE_UNDEPLOYED) {
// must already have factoryCount==0 and session==null
return;
}
// state is PREDEPLOYED, DEPLOYED or DEPLOY_FAILED
session.log(SessionLog.FINEST, SessionLog.PROPERTIES, "undeploy_begin", new Object[]{getPersistenceUnitInfo().getPersistenceUnitName(), state, factoryCount});
try {
factoryCount--;
if(factoryCount > 0) {
return;
}
state = STATE_UNDEPLOYED;
removeSessionFromGlobalSessionManager();
} finally {
session.log(SessionLog.FINEST, SessionLog.PROPERTIES, "undeploy_end", new Object[]{getPersistenceUnitInfo().getPersistenceUnitName(), state, factoryCount});
if(state == STATE_UNDEPLOYED) {
session = null;
}
}
}
/**
* Allow customized session event listener to be added into session.
* The method needs to be called in deploy stage.
*/
protected void setSessionEventListener(Map m, ClassLoader loader){
//Set event listener if it has been specified.
String sessionEventListenerClassName = EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.SESSION_EVENT_LISTENER_CLASS, m, session);
if(sessionEventListenerClassName!=null){
Class sessionEventListenerClass = findClassForProperty(sessionEventListenerClassName,PersistenceUnitProperties.SESSION_EVENT_LISTENER_CLASS, loader);
try {
SessionEventListener sessionEventListener = (SessionEventListener)buildObjectForClass(sessionEventListenerClass, SessionEventListener.class);
if(sessionEventListener!=null){
session.getEventManager().getListeners().add(sessionEventListener);
} else {
session.handleException(ValidationException.invalidSessionEventListenerClass(sessionEventListenerClassName));
}
} catch (IllegalAccessException e) {
session.handleException(ValidationException.cannotInstantiateSessionEventListenerClass(sessionEventListenerClassName,e));
} catch (PrivilegedActionException e) {
session.handleException(ValidationException.cannotInstantiateSessionEventListenerClass(sessionEventListenerClassName,e));
} catch (InstantiationException e) {
session.handleException(ValidationException.cannotInstantiateSessionEventListenerClass(sessionEventListenerClassName,e));
}
}
}
/**
* Allow customized exception handler to be added into session.
* The method needs to be called in deploy and pre-deploy stage.
*/
protected void setExceptionHandler(Map m, ClassLoader loader){
//Set exception handler if it was specified.
String exceptionHandlerClassName = EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.EXCEPTION_HANDLER_CLASS, m, session);
if(exceptionHandlerClassName!=null){
Class exceptionHandlerClass = findClassForProperty(exceptionHandlerClassName,PersistenceUnitProperties.EXCEPTION_HANDLER_CLASS, loader);
try {
ExceptionHandler exceptionHandler = (ExceptionHandler)buildObjectForClass(exceptionHandlerClass, ExceptionHandler.class);
if (exceptionHandler!=null){
session.setExceptionHandler(exceptionHandler);
} else {
session.handleException(ValidationException.invalidExceptionHandlerClass(exceptionHandlerClassName));
}
} catch (IllegalAccessException e) {
session.handleException(ValidationException.cannotInstantiateExceptionHandlerClass(exceptionHandlerClassName,e));
} catch (PrivilegedActionException e) {
session.handleException(ValidationException.cannotInstantiateExceptionHandlerClass(exceptionHandlerClassName,e));
} catch (InstantiationException e) {
session.handleException(ValidationException.cannotInstantiateExceptionHandlerClass(exceptionHandlerClassName,e));
}
}
}
/**
* Update batch writing setting.
* The method needs to be called in deploy stage.
*/
protected void updateBatchWritingSetting(Map persistenceProperties) {
String batchWritingSettingString = PropertiesHandler.getPropertyValueLogDebug(PersistenceUnitProperties.BATCH_WRITING, persistenceProperties, session);
if (batchWritingSettingString != null) {
session.getPlatform().setUsesBatchWriting(batchWritingSettingString != BatchWriting.None);
if (batchWritingSettingString == BatchWriting.JDBC) {
session.getPlatform().setUsesJDBCBatchWriting(true);
session.getPlatform().setUsesNativeBatchWriting(false);
} else if (batchWritingSettingString == BatchWriting.Buffered) {
session.getPlatform().setUsesJDBCBatchWriting(false);
session.getPlatform().setUsesNativeBatchWriting(false);
} else if (batchWritingSettingString == BatchWriting.OracleJDBC) {
session.getPlatform().setUsesNativeBatchWriting(true);
session.getPlatform().setUsesJDBCBatchWriting(true);
}
}
}
/**
* Enable or disable the capability of Native SQL function.
* The method needs to be called in deploy stage.
*/
protected void updateNativeSQLSetting(Map m){
//Set Native SQL flag if it was specified.
String nativeSQLString = EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.NATIVE_SQL, m, session);
if(nativeSQLString!=null){
if(nativeSQLString.equalsIgnoreCase("true") ){
session.getProject().getLogin().useNativeSQL();
}else if (nativeSQLString.equalsIgnoreCase("false")){
session.getProject().getLogin().dontUseNativeSQL();
}else{
session.handleException(ValidationException.invalidBooleanValueForSettingNativeSQL(nativeSQLString));
}
}
}
/**
* Enable or disable statements cached, update statements cache size.
* The method needs to be called in deploy stage.
*/
protected void updateCacheStatementSettings(Map m){
// Cache statements if flag was specified.
String statmentsNeedBeCached = EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.CACHE_STATEMENTS, m, session);
if (statmentsNeedBeCached!=null) {
if (statmentsNeedBeCached.equalsIgnoreCase("true")) {
if (session.getConnectionPools().size()>0){//And if connection pooling is configured,
session.getProject().getLogin().setShouldCacheAllStatements(true);
} else {
session.log(SessionLog.WARNING, SessionLog.PROPERTIES, "persistence_unit_ignores_statments_cache_setting", new Object[]{null});
}
} else if (statmentsNeedBeCached.equalsIgnoreCase("false")) {
session.getProject().getLogin().setShouldCacheAllStatements(false);
} else {
session.handleException(ValidationException.invalidBooleanValueForEnableStatmentsCached(statmentsNeedBeCached));
}
}
// Set statement cache size if specified.
String cacheStatementsSize = EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.CACHE_STATEMENTS_SIZE, m, session);
if (cacheStatementsSize!=null) {
try {
session.getProject().getLogin().setStatementCacheSize(Integer.parseInt(cacheStatementsSize));
} catch (NumberFormatException e) {
session.handleException(ValidationException.invalidCacheStatementsSize(cacheStatementsSize,e.getMessage()));
}
}
}
/**
* Enable or disable default temporal mutable setting.
* The method needs to be called in deploy stage.
*/
protected void updateTemporalMutableSetting(Map m) {
// Cache statements if flag was specified.
String temporalMutable = EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.TEMPORAL_MUTABLE, m, session);
if (temporalMutable != null) {
if (temporalMutable.equalsIgnoreCase("true")) {
session.getProject().setDefaultTemporalMutable(true);
} else if (temporalMutable.equalsIgnoreCase("false")) {
session.getProject().setDefaultTemporalMutable(false);
} else {
session.handleException(ValidationException.invalidBooleanValueForProperty(temporalMutable, PersistenceUnitProperties.TEMPORAL_MUTABLE));
}
}
}
/**
* Copy named queries defined in EclipseLink descriptor into the session if it was indicated to do so.
*/
protected void setDescriptorNamedQueries(Map m) {
// Copy named queries to session if the flag has been specified.
String addNamedQueriesString = EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.INCLUDE_DESCRIPTOR_QUERIES, m, session);
if (addNamedQueriesString!=null) {
if (addNamedQueriesString.equalsIgnoreCase("true")) {
session.copyDescriptorNamedQueries(false);
} else {
if (!addNamedQueriesString.equalsIgnoreCase("false")) {
session.handleException(ValidationException.invalidBooleanValueForAddingNamedQueries(addNamedQueriesString));
}
}
}
}
}
| Bug 246317 Multiple PUs with session-name not supported.\n Reviewed by Tom Ware
Former-commit-id: 9108119514a8dbbabb2c034bbc71f216b4042035 | jpa/org.eclipse.persistence.jpa/src/org/eclipse/persistence/internal/jpa/EntityManagerSetupImpl.java | Bug 246317 Multiple PUs with session-name not supported.\n Reviewed by Tom Ware |
|
Java | mpl-2.0 | 96c64900d84a448b3814b4ab43dcd078e30dd64a | 0 | preethi29/openmrs-core,ssmusoke/openmrs-core,ssmusoke/openmrs-core,aboutdata/openmrs-core,vinayvenu/openmrs-core,MuhammadSafwan/Stop-Button-Ability,alexwind26/openmrs-core,jembi/openmrs-core,kristopherschmidt/openmrs-core,WANeves/openmrs-core,iLoop2/openmrs-core,jamesfeshner/openmrs-module,Negatu/openmrs-core,trsorsimoII/openmrs-core,joansmith/openmrs-core,maekstr/openmrs-core,joansmith/openmrs-core,lilo2k/openmrs-core,MitchellBot/openmrs-core,kigsmtua/openmrs-core,koskedk/openmrs-core,kckc/openmrs-core,asifur77/openmrs,foolchan2556/openmrs-core,jvena1/openmrs-core,aj-jaswanth/openmrs-core,MitchellBot/openmrs-core,sravanthi17/openmrs-core,kabariyamilind/openMRSDEV,kigsmtua/openmrs-core,kckc/openmrs-core,pselle/openmrs-core,koskedk/openmrs-core,jvena1/openmrs-core,vinayvenu/openmrs-core,dcmul/openmrs-core,jembi/openmrs-core,jembi/openmrs-core,chethandeshpande/openmrs-core,vinayvenu/openmrs-core,sintjuri/openmrs-core,Negatu/openmrs-core,lbl52001/openmrs-core,sravanthi17/openmrs-core,kckc/openmrs-core,aboutdata/openmrs-core,foolchan2556/openmrs-core,lbl52001/openmrs-core,macorrales/openmrs-core,sintjuri/openmrs-core,trsorsimoII/openmrs-core,milankarunarathne/openmrs-core,MuhammadSafwan/Stop-Button-Ability,prisamuel/openmrs-core,jamesfeshner/openmrs-module,sravanthi17/openmrs-core,alexwind26/openmrs-core,jamesfeshner/openmrs-module,milankarunarathne/openmrs-core,MuhammadSafwan/Stop-Button-Ability,maany/openmrs-core,chethandeshpande/openmrs-core,andyvand/OpenMRS,kabariyamilind/openMRSDEV,spereverziev/openmrs-core,hoquangtruong/TestMylyn,MitchellBot/openmrs-core,koskedk/openmrs-core,milankarunarathne/openmrs-core,kabariyamilind/openMRSDEV,alexei-grigoriev/openmrs-core,aj-jaswanth/openmrs-core,jembi/openmrs-core,aj-jaswanth/openmrs-core,sadhanvejella/openmrs,geoff-wasilwa/openmrs-core,jembi/openmrs-core,siddharthkhabia/openmrs-core,aj-jaswanth/openmrs-core,nilusi/Legacy-UI,sadhanvejella/openmrs,lbl52001/openmrs-core,Bhamni/openmrs-core,spereverziev/openmrs-core,siddharthkhabia/openmrs-core,andyvand/OpenMRS,Openmrs-joel/openmrs-core,andyvand/OpenMRS,jcantu1988/openmrs-core,MitchellBot/openmrs-core,hoquangtruong/TestMylyn,Ch3ck/openmrs-core,preethi29/openmrs-core,naraink/openmrs-core,jcantu1988/openmrs-core,maany/openmrs-core,kckc/openmrs-core,maany/openmrs-core,macorrales/openmrs-core,iLoop2/openmrs-core,maekstr/openmrs-core,alexei-grigoriev/openmrs-core,macorrales/openmrs-core,kigsmtua/openmrs-core,dcmul/openmrs-core,Negatu/openmrs-core,lilo2k/openmrs-core,maekstr/openmrs-core,chethandeshpande/openmrs-core,geoff-wasilwa/openmrs-core,WANeves/openmrs-core,siddharthkhabia/openmrs-core,Openmrs-joel/openmrs-core,ssmusoke/openmrs-core,pselle/openmrs-core,lilo2k/openmrs-core,kckc/openmrs-core,donaldgavis/openmrs-core,ldf92/openmrs-core,AbhijitParate/openmrs-core,kabariyamilind/openMRSDEV,koskedk/openmrs-core,lbl52001/openmrs-core,maekstr/openmrs-core,WANeves/openmrs-core,kristopherschmidt/openmrs-core,spereverziev/openmrs-core,Winbobob/openmrs-core,donaldgavis/openmrs-core,kristopherschmidt/openmrs-core,Winbobob/openmrs-core,Bhamni/openmrs-core,prisamuel/openmrs-core,prisamuel/openmrs-core,Ch3ck/openmrs-core,pselle/openmrs-core,pselle/openmrs-core,trsorsimoII/openmrs-core,dcmul/openmrs-core,AbhijitParate/openmrs-core,kigsmtua/openmrs-core,jcantu1988/openmrs-core,dcmul/openmrs-core,prisamuel/openmrs-core,shiangree/openmrs-core,jcantu1988/openmrs-core,geoff-wasilwa/openmrs-core,MuhammadSafwan/Stop-Button-Ability,michaelhofer/openmrs-core,ssmusoke/openmrs-core,WANeves/openmrs-core,naraink/openmrs-core,Winbobob/openmrs-core,Ch3ck/openmrs-core,sadhanvejella/openmrs,donaldgavis/openmrs-core,michaelhofer/openmrs-core,chethandeshpande/openmrs-core,hoquangtruong/TestMylyn,sintjuri/openmrs-core,koskedk/openmrs-core,sadhanvejella/openmrs,WANeves/openmrs-core,maekstr/openmrs-core,MitchellBot/openmrs-core,sravanthi17/openmrs-core,AbhijitParate/openmrs-core,lilo2k/openmrs-core,maany/openmrs-core,vinayvenu/openmrs-core,Openmrs-joel/openmrs-core,lilo2k/openmrs-core,Winbobob/openmrs-core,ern2/openmrs-core,ldf92/openmrs-core,kckc/openmrs-core,sravanthi17/openmrs-core,shiangree/openmrs-core,maekstr/openmrs-core,ssmusoke/openmrs-core,dlahn/openmrs-core,aboutdata/openmrs-core,donaldgavis/openmrs-core,ern2/openmrs-core,foolchan2556/openmrs-core,Winbobob/openmrs-core,alexwind26/openmrs-core,milankarunarathne/openmrs-core,Ch3ck/openmrs-core,prisamuel/openmrs-core,dcmul/openmrs-core,MuhammadSafwan/Stop-Button-Ability,Negatu/openmrs-core,geoff-wasilwa/openmrs-core,nilusi/Legacy-UI,kabariyamilind/openMRSDEV,andyvand/OpenMRS,trsorsimoII/openmrs-core,Negatu/openmrs-core,shiangree/openmrs-core,andyvand/OpenMRS,jvena1/openmrs-core,michaelhofer/openmrs-core,lilo2k/openmrs-core,Winbobob/openmrs-core,chethandeshpande/openmrs-core,aboutdata/openmrs-core,rbtracker/openmrs-core,dlahn/openmrs-core,ldf92/openmrs-core,aboutdata/openmrs-core,joansmith/openmrs-core,ern2/openmrs-core,iLoop2/openmrs-core,alexei-grigoriev/openmrs-core,asifur77/openmrs,dlahn/openmrs-core,shiangree/openmrs-core,Negatu/openmrs-core,kigsmtua/openmrs-core,jcantu1988/openmrs-core,hoquangtruong/TestMylyn,rbtracker/openmrs-core,iLoop2/openmrs-core,asifur77/openmrs,aj-jaswanth/openmrs-core,MuhammadSafwan/Stop-Button-Ability,sadhanvejella/openmrs,AbhijitParate/openmrs-core,nilusi/Legacy-UI,pselle/openmrs-core,naraink/openmrs-core,Bhamni/openmrs-core,Openmrs-joel/openmrs-core,jamesfeshner/openmrs-module,spereverziev/openmrs-core,milankarunarathne/openmrs-core,kigsmtua/openmrs-core,jembi/openmrs-core,naraink/openmrs-core,hoquangtruong/TestMylyn,alexwind26/openmrs-core,foolchan2556/openmrs-core,kristopherschmidt/openmrs-core,naraink/openmrs-core,sintjuri/openmrs-core,asifur77/openmrs,Bhamni/openmrs-core,jamesfeshner/openmrs-module,donaldgavis/openmrs-core,WANeves/openmrs-core,maany/openmrs-core,ldf92/openmrs-core,naraink/openmrs-core,preethi29/openmrs-core,iLoop2/openmrs-core,siddharthkhabia/openmrs-core,alexei-grigoriev/openmrs-core,michaelhofer/openmrs-core,lbl52001/openmrs-core,joansmith/openmrs-core,rbtracker/openmrs-core,kristopherschmidt/openmrs-core,AbhijitParate/openmrs-core,trsorsimoII/openmrs-core,siddharthkhabia/openmrs-core,alexwind26/openmrs-core,spereverziev/openmrs-core,Openmrs-joel/openmrs-core,AbhijitParate/openmrs-core,foolchan2556/openmrs-core,lbl52001/openmrs-core,sadhanvejella/openmrs,prisamuel/openmrs-core,ldf92/openmrs-core,preethi29/openmrs-core,joansmith/openmrs-core,dcmul/openmrs-core,milankarunarathne/openmrs-core,preethi29/openmrs-core,Bhamni/openmrs-core,foolchan2556/openmrs-core,dlahn/openmrs-core,vinayvenu/openmrs-core,jvena1/openmrs-core,macorrales/openmrs-core,Ch3ck/openmrs-core,aboutdata/openmrs-core,jvena1/openmrs-core,nilusi/Legacy-UI,siddharthkhabia/openmrs-core,iLoop2/openmrs-core,andyvand/OpenMRS,alexei-grigoriev/openmrs-core,rbtracker/openmrs-core,sintjuri/openmrs-core,ern2/openmrs-core,shiangree/openmrs-core,macorrales/openmrs-core,sintjuri/openmrs-core,koskedk/openmrs-core,spereverziev/openmrs-core,shiangree/openmrs-core,asifur77/openmrs,nilusi/Legacy-UI,alexei-grigoriev/openmrs-core,geoff-wasilwa/openmrs-core,dlahn/openmrs-core,nilusi/Legacy-UI,rbtracker/openmrs-core,ern2/openmrs-core,michaelhofer/openmrs-core,pselle/openmrs-core,hoquangtruong/TestMylyn | /**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.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://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import org.openmrs.api.context.Context;
import org.openmrs.test.Verifies;
/**
* Tests methods in the {@link ProgramWorkflow} class
*/
public class ProgramWorkflowTest {
/**
* @see {@link ProgramWorkflow#getSortedStates()}
*/
@Test
@Verifies(value = "should sort names containing numbers intelligently", method = "getSortedStates()")
public void getSortedStates_shouldSortNamesContainingNumbersIntelligently() throws Exception {
ProgramWorkflow program = new ProgramWorkflow();
ConceptName state1ConceptName = new ConceptName("Group 10", Context.getLocale());
Concept state1Concept = new Concept();
state1Concept.addName(state1ConceptName);
ProgramWorkflowState state1 = new ProgramWorkflowState();
state1.setConcept(state1Concept);
program.addState(state1);
ConceptName state2ConceptName = new ConceptName("Group 2", Context.getLocale());
Concept state2Concept = new Concept();
state2Concept.addName(state2ConceptName);
ProgramWorkflowState state2 = new ProgramWorkflowState();
state2.setConcept(state2Concept);
program.addState(state2);
Set<ProgramWorkflowState> sortedStates = program.getSortedStates();
int x = 1;
for (ProgramWorkflowState state : sortedStates) {
if (x == 1)
Assert.assertEquals("Group 2", state.getConcept().getBestName(null).getName());
else if (x == 2)
Assert.assertEquals("Group 10", state.getConcept().getBestName(null).getName());
else
Assert.fail("Wha?!");
x++;
}
}
/**
* @see {@link Program#equals(Object)}
*/
@Test
public void equals_shouldReturnFalseIfProgramInstancesAreDifferentAndIdsAreNull() throws Exception {
Program program1 = new Program();
Program program2 = new Program();
Assert.assertFalse(program1.equals(program2));
Assert.assertTrue(program1.equals(program1));
}
/**
* @see {@link ProgramWorkflow#equals(Object)}
*/
@Test
public void equals_shouldReturnFalseIfProgramWorkflowInstancesAreDifferentAndIdsAreNull() throws Exception {
ProgramWorkflow workflow1 = new ProgramWorkflow();
ProgramWorkflow workflow2 = new ProgramWorkflow();
Assert.assertFalse(workflow1.equals(workflow2));
Assert.assertTrue(workflow1.equals(workflow1));
}
/**
* @see {@link ProgramWorkflowState#equals(Object)}
*/
@Test
public void equals_shouldReturnFalseIfProgramWorkflowStateInstancesAreDifferentAndIdsAreNull() throws Exception {
ProgramWorkflowState state1 = new ProgramWorkflowState();
ProgramWorkflowState state2 = new ProgramWorkflowState();
Assert.assertFalse(state1.equals(state2));
Assert.assertTrue(state1.equals(state1));
}
/**
* @see {@link PatientProgram#equals(Object)}
*/
@Test
public void equals_shouldReturnFalseIfPatientProgramInstancesAreDifferentAndIsAreNull() throws Exception {
PatientProgram p1 = new PatientProgram();
PatientProgram p2 = new PatientProgram();
Assert.assertFalse(p1.equals(p2));
Assert.assertTrue(p1.equals(p1));
}
/**
* @see {@link PatientSate#equals(Object)}
*/
@Test
public void equals_shouldReturnFalseIfPatientStateInstancesAreDifferentAndIdsAreNull() throws Exception {
PatientState state1 = new PatientState();
PatientState state2 = new PatientState();
Assert.assertFalse(state1.equals(state2));
Assert.assertTrue(state1.equals(state1));
}
/**
* @see {@link ConceptStateConversion#equals(Object)}
*/
@Test
public void equals_shouldReturnFalseIfConceptStateConversionInstancesAreDifferentAndIdsAreNull() throws Exception {
ConceptStateConversion c1 = new ConceptStateConversion();
ConceptStateConversion c2 = new ConceptStateConversion();
Assert.assertFalse(c1.equals(c2));
Assert.assertTrue(c1.equals(c1));
}
}
| test/api/org/openmrs/ProgramWorkflowTest.java | /**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.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://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import org.openmrs.api.context.Context;
import org.openmrs.test.Verifies;
/**
* Tests methods in the {@link ProgramWorkflow} class
*/
public class ProgramWorkflowTest {
/**
* @see {@link ProgramWorkflow#getSortedStates()}
*/
@Test
@Verifies(value = "should sort names containing numbers intelligently", method = "getSortedStates()")
public void getSortedStates_shouldSortNamesContainingNumbersIntelligently() throws Exception {
ProgramWorkflow program = new ProgramWorkflow();
ConceptName state1ConceptName = new ConceptName("Group 10", Context.getLocale());
Concept state1Concept = new Concept();
state1Concept.addName(state1ConceptName);
ProgramWorkflowState state1 = new ProgramWorkflowState();
state1.setConcept(state1Concept);
program.addState(state1);
ConceptName state2ConceptName = new ConceptName("Group 2", Context.getLocale());
Concept state2Concept = new Concept();
state2Concept.addName(state2ConceptName);
ProgramWorkflowState state2 = new ProgramWorkflowState();
state2.setConcept(state2Concept);
program.addState(state2);
Set<ProgramWorkflowState> sortedStates = program.getSortedStates();
int x = 1;
for (ProgramWorkflowState state : sortedStates) {
if (x == 1)
Assert.assertEquals("Group 2", state.getConcept().getBestName(null).getName());
else if (x == 2)
Assert.assertEquals("Group 10", state.getConcept().getBestName(null).getName());
else
Assert.fail("Wha?!");
x++;
}
}
/**
* @see {@link Program#equals(Object)}
*/
@Test
public void equals_programShouldReturnFalseIfInstancesAreDifferentAndIdentifiersAreNull() throws Exception {
Program program1 = new Program();
Program program2 = new Program();
Assert.assertFalse(program1.equals(program2));
Assert.assertTrue(program1.equals(program1));
}
/**
* @see {@link ProgramWorkflow#equals(Object)}
*/
@Test
public void equals_programWorkflowShouldReturnFalseIfInstancesAreDifferentAndIdentifiersAreNull() throws Exception {
ProgramWorkflow workflow1 = new ProgramWorkflow();
ProgramWorkflow workflow2 = new ProgramWorkflow();
Assert.assertFalse(workflow1.equals(workflow2));
Assert.assertTrue(workflow1.equals(workflow1));
}
/**
* @see {@link ProgramWorkflowState#equals(Object)}
*/
@Test
public void equals_programWorkflowStateShouldReturnFalseIfInstancesAreDifferentAndIdentifiersAreNull() throws Exception {
ProgramWorkflowState state1 = new ProgramWorkflowState();
ProgramWorkflowState state2 = new ProgramWorkflowState();
Assert.assertFalse(state1.equals(state2));
Assert.assertTrue(state1.equals(state1));
}
/**
* @see {@link PatientProgram#equals(Object)}
*/
@Test
public void equals_patientProgramShouldReturnFalseIfInstancesAreDifferentAndIdentifiersAreNull() throws Exception {
PatientProgram p1 = new PatientProgram();
PatientProgram p2 = new PatientProgram();
Assert.assertFalse(p1.equals(p2));
Assert.assertTrue(p1.equals(p1));
}
/**
* @see {@link PatientSate#equals(Object)}
*/
@Test
public void equals_patientStateShouldReturnFalseIfInstancesAreDifferentAndIdentifiersAreNull() throws Exception {
PatientState state1 = new PatientState();
PatientState state2 = new PatientState();
Assert.assertFalse(state1.equals(state2));
Assert.assertTrue(state1.equals(state1));
}
/**
* @see {@link ConceptStateConversion#equals(Object)}
*/
@Test
public void equals_conceptStateConversionShouldReturnFalseIfInstancesAreDifferentAndIdentifiersAreNull() throws Exception {
ConceptStateConversion c1 = new ConceptStateConversion();
ConceptStateConversion c2 = new ConceptStateConversion();
Assert.assertFalse(c1.equals(c2));
Assert.assertTrue(c1.equals(c1));
}
}
| Fix to ProgramWorkflowTest method names to match convention of starting with should
git-svn-id: ce3478dfdc990238714fcdf4fc6855b7489218cf@9266 5bac5841-c719-aa4e-b3fe-cce5062f897a
| test/api/org/openmrs/ProgramWorkflowTest.java | Fix to ProgramWorkflowTest method names to match convention of starting with should |
|
Java | agpl-3.0 | ccc65e192fd7bb13262b7436fec4f45ddf51b2b1 | 0 | podd/podd-redesign,podd/podd-redesign,podd/podd-redesign,podd/podd-redesign | /**
*
*/
package com.github.podd.api.file;
import com.github.podd.api.PoddRdfProcessorFactory;
/**
* @author Peter Ansell [email protected]
*
*/
public interface PoddFileReferenceProcessorFactory extends PoddRdfProcessorFactory<PoddFileReferenceProcessor<PoddFileReference>>
{
}
| webapp/api/src/main/java/com/github/podd/api/file/PoddFileReferenceProcessorFactory.java | /**
*
*/
package com.github.podd.api.file;
import com.github.podd.api.PoddRdfProcessorFactory;
/**
* @author Peter Ansell [email protected]
*
*/
public interface PoddFileReferenceProcessorFactory extends PoddRdfProcessorFactory<PoddFileReferenceProcessor>
{
}
| add generics | webapp/api/src/main/java/com/github/podd/api/file/PoddFileReferenceProcessorFactory.java | add generics |
|
Java | agpl-3.0 | 657d92919ec60b3601c0a9ab529866ff506ca85b | 0 | ua-eas/kfs-devops-automation-fork,UniversityOfHawaii/kfs,bhutchinson/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,bhutchinson/kfs,UniversityOfHawaii/kfs,smith750/kfs,kkronenb/kfs,kkronenb/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,kuali/kfs,quikkian-ua-devops/kfs,kuali/kfs,kkronenb/kfs,ua-eas/kfs,smith750/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/will-financials,smith750/kfs,ua-eas/kfs,ua-eas/kfs,smith750/kfs,kuali/kfs,ua-eas/kfs,UniversityOfHawaii/kfs,kkronenb/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,ua-eas/kfs,bhutchinson/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,bhutchinson/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,kuali/kfs,kuali/kfs,ua-eas/kfs-devops-automation-fork | /*
* Copyright 2008 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kfs.module.cab.service.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.kuali.kfs.coa.businessobject.ObjectCode;
import org.kuali.kfs.fp.businessobject.CapitalAssetInformation;
import org.kuali.kfs.fp.businessobject.CapitalAssetInformationDetail;
import org.kuali.kfs.fp.document.CashReceiptDocument;
import org.kuali.kfs.fp.document.DistributionOfIncomeAndExpenseDocument;
import org.kuali.kfs.fp.document.GeneralErrorCorrectionDocument;
import org.kuali.kfs.fp.document.InternalBillingDocument;
import org.kuali.kfs.fp.document.ProcurementCardDocument;
import org.kuali.kfs.fp.document.ServiceBillingDocument;
import org.kuali.kfs.fp.document.YearEndDistributionOfIncomeAndExpenseDocument;
import org.kuali.kfs.fp.document.YearEndGeneralErrorCorrectionDocument;
import org.kuali.kfs.integration.cab.CapitalAssetBuilderAssetTransactionType;
import org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService;
import org.kuali.kfs.integration.cam.CapitalAssetManagementModuleService;
import org.kuali.kfs.integration.purap.CapitalAssetLocation;
import org.kuali.kfs.integration.purap.CapitalAssetSystem;
import org.kuali.kfs.integration.purap.ExternalPurApItem;
import org.kuali.kfs.integration.purap.ItemCapitalAsset;
import org.kuali.kfs.integration.purap.PurchasingAccountsPayableModuleService;
import org.kuali.kfs.module.cab.CabConstants;
import org.kuali.kfs.module.cab.CabKeyConstants;
import org.kuali.kfs.module.cab.CabParameterConstants;
import org.kuali.kfs.module.cab.CabPropertyConstants;
import org.kuali.kfs.module.cab.businessobject.AssetTransactionType;
import org.kuali.kfs.module.cab.businessobject.GeneralLedgerEntry;
import org.kuali.kfs.module.cab.businessobject.GeneralLedgerEntryAsset;
import org.kuali.kfs.module.cab.businessobject.PurchasingAccountsPayableDocument;
import org.kuali.kfs.module.cab.businessobject.PurchasingAccountsPayableItemAsset;
import org.kuali.kfs.module.cab.businessobject.PurchasingAccountsPayableLineAssetAccount;
import org.kuali.kfs.module.cab.document.service.PurApInfoService;
import org.kuali.kfs.module.cam.CamsConstants;
import org.kuali.kfs.module.cam.CamsKeyConstants;
import org.kuali.kfs.module.cam.CamsPropertyConstants;
import org.kuali.kfs.module.cam.CamsConstants.DocumentTypeName;
import org.kuali.kfs.module.cam.businessobject.Asset;
import org.kuali.kfs.module.cam.businessobject.AssetGlobal;
import org.kuali.kfs.module.cam.businessobject.AssetGlobalDetail;
import org.kuali.kfs.module.cam.businessobject.AssetPaymentAssetDetail;
import org.kuali.kfs.module.cam.businessobject.AssetType;
import org.kuali.kfs.module.cam.document.service.AssetService;
import org.kuali.kfs.module.purap.PurapConstants;
import org.kuali.kfs.module.purap.PurapKeyConstants;
import org.kuali.kfs.module.purap.PurapParameterConstants;
import org.kuali.kfs.module.purap.PurapPropertyConstants;
import org.kuali.kfs.module.purap.businessobject.AccountsPayableItem;
import org.kuali.kfs.module.purap.businessobject.AvailabilityMatrix;
import org.kuali.kfs.module.purap.businessobject.PurApAccountingLine;
import org.kuali.kfs.module.purap.businessobject.PurApItem;
import org.kuali.kfs.module.purap.businessobject.PurchasingCapitalAssetItem;
import org.kuali.kfs.module.purap.businessobject.PurchasingItem;
import org.kuali.kfs.module.purap.businessobject.PurchasingItemBase;
import org.kuali.kfs.module.purap.businessobject.PurchasingItemCapitalAssetBase;
import org.kuali.kfs.module.purap.document.AccountsPayableDocument;
import org.kuali.kfs.module.purap.document.PurchaseOrderDocument;
import org.kuali.kfs.module.purap.document.PurchasingDocument;
import org.kuali.kfs.module.purap.document.RequisitionDocument;
import org.kuali.kfs.sys.KFSConstants;
import org.kuali.kfs.sys.KFSKeyConstants;
import org.kuali.kfs.sys.KFSPropertyConstants;
import org.kuali.kfs.sys.businessobject.AccountingLine;
import org.kuali.kfs.sys.businessobject.Building;
import org.kuali.kfs.sys.businessobject.Room;
import org.kuali.kfs.sys.businessobject.SourceAccountingLine;
import org.kuali.kfs.sys.businessobject.TargetAccountingLine;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.sys.document.AccountingDocument;
import org.kuali.kfs.sys.service.impl.KfsParameterConstants;
import org.kuali.rice.kns.bo.Campus;
import org.kuali.rice.kns.bo.DocumentHeader;
import org.kuali.rice.kns.bo.Parameter;
import org.kuali.rice.kns.datadictionary.AttributeDefinition;
import org.kuali.rice.kns.datadictionary.BusinessObjectEntry;
import org.kuali.rice.kns.service.BusinessObjectDictionaryService;
import org.kuali.rice.kns.service.BusinessObjectService;
import org.kuali.rice.kns.service.DataDictionaryService;
import org.kuali.rice.kns.service.DictionaryValidationService;
import org.kuali.rice.kns.service.KualiConfigurationService;
import org.kuali.rice.kns.service.KualiModuleService;
import org.kuali.rice.kns.service.ParameterService;
import org.kuali.rice.kns.util.GlobalVariables;
import org.kuali.rice.kns.util.KualiDecimal;
import org.kuali.rice.kns.util.ObjectUtils;
import org.kuali.rice.kns.workflow.service.KualiWorkflowDocument;
public class CapitalAssetBuilderModuleServiceImpl implements CapitalAssetBuilderModuleService {
private static Logger LOG = Logger.getLogger(CapitalAssetBuilderModuleService.class);
/**
* @see org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService#getAllAssetTransactionTypes()
*/
public List<CapitalAssetBuilderAssetTransactionType> getAllAssetTransactionTypes() {
Class<? extends CapitalAssetBuilderAssetTransactionType> assetTransactionTypeClass = this.getKualiModuleService().getResponsibleModuleService(CapitalAssetBuilderAssetTransactionType.class).getExternalizableBusinessObjectImplementation(CapitalAssetBuilderAssetTransactionType.class);
return (List<CapitalAssetBuilderAssetTransactionType>) this.getBusinessObjectService().findAll(assetTransactionTypeClass);
}
/**
* @see org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService#validatePurchasingAccountsPayableData(org.kuali.kfs.sys.document.AccountingDocument)
*/
public boolean validatePurchasingData(AccountingDocument accountingDocument) {
PurchasingDocument purchasingDocument = (PurchasingDocument) accountingDocument;
String documentType = (purchasingDocument instanceof RequisitionDocument) ? "REQUISITION" : "PURCHASE_ORDER";
if (PurapConstants.CapitalAssetSystemTypes.INDIVIDUAL.equals(purchasingDocument.getCapitalAssetSystemTypeCode())) {
return validateIndividualCapitalAssetSystemFromPurchasing(purchasingDocument.getCapitalAssetSystemStateCode(), purchasingDocument.getPurchasingCapitalAssetItems(), purchasingDocument.getChartOfAccountsCode(), documentType);
}
else if (PurapConstants.CapitalAssetSystemTypes.ONE_SYSTEM.equals(purchasingDocument.getCapitalAssetSystemTypeCode())) {
return validateOneSystemCapitalAssetSystemFromPurchasing(purchasingDocument.getCapitalAssetSystemStateCode(), purchasingDocument.getPurchasingCapitalAssetSystems(), purchasingDocument.getPurchasingCapitalAssetItems(), purchasingDocument.getChartOfAccountsCode(), documentType);
}
else if (PurapConstants.CapitalAssetSystemTypes.MULTIPLE.equals(purchasingDocument.getCapitalAssetSystemTypeCode())) {
return validateMultipleSystemsCapitalAssetSystemFromPurchasing(purchasingDocument.getCapitalAssetSystemStateCode(), purchasingDocument.getPurchasingCapitalAssetSystems(), purchasingDocument.getPurchasingCapitalAssetItems(), purchasingDocument.getChartOfAccountsCode(), documentType);
}
return false;
}
public boolean validateAccountsPayableData(AccountingDocument accountingDocument) {
AccountsPayableDocument apDocument = (AccountsPayableDocument) accountingDocument;
boolean valid = true;
for (PurApItem purApItem : apDocument.getItems()) {
AccountsPayableItem accountsPayableItem = (AccountsPayableItem) purApItem;
// only run on ap items that were line items (not additional charge items) and were cams items
if ((!accountsPayableItem.getItemType().isAdditionalChargeIndicator()) && StringUtils.isNotEmpty(accountsPayableItem.getCapitalAssetTransactionTypeCode())) {
valid &= validateAccountsPayableItem(accountsPayableItem);
}
}
return valid;
}
/**
* Perform the item level capital asset validation to determine if the given document is not allowed to become an Automatic
* Purchase Order (APO). The APO is not allowed if any accounting strings on the document are using an object level indicated as
* capital via a parameter setting.
*/
public boolean doesAccountingLineFailAutomaticPurchaseOrderRules(AccountingLine accountingLine) {
PurApAccountingLine purapAccountingLine = (PurApAccountingLine) accountingLine;
purapAccountingLine.refreshNonUpdateableReferences();
return getParameterService().getParameterEvaluator(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, CabParameterConstants.CapitalAsset.CAPITAL_ASSET_OBJECT_LEVELS, purapAccountingLine.getObjectCode().getFinancialObjectLevelCode()).evaluationSucceeds();
}
/**
* Perform the document level capital asset validation to determine if the given document is not allowed to become an Automatic
* Purchase Order (APO). The APO is not allowed if any capital asset items exist on the document.
*/
public boolean doesDocumentFailAutomaticPurchaseOrderRules(AccountingDocument accountingDocument) {
PurchasingDocument purchasingDocument = (PurchasingDocument) accountingDocument;
return ObjectUtils.isNotNull(purchasingDocument.getPurchasingCapitalAssetItems()) && !purchasingDocument.getPurchasingCapitalAssetItems().isEmpty();
}
public boolean validateAutomaticPurchaseOrderRule(AccountingDocument accountingDocument) {
PurchasingDocument purchasingDocument = (PurchasingDocument) accountingDocument;
for (PurApItem item : purchasingDocument.getItems()) {
if (doesItemNeedCapitalAsset(item.getItemTypeCode(), item.getSourceAccountingLines())) {
// if the item needs capital asset, we cannot have an APO, so return false.
return false;
}
}
return true;
}
public boolean doesItemNeedCapitalAsset(String itemTypeCode, List accountingLines) {
if (PurapConstants.ItemTypeCodes.ITEM_TYPE_TRADE_IN_CODE.equals(itemTypeCode)) {
// FIXME: Chris - this should be true but need to look to see where itemline number is referenced first
// return true;
return false;
}// else
for (Iterator iterator = accountingLines.iterator(); iterator.hasNext();) {
PurApAccountingLine accountingLine = (PurApAccountingLine) iterator.next();
accountingLine.refreshReferenceObject(KFSPropertyConstants.OBJECT_CODE);
if (isCapitalAssetObjectCode(accountingLine.getObjectCode())) {
return true;
}
}
return false;
}
public boolean validateUpdateCAMSView(AccountingDocument accountingDocument) {
PurchasingDocument purchasingDocument = (PurchasingDocument) accountingDocument;
boolean valid = true;
for (PurApItem purapItem : purchasingDocument.getItems()) {
if (purapItem.getItemType().isLineItemIndicator()) {
if (!doesItemNeedCapitalAsset(purapItem.getItemTypeCode(), purapItem.getSourceAccountingLines())) {
PurchasingCapitalAssetItem camsItem = ((PurchasingItem) purapItem).getPurchasingCapitalAssetItem();
if (camsItem != null && !camsItem.isEmpty()) {
valid = false;
GlobalVariables.getErrorMap().putError("newPurchasingItemCapitalAssetLine", PurapKeyConstants.ERROR_CAPITAL_ASSET_ITEM_NOT_CAMS_ELIGIBLE, "in line item # " + purapItem.getItemLineNumber());
}
}
}
}
return valid;
}
public boolean validateAddItemCapitalAssetBusinessRules(ItemCapitalAsset asset) {
boolean valid = true;
if (asset.getCapitalAssetNumber() == null) {
valid = false;
}
else {
valid = SpringContext.getBean(DictionaryValidationService.class).isBusinessObjectValid((PurchasingItemCapitalAssetBase) asset);
}
if (!valid) {
String propertyName = "newPurchasingItemCapitalAssetLine." + PurapPropertyConstants.CAPITAL_ASSET_NUMBER;
String errorKey = PurapKeyConstants.ERROR_CAPITAL_ASSET_ASSET_NUMBER_MUST_BE_LONG_NOT_NULL;
GlobalVariables.getErrorMap().putError(propertyName, errorKey);
}
return valid;
}
public boolean warningObjectLevelCapital(AccountingDocument accountingDocument) {
org.kuali.kfs.module.purap.document.PurchasingAccountsPayableDocument purapDocument = (org.kuali.kfs.module.purap.document.PurchasingAccountsPayableDocument) accountingDocument;
for (PurApItem item : purapDocument.getItems()) {
if (item.getItemType().isLineItemIndicator() && item.getItemType().isQuantityBasedGeneralLedgerIndicator()) {
List<PurApAccountingLine> accounts = item.getSourceAccountingLines();
BigDecimal unitPrice = item.getItemUnitPrice();
String itemIdentifier = item.getItemIdentifierString();
for (PurApAccountingLine account : accounts) {
ObjectCode objectCode = account.getObjectCode();
if (!validateLevelCapitalAssetIndication(unitPrice, objectCode, itemIdentifier)) {
// found an error
return false;
}
}
}
}
// no need for error
return true;
}
/**
* Validates the capital asset field requirements based on system parameter and chart for individual system type. This also
* calls validations for quantity on locations equal quantity on line items, validates that the transaction type allows asset
* number and validates the non quantity driven allowed indicator.
*
* @param systemState
* @param capitalAssetItems
* @param chartCode
* @param documentType
* @return
*/
protected boolean validateIndividualCapitalAssetSystemFromPurchasing(String systemState, List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String documentType) {
// For Individual Asset system type, the List of CapitalAssetSystems in the input parameter for
// validateAllFieldRequirementsByChart
// should be null. So we'll pass in a null here.
boolean valid = validateAllFieldRequirementsByChart(systemState, null, capitalAssetItems, chartCode, documentType, PurapConstants.CapitalAssetSystemTypes.INDIVIDUAL);
valid &= validateQuantityOnLocationsEqualsQuantityOnItem(capitalAssetItems, PurapConstants.CapitalAssetSystemTypes.INDIVIDUAL, systemState);
valid &= validateIndividualSystemPurchasingTransactionTypesAllowingAssetNumbers(capitalAssetItems);
valid &= validateNonQuantityDrivenAllowedIndicatorAndTradeIn(capitalAssetItems);
return valid;
}
/**
* Validates the capital asset field requirements based on system parameter and chart for one system type. This also calls
* validations that the transaction type allows asset number and validates the non quantity driven allowed indicator.
*
* @param systemState
* @param capitalAssetSystems
* @param capitalAssetItems
* @param chartCode
* @param documentType
* @return
*/
protected boolean validateOneSystemCapitalAssetSystemFromPurchasing(String systemState, List<CapitalAssetSystem> capitalAssetSystems, List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String documentType) {
boolean valid = validateAllFieldRequirementsByChart(systemState, capitalAssetSystems, capitalAssetItems, chartCode, documentType, PurapConstants.CapitalAssetSystemTypes.ONE_SYSTEM);
String capitalAssetTransactionType = capitalAssetItems.get(0).getCapitalAssetTransactionTypeCode();
String prefix = "document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEMS + "[0].";
valid &= validatePurchasingTransactionTypesAllowingAssetNumbers(capitalAssetSystems.get(0), capitalAssetTransactionType, prefix);
valid &= validateNonQuantityDrivenAllowedIndicatorAndTradeIn(capitalAssetItems);
return valid;
}
/**
* Validates the capital asset field requirements based on system parameter and chart for multiple system type. This also calls
* validations that the transaction type allows asset number and validates the non quantity driven allowed indicator.
*
* @param systemState
* @param capitalAssetSystems
* @param capitalAssetItems
* @param chartCode
* @param documentType
* @return
*/
protected boolean validateMultipleSystemsCapitalAssetSystemFromPurchasing(String systemState, List<CapitalAssetSystem> capitalAssetSystems, List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String documentType) {
boolean valid = validateAllFieldRequirementsByChart(systemState, capitalAssetSystems, capitalAssetItems, chartCode, documentType, PurapConstants.CapitalAssetSystemTypes.MULTIPLE);
String capitalAssetTransactionType = capitalAssetItems.get(0).getCapitalAssetTransactionTypeCode();
String prefix = "document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEMS + "[0].";
valid &= validatePurchasingTransactionTypesAllowingAssetNumbers(capitalAssetSystems.get(0), capitalAssetTransactionType, prefix);
valid &= validateNonQuantityDrivenAllowedIndicatorAndTradeIn(capitalAssetItems);
return valid;
}
/**
* Validates all the field requirements by chart. It obtains a List of parameters where the parameter names are like
* "CHARTS_REQUIRING%" then loop through these parameters. If the system type is individual then invoke the
* validateFieldRequirementByChartForIndividualSystemType for further validation, otherwise invoke the
* validateFieldRequirementByChartForOneOrMultipleSystemType for further validation.
*
* @param systemState
* @param capitalAssetSystems
* @param capitalAssetItems
* @param chartCode
* @param documentType
* @param systemType
* @return
*/
protected boolean validateAllFieldRequirementsByChart(String systemState, List<CapitalAssetSystem> capitalAssetSystems, List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String documentType, String systemType) {
boolean valid = true;
List<Parameter> results = new ArrayList<Parameter>();
Map<String, String> criteria = new HashMap<String, String>();
criteria.put(CabPropertyConstants.Parameter.PARAMETER_NAMESPACE_CODE, CabConstants.Parameters.NAMESPACE);
criteria.put(CabPropertyConstants.Parameter.PARAMETER_DETAIL_TYPE_CODE, CabConstants.Parameters.DETAIL_TYPE_DOCUMENT);
criteria.put(CabPropertyConstants.Parameter.PARAMETER_NAME, "CHARTS_REQUIRING%" + documentType);
results.addAll(SpringContext.getBean(ParameterService.class).retrieveParametersGivenLookupCriteria(criteria));
for (Parameter parameter : results) {
if (ObjectUtils.isNotNull(parameter)) {
if (systemType.equals(PurapConstants.CapitalAssetSystemTypes.INDIVIDUAL)) {
valid &= validateFieldRequirementByChartForIndividualSystemType(systemState, capitalAssetItems, chartCode, parameter.getParameterName(), parameter.getParameterValue());
}
else {
valid &= validateFieldRequirementByChartForOneOrMultipleSystemType(systemType, systemState, capitalAssetSystems, capitalAssetItems, chartCode, parameter.getParameterName(), parameter.getParameterValue());
}
}
}
return valid;
}
/**
* Validates all the field requirements by chart. It obtains a List of parameters where the parameter names are like
* "CHARTS_REQUIRING%" then loop through these parameters. If any of the parameter's values is null, then return false
*
* @param accountingDocument
* @return
*/
public boolean validateAllFieldRequirementsByChart(AccountingDocument accountingDocument) {
PurchasingDocument purchasingDocument = (PurchasingDocument) accountingDocument;
String documentType = (purchasingDocument instanceof RequisitionDocument) ? "REQUISITION" : "PURCHASE_ORDER";
boolean valid = true;
List<Parameter> results = new ArrayList<Parameter>();
Map<String, String> criteria = new HashMap<String, String>();
criteria.put(CabPropertyConstants.Parameter.PARAMETER_NAMESPACE_CODE, CabConstants.Parameters.NAMESPACE);
criteria.put(CabPropertyConstants.Parameter.PARAMETER_DETAIL_TYPE_CODE, CabConstants.Parameters.DETAIL_TYPE_DOCUMENT);
criteria.put(CabPropertyConstants.Parameter.PARAMETER_NAME, "CHARTS_REQUIRING%" + documentType);
results.addAll(SpringContext.getBean(ParameterService.class).retrieveParametersGivenLookupCriteria(criteria));
for (Parameter parameter : results) {
if (ObjectUtils.isNotNull(parameter)) {
if (parameter.getParameterValue() != null) {
return false;
}
}
}
return valid;
}
/**
* Validates for PURCHASING_OBJECT_SUB_TYPES parameter. If at least one object code of any accounting line entered is of this
* type, then return false.
*
* @param accountingDocument
* @return
*/
public boolean validatePurchasingObjectSubType(AccountingDocument accountingDocument) {
boolean valid = true;
PurchasingDocument purchasingDocument = (PurchasingDocument) accountingDocument;
for (PurApItem item : purchasingDocument.getItems()) {
String itemTypeCode = item.getItemTypeCode();
List accountingLines = item.getSourceAccountingLines();
for (Iterator iterator = accountingLines.iterator(); iterator.hasNext();) {
PurApAccountingLine accountingLine = (PurApAccountingLine) iterator.next();
accountingLine.refreshReferenceObject(KFSPropertyConstants.OBJECT_CODE);
if (isCapitalAssetObjectCode(accountingLine.getObjectCode())) {
return false;
}
}
}
return valid;
}
/**
* Validates field requirement by chart for one or multiple system types.
*
* @param systemType
* @param systemState
* @param capitalAssetSystems
* @param capitalAssetItems
* @param chartCode
* @param parameterName
* @param parameterValueString
* @return
*/
protected boolean validateFieldRequirementByChartForOneOrMultipleSystemType(String systemType, String systemState, List<CapitalAssetSystem> capitalAssetSystems, List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String parameterName, String parameterValueString) {
boolean valid = true;
boolean needValidation = (this.getParameterService().getParameterEvaluator(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, parameterName, chartCode).evaluationSucceeds());
if (needValidation) {
if (parameterName.startsWith("CHARTS_REQUIRING_LOCATIONS_ADDRESS")) {
return validateCapitalAssetLocationAddressFieldsOneOrMultipleSystemType(capitalAssetSystems);
}
String mappedName = PurapConstants.CAMS_REQUIREDNESS_FIELDS.REQUIREDNESS_FIELDS_BY_PARAMETER_NAMES.get(parameterName);
if (mappedName != null) {
// Check the availability matrix here, if this field doesn't exist according to the avail. matrix, then no need
// to validate any further.
String availableValue = getValueFromAvailabilityMatrix(mappedName, systemType, systemState);
if (availableValue.equals(PurapConstants.CapitalAssetAvailability.NONE)) {
return true;
}
// capitalAssetTransactionType field is off the item
if (mappedName.equals(PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE_CODE)) {
String[] mappedNames = { PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS, mappedName };
for (PurchasingCapitalAssetItem item : capitalAssetItems) {
StringBuffer keyBuffer = new StringBuffer("document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "[" + new Integer(item.getPurchasingItem().getItemLineNumber().intValue() - 1) + "].");
valid &= validateFieldRequirementByChartHelper(item, ArrayUtils.subarray(mappedNames, 1, mappedNames.length), keyBuffer, item.getPurchasingItem().getItemLineNumber());
}
}
// all the other fields are off the system.
else {
List<String> mappedNamesList = new ArrayList<String>();
mappedNamesList.add(PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEMS);
if (mappedName.indexOf(".") < 0) {
mappedNamesList.add(mappedName);
}
else {
mappedNamesList.addAll(mappedNameSplitter(mappedName));
}
// For One system type, we would only have 1 CapitalAssetSystem, however, for multiple we may have more than
// one systems in the future. Either way, this for loop should allow both the one system and multiple system
// types to work fine.
int count = 0;
for (CapitalAssetSystem system : capitalAssetSystems) {
StringBuffer keyBuffer = new StringBuffer("document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEMS + "[" + new Integer(count) + "].");
valid &= validateFieldRequirementByChartHelper(system, ArrayUtils.subarray(mappedNamesList.toArray(), 1, mappedNamesList.size()), keyBuffer, null);
count++;
}
}
}
}
return valid;
}
/**
* Validates the field requirement by chart for individual system type.
*
* @param systemState
* @param capitalAssetItems
* @param chartCode
* @param parameterName
* @param parameterValueString
* @return
*/
protected boolean validateFieldRequirementByChartForIndividualSystemType(String systemState, List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String parameterName, String parameterValueString) {
boolean valid = true;
boolean needValidation = (this.getParameterService().getParameterEvaluator(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, parameterName, chartCode).evaluationSucceeds());
if (needValidation) {
if (parameterName.startsWith("CHARTS_REQUIRING_LOCATIONS_ADDRESS")) {
return validateCapitalAssetLocationAddressFieldsForIndividualSystemType(capitalAssetItems);
}
String mappedName = PurapConstants.CAMS_REQUIREDNESS_FIELDS.REQUIREDNESS_FIELDS_BY_PARAMETER_NAMES.get(parameterName);
if (mappedName != null) {
// Check the availability matrix here, if this field doesn't exist according to the avail. matrix, then no need
// to validate any further.
String availableValue = getValueFromAvailabilityMatrix(mappedName, PurapConstants.CapitalAssetSystemTypes.INDIVIDUAL, systemState);
if (availableValue.equals(PurapConstants.CapitalAssetAvailability.NONE)) {
return true;
}
// capitalAssetTransactionType field is off the item
List<String> mappedNamesList = new ArrayList<String>();
if (mappedName.equals(PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE_CODE)) {
mappedNamesList.add(PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS);
mappedNamesList.add(mappedName);
}
// all the other fields are off the system which is off the item
else {
mappedNamesList.add(PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS);
mappedNamesList.add(PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEM);
if (mappedName.indexOf(".") < 0) {
mappedNamesList.add(mappedName);
}
else {
mappedNamesList.addAll(mappedNameSplitter(mappedName));
}
}
// For Individual system type, we'll always iterate through the item, then if the field is off the system, we'll get
// it through
// the purchasingCapitalAssetSystem of the item.
for (PurchasingCapitalAssetItem item : capitalAssetItems) {
StringBuffer keyBuffer = new StringBuffer("document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "[" + new Integer(item.getPurchasingItem().getItemLineNumber().intValue() - 1) + "].");
valid &= validateFieldRequirementByChartHelper(item, ArrayUtils.subarray(mappedNamesList.toArray(), 1, mappedNamesList.size()), keyBuffer, item.getPurchasingItem().getItemLineNumber());
}
}
}
return valid;
}
/**
* Utility method to split a long String using the "." as the delimiter then add each of the array element into a List of String
* and return the List of String.
*
* @param mappedName The String to be splitted.
* @return The List of String after being splitted, with the "." as delimiter.
*/
protected List<String> mappedNameSplitter(String mappedName) {
List<String> result = new ArrayList<String>();
String[] mappedNamesArray = mappedName.split("\\.");
for (int i = 0; i < mappedNamesArray.length; i++) {
result.add(mappedNamesArray[i]);
}
return result;
}
/**
* Validates the field requirement by chart recursively and give error messages when it returns false.
*
* @param bean The object to be used to obtain the property value
* @param mappedNames The array of Strings which when combined together, they form the field property
* @param errorKey The error key to be used for adding error messages to the error map.
* @param itemNumber The Integer that represents the item number that we're currently iterating.
* @return true if it passes the validation.
*/
protected boolean validateFieldRequirementByChartHelper(Object bean, Object[] mappedNames, StringBuffer errorKey, Integer itemNumber) {
boolean valid = true;
Object value = ObjectUtils.getPropertyValue(bean, (String) mappedNames[0]);
if (ObjectUtils.isNull(value)) {
errorKey.append(mappedNames[0]);
String fieldName = SpringContext.getBean(DataDictionaryService.class).getAttributeErrorLabel(bean.getClass(), (String) mappedNames[0]);
if (itemNumber != null) {
fieldName = fieldName + " in Item " + itemNumber;
}
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, fieldName);
return false;
}
else if (value instanceof Collection) {
if (((Collection) value).isEmpty()) {
// if this collection doesn't contain anything, when it's supposed to contain some strings with values, return
// false.
errorKey.append(mappedNames[0]);
String mappedNameStr = (String) mappedNames[0];
String methodToInvoke = "get" + (mappedNameStr.substring(0, 1)).toUpperCase() + mappedNameStr.substring(1, mappedNameStr.length() - 1) + "Class";
Class offendingClass;
try {
offendingClass = (Class) bean.getClass().getMethod(methodToInvoke, null).invoke(bean, null);
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
BusinessObjectEntry boe = SpringContext.getBean(DataDictionaryService.class).getDataDictionary().getBusinessObjectEntry(offendingClass.getSimpleName());
List<AttributeDefinition> offendingAttributes = boe.getAttributes();
AttributeDefinition offendingAttribute = offendingAttributes.get(0);
String fieldName = SpringContext.getBean(DataDictionaryService.class).getAttributeShortLabel(offendingClass, offendingAttribute.getName());
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, fieldName);
return false;
}
int count = 0;
for (Iterator iter = ((Collection) value).iterator(); iter.hasNext();) {
errorKey.append(mappedNames[0] + "[" + count + "].");
count++;
valid &= validateFieldRequirementByChartHelper(iter.next(), ArrayUtils.subarray(mappedNames, 1, mappedNames.length), errorKey, itemNumber);
}
return valid;
}
else if (StringUtils.isBlank(value.toString())) {
errorKey.append(mappedNames[0]);
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, (String) mappedNames[0]);
return false;
}
else if (mappedNames.length > 1) {
// this means we have not reached the end of a single field to be traversed yet, so continue with the recursion.
errorKey.append(mappedNames[0]).append(".");
valid &= validateFieldRequirementByChartHelper(value, ArrayUtils.subarray(mappedNames, 1, mappedNames.length), errorKey, itemNumber);
return valid;
}
else {
return true;
}
}
protected String getValueFromAvailabilityMatrix(String fieldName, String systemType, String systemState) {
for (AvailabilityMatrix am : PurapConstants.CAMS_AVAILABILITY_MATRIX.MATRIX_LIST) {
if (am.fieldName.equals(fieldName) && am.systemState.equals(systemState) && am.systemType.equals(systemType)) {
return am.availableValue;
}
}
// if we can't find any matching from availability matrix, return null for now.
return null;
}
/**
* Validates that the total quantity on all locations equals to the quantity on the line item. This is only used for IND system
* type.
*
* @param capitalAssetItems
* @return true if the total quantity on all locations equals to the quantity on the line item.
*/
protected boolean validateQuantityOnLocationsEqualsQuantityOnItem(List<PurchasingCapitalAssetItem> capitalAssetItems, String systemType, String systemState) {
boolean valid = true;
String availableValue = getValueFromAvailabilityMatrix(PurapPropertyConstants.CAPITAL_ASSET_LOCATIONS + "." + PurapPropertyConstants.QUANTITY, systemType, systemState);
if (availableValue.equals(PurapConstants.CapitalAssetAvailability.NONE)) {
// If the location quantity isn't available on the document given the system type and system state, we don't need to
// validate this, just return true.
return true;
}
int count = 0;
for (PurchasingCapitalAssetItem item : capitalAssetItems) {
if (item.getPurchasingItem() != null && item.getPurchasingItem().getItemType().isQuantityBasedGeneralLedgerIndicator() && !item.getPurchasingCapitalAssetSystem().getCapitalAssetLocations().isEmpty()) {
KualiDecimal total = new KualiDecimal(0);
for (CapitalAssetLocation location : item.getPurchasingCapitalAssetSystem().getCapitalAssetLocations()) {
if (ObjectUtils.isNotNull(location.getItemQuantity())) {
total = total.add(location.getItemQuantity());
}
}
if (!item.getPurchasingItem().getItemQuantity().equals(total)) {
valid = false;
String errorKey = PurapKeyConstants.ERROR_CAPITAL_ASSET_LOCATIONS_QUANTITY_MUST_EQUAL_ITEM_QUANTITY;
String propertyName = "document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "[" + count + "]." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEM + ".newPurchasingCapitalAssetLocationLine." + PurapPropertyConstants.QUANTITY;
GlobalVariables.getErrorMap().putError(propertyName, errorKey, Integer.toString(count + 1));
}
}
count++;
}
return valid;
}
/**
* Validates for the individual system type that for each of the items, the capitalAssetTransactionTypeCode matches the system
* parameter PURCHASING_ASSET_TRANSACTION_TYPES_ALLOWING_ASSET_NUMBERS, the method will return true but if it doesn't match the
* system parameter, then loop through each of the itemCapitalAssets. If there is any non-null capitalAssetNumber then return
* false.
*
* @param capitalAssetItems the List of PurchasingCapitalAssetItems on the document to be validated
* @return false if the capital asset transaction type does not match the system parameter that allows asset numbers but the
* itemCapitalAsset contains at least one asset numbers.
*/
protected boolean validateIndividualSystemPurchasingTransactionTypesAllowingAssetNumbers(List<PurchasingCapitalAssetItem> capitalAssetItems) {
boolean valid = true;
int count = 0;
for (PurchasingCapitalAssetItem capitalAssetItem : capitalAssetItems) {
String prefix = "document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "[" + count + "].";
valid &= validatePurchasingTransactionTypesAllowingAssetNumbers(capitalAssetItem.getPurchasingCapitalAssetSystem(), capitalAssetItem.getCapitalAssetTransactionTypeCode(), prefix);
count++;
}
return valid;
}
/**
* Generic validation that if the capitalAssetTransactionTypeCode does not match the system parameter
* PURCHASING_ASSET_TRANSACTION_TYPES_ALLOWING_ASSET_NUMBERS and at least one of the itemCapitalAssets contain a non-null
* capitalAssetNumber then return false. This method is used by one system and multiple system types as well as being used as a
* helper method for validateIndividualSystemPurchasingTransactionTypesAllowingAssetNumbers method.
*
* @param capitalAssetSystem the capitalAssetSystem containing a List of itemCapitalAssets to be validated.
* @param capitalAssetTransactionType the capitalAssetTransactionTypeCode containing asset numbers to be validated.
* @return false if the capital asset transaction type does not match the system parameter that allows asset numbers but the
* itemCapitalAsset contains at least one asset numbers.
*/
protected boolean validatePurchasingTransactionTypesAllowingAssetNumbers(CapitalAssetSystem capitalAssetSystem, String capitalAssetTransactionType, String prefix) {
boolean allowedAssetNumbers = (this.getParameterService().getParameterEvaluator(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, CabParameterConstants.CapitalAsset.PURCHASING_ASSET_TRANSACTION_TYPES_ALLOWING_ASSET_NUMBERS, capitalAssetTransactionType).evaluationSucceeds());
if (allowedAssetNumbers) {
// If this is a transaction type that allows asset numbers, we don't need to validate anymore, just return true here.
return true;
}
else {
for (ItemCapitalAsset asset : capitalAssetSystem.getItemCapitalAssets()) {
if (asset.getCapitalAssetNumber() != null) {
String propertyName = prefix + PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE_CODE;
GlobalVariables.getErrorMap().putError(propertyName, PurapKeyConstants.ERROR_CAPITAL_ASSET_ASSET_NUMBERS_NOT_ALLOWED_TRANS_TYPE, capitalAssetTransactionType);
return false;
}
}
}
return true;
}
/**
* TODO: rename this method removing trade in reference? Validates that if the non quantity drive allowed indicator on the
* capital asset transaction type is false and the item is of non quantity type
*
* @param capitalAssetItems The List of PurchasingCapitalAssetItem to be validated.
* @return false if the indicator is false and there is at least one non quantity items on the list.
*/
protected boolean validateNonQuantityDrivenAllowedIndicatorAndTradeIn(List<PurchasingCapitalAssetItem> capitalAssetItems) {
boolean valid = true;
int count = 0;
for (PurchasingCapitalAssetItem capitalAssetItem : capitalAssetItems) {
String prefix = "document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "[" + count + "].";
if (StringUtils.isNotBlank(capitalAssetItem.getCapitalAssetTransactionTypeCode())) {
// ((PurchasingCapitalAssetItemBase)
// capitalAssetItem).refreshReferenceObject(PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE);
if (!capitalAssetItem.getCapitalAssetTransactionType().getCapitalAssetNonquantityDrivenAllowIndicator()) {
if (!capitalAssetItem.getPurchasingItem().getItemType().isQuantityBasedGeneralLedgerIndicator()) {
String propertyName = prefix + PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE_CODE;
GlobalVariables.getErrorMap().putError(propertyName, PurapKeyConstants.ERROR_CAPITAL_ASSET_TRANS_TYPE_NOT_ALLOWING_NON_QUANTITY_ITEMS, capitalAssetItem.getCapitalAssetTransactionTypeCode());
valid &= false;
}
}
}
count++;
}
return valid;
}
/**
* Wrapper to do Capital Asset validations, generating errors instead of warnings. Makes sure that the given item's data
* relevant to its later possible classification as a Capital Asset is internally consistent, by marshaling and calling the
* methods marked as Capital Asset validations. This implementation assumes that all object codes are valid (real) object codes.
*
* @param recurringPaymentType The item's document's RecurringPaymentType
* @param item A PurchasingItemBase object
* @param apoCheck True if this check is for APO purposes
* @return True if the item passes all Capital Asset validations
*/
public boolean validateItemCapitalAssetWithErrors(String recurringPaymentTypeCode, ExternalPurApItem item, boolean apoCheck) {
PurchasingItemBase purchasingItem = (PurchasingItemBase) item;
List<String> previousErrorPath = GlobalVariables.getErrorMap().getErrorPath();
GlobalVariables.getErrorMap().clearErrorPath();
GlobalVariables.getErrorMap().addToErrorPath(PurapConstants.CAPITAL_ASSET_TAB_ERRORS);
boolean result = validatePurchasingItemCapitalAsset(recurringPaymentTypeCode, purchasingItem);
// Now that we're done with cams related validations, reset the error path to what it was previously.
GlobalVariables.getErrorMap().clearErrorPath();
for (String path : previousErrorPath) {
GlobalVariables.getErrorMap().addToErrorPath(path);
}
return result;
}
/**
* Makes sure that the given item's data relevant to its later possible classification as a Capital Asset is internally
* consistent, by marshaling and calling the methods marked as Capital Asset validations. This implementation assumes that all
* object codes are valid (real) object codes.
*
* @param recurringPaymentType The item's document's RecurringPaymentType
* @param item A PurchasingItemBase object
* @param warn A boolean which should be set to true if warnings are to be set on the calling document for most of the
* validations, rather than errors.
* @return True if the item passes all Capital Asset validations
*/
protected boolean validatePurchasingItemCapitalAsset(String recurringPaymentTypeCode, PurchasingItem item) {
boolean valid = true;
String capitalAssetTransactionTypeCode = "";
AssetTransactionType capitalAssetTransactionType = null;
String itemIdentifier = item.getItemIdentifierString();
if (item.getPurchasingCapitalAssetItem() != null) {
capitalAssetTransactionTypeCode = item.getPurchasingCapitalAssetItem().getCapitalAssetTransactionTypeCode();
// ((PurchasingCapitalAssetItemBase)
// item.getPurchasingCapitalAssetItem()).refreshReferenceObject(PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE);
capitalAssetTransactionType = (AssetTransactionType) item.getPurchasingCapitalAssetItem().getCapitalAssetTransactionType();
}
// These checks do not depend on Accounting Line information, but do depend on transaction type.
if (!StringUtils.isEmpty(capitalAssetTransactionTypeCode)) {
valid &= validateCapitalAssetTransactionTypeVersusRecurrence(capitalAssetTransactionType, recurringPaymentTypeCode, itemIdentifier);
}
return valid &= validatePurapItemCapitalAsset(item, capitalAssetTransactionType);
}
/**
* This method validated purapItem giving a transtype
*
* @param recurringPaymentType
* @param item
* @param warn
* @return
*/
protected boolean validatePurapItemCapitalAsset(PurApItem item, AssetTransactionType capitalAssetTransactionType) {
boolean valid = true;
String itemIdentifier = item.getItemIdentifierString();
boolean quantityBased = item.getItemType().isQuantityBasedGeneralLedgerIndicator();
BigDecimal itemUnitPrice = item.getItemUnitPrice();
HashSet<String> capitalOrExpenseSet = new HashSet<String>(); // For the first validation on every accounting line.
// Do the checks that depend on Accounting Line information.
for (PurApAccountingLine accountingLine : item.getSourceAccountingLines()) {
// Because of ObjectCodeCurrent, we had to refresh this.
accountingLine.refreshReferenceObject(KFSPropertyConstants.OBJECT_CODE);
ObjectCode objectCode = accountingLine.getObjectCode();
String capitalOrExpense = objectCodeCapitalOrExpense(objectCode);
capitalOrExpenseSet.add(capitalOrExpense); // HashSets accumulate distinct values (and nulls) only.
valid &= validateAccountingLinesNotCapitalAndExpense(capitalOrExpenseSet, itemIdentifier, objectCode);
// Do the checks involving capital asset transaction type.
if (capitalAssetTransactionType != null) {
valid &= validateObjectCodeVersusTransactionType(objectCode, capitalAssetTransactionType, itemIdentifier, quantityBased);
}
}
return valid;
}
/**
* Capital Asset validation: An item cannot have among its associated accounting lines both object codes that indicate it is a
* Capital Asset, and object codes that indicate that the item is not a Capital Asset. Whether an object code indicates that the
* item is a Capital Asset is determined by whether its level is among a specific set of levels that are deemed acceptable for
* such items.
*
* @param capitalOrExpenseSet A HashSet containing the distinct values of either "Capital" or "Expense" that have been added to
* it.
* @param warn A boolean which should be set to true if warnings are to be set on the calling document
* @param itemIdentifier A String identifying the item for error display
* @param objectCode An ObjectCode, for error display
* @return True if the given HashSet contains at most one of either "Capital" or "Expense"
*/
protected boolean validateAccountingLinesNotCapitalAndExpense(HashSet<String> capitalOrExpenseSet, String itemIdentifier, ObjectCode objectCode) {
boolean valid = true;
// If the set contains more than one distinct string, fail.
if (capitalOrExpenseSet.size() > 1) {
GlobalVariables.getErrorMap().putError(KFSConstants.FINANCIAL_OBJECT_LEVEL_CODE_PROPERTY_NAME, CabKeyConstants.ERROR_ITEM_CAPITAL_AND_EXPENSE, itemIdentifier, objectCode.getFinancialObjectCodeName());
valid &= false;
}
return valid;
}
protected boolean validateLevelCapitalAssetIndication(BigDecimal unitPrice, ObjectCode objectCode, String itemIdentifier) {
String capitalAssetPriceThresholdParam = this.getParameterService().getParameterValue(AssetGlobal.class, CabParameterConstants.CapitalAsset.CAPITALIZATION_LIMIT_AMOUNT);
BigDecimal priceThreshold = null;
try {
priceThreshold = new BigDecimal(capitalAssetPriceThresholdParam);
}
catch (NumberFormatException nfe) {
throw new RuntimeException("the parameter for CAPITAL_ASSET_OBJECT_LEVELS came was not able to be converted to a number.", nfe);
}
if (unitPrice.compareTo(priceThreshold) >= 0) {
List<String> possibleCAMSObjectLevels = this.getParameterService().getParameterValues(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, CabParameterConstants.CapitalAsset.POSSIBLE_CAPITAL_ASSET_OBJECT_LEVELS);
if (possibleCAMSObjectLevels.contains(objectCode.getFinancialObjectLevelCode())) {
String warning = SpringContext.getBean(KualiConfigurationService.class).getPropertyString(CabKeyConstants.WARNING_ABOVE_THRESHOLD_SUGESTS_CAPITAL_ASSET_LEVEL);
warning = StringUtils.replace(warning, "{0}", itemIdentifier);
warning = StringUtils.replace(warning, "{1}", priceThreshold.toString());
GlobalVariables.getMessageList().add(warning);
return false;
}
}
return true;
}
/**
* Capital Asset validation: If the item has a transaction type, check that the transaction type is acceptable for the object
* code sub-types of all the object codes on the associated accounting lines.
*
* @param objectCode
* @param capitalAssetTransactionType
* @param warn A boolean which should be set to true if warnings are to be set on the calling document
* @param itemIdentifier
* @return
*/
protected boolean validateObjectCodeVersusTransactionType(ObjectCode objectCode, CapitalAssetBuilderAssetTransactionType capitalAssetTransactionType, String itemIdentifier, boolean quantityBasedItem) {
boolean valid = true;
String[] objectCodeSubTypes = {};
if (quantityBasedItem) {
String capitalAssetQuantitySubtypeRequiredText = capitalAssetTransactionType.getCapitalAssetQuantitySubtypeRequiredText();
if (capitalAssetQuantitySubtypeRequiredText != null) {
objectCodeSubTypes = StringUtils.split(capitalAssetQuantitySubtypeRequiredText, ";");
}
}
else {
String capitalAssetNonquantitySubtypeRequiredText = capitalAssetTransactionType.getCapitalAssetNonquantitySubtypeRequiredText();
if (capitalAssetNonquantitySubtypeRequiredText != null) {
objectCodeSubTypes = StringUtils.split(capitalAssetNonquantitySubtypeRequiredText, ";");
}
}
boolean found = false;
for (String subType : objectCodeSubTypes) {
if (StringUtils.equals(subType, objectCode.getFinancialObjectSubTypeCode())) {
found = true;
break;
}
}
if (!found) {
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.ITEM_CAPITAL_ASSET_TRANSACTION_TYPE, CabKeyConstants.ERROR_ITEM_TRAN_TYPE_OBJECT_CODE_SUBTYPE, itemIdentifier, capitalAssetTransactionType.getCapitalAssetTransactionTypeDescription(), objectCode.getFinancialObjectCodeName(), objectCode.getFinancialObjectSubType().getFinancialObjectSubTypeName());
valid &= false;
}
return valid;
}
/**
* Capital Asset validation: If the item has a transaction type, check that if the document specifies that recurring payments
* are to be made, that the transaction type is one that is appropriate for this situation, and that if the document does not
* specify that recurring payments are to be made, that the transaction type is one that is appropriate for that situation.
*
* @param capitalAssetTransactionType
* @param recurringPaymentType
* @param warn A boolean which should be set to true if warnings are to be set on the calling document
* @param itemIdentifier
* @return
*/
protected boolean validateCapitalAssetTransactionTypeVersusRecurrence(CapitalAssetBuilderAssetTransactionType capitalAssetTransactionType, String recurringPaymentTypeCode, String itemIdentifier) {
boolean valid = true;
// If there is a tran type ...
if ((capitalAssetTransactionType != null) && (capitalAssetTransactionType.getCapitalAssetTransactionTypeCode() != null)) {
String recurringTransactionTypeCodes = this.getParameterService().getParameterValue(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, CabParameterConstants.CapitalAsset.RECURRING_CAMS_TRAN_TYPES);
if (StringUtils.isNotEmpty(recurringPaymentTypeCode)) { // If there is a recurring payment type ...
if (!StringUtils.contains(recurringTransactionTypeCodes, capitalAssetTransactionType.getCapitalAssetTransactionTypeCode())) {
// There should be a recurring tran type code.
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.ITEM_CAPITAL_ASSET_TRANSACTION_TYPE, CabKeyConstants.ERROR_ITEM_WRONG_TRAN_TYPE, itemIdentifier, capitalAssetTransactionType.getCapitalAssetTransactionTypeDescription(), CabConstants.ValidationStrings.RECURRING);
valid &= false;
}
}
else { // If the payment type is not recurring ...
// There should not be a recurring transaction type code.
if (StringUtils.contains(recurringTransactionTypeCodes, capitalAssetTransactionType.getCapitalAssetTransactionTypeCode())) {
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.ITEM_CAPITAL_ASSET_TRANSACTION_TYPE, CabKeyConstants.ERROR_ITEM_WRONG_TRAN_TYPE, itemIdentifier, capitalAssetTransactionType.getCapitalAssetTransactionTypeDescription(), CabConstants.ValidationStrings.NON_RECURRING);
valid &= false;
}
}
}
else { // If there is no transaction type ...
if (StringUtils.isNotEmpty(recurringPaymentTypeCode)) { // If there is a recurring payment type ...
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.ITEM_CAPITAL_ASSET_TRANSACTION_TYPE, CabKeyConstants.ERROR_ITEM_NO_TRAN_TYPE, itemIdentifier, CabConstants.ValidationStrings.RECURRING);
valid &= false;
}
else { // If the payment type is not recurring ...
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.ITEM_CAPITAL_ASSET_TRANSACTION_TYPE, CabKeyConstants.ERROR_ITEM_NO_TRAN_TYPE, itemIdentifier, CabConstants.ValidationStrings.NON_RECURRING);
valid &= false;
}
}
return valid;
}
/**
* Utility wrapping isCapitalAssetObjectCode for the use of processItemCapitalAssetValidation.
*
* @param oc An ObjectCode
* @return A String indicating that the given object code is either Capital or Expense
*/
protected String objectCodeCapitalOrExpense(ObjectCode oc) {
String capital = CabConstants.ValidationStrings.CAPITAL;
String expense = CabConstants.ValidationStrings.EXPENSE;
return (isCapitalAssetObjectCode(oc) ? capital : expense);
}
/**
* Predicate to determine whether the given object code is of a specified object sub type required for purap cams.
*
* @param oc An ObjectCode
* @return True if the ObjectSubType is the one designated for capital assets.
*/
protected boolean isCapitalAssetObjectCode(ObjectCode oc) {
String capitalAssetObjectSubType = this.getParameterService().getParameterValue(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, PurapParameterConstants.CapitalAsset.PURCHASING_OBJECT_SUB_TYPES);
return (StringUtils.containsIgnoreCase(capitalAssetObjectSubType, oc.getFinancialObjectSubTypeCode()) ? true : false);
}
protected boolean validateCapitalAssetLocationAddressFieldsOneOrMultipleSystemType(List<CapitalAssetSystem> capitalAssetSystems) {
boolean valid = true;
int systemCount = 0;
for (CapitalAssetSystem system : capitalAssetSystems) {
List<CapitalAssetLocation> capitalAssetLocations = system.getCapitalAssetLocations();
StringBuffer errorKey = new StringBuffer("document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEMS + "[" + new Integer(systemCount++) + "].");
errorKey.append("capitalAssetLocations");
int locationCount = 0;
for (CapitalAssetLocation location : capitalAssetLocations) {
errorKey.append("[" + locationCount++ + "].");
valid &= validateCapitalAssetLocationAddressFields(location, errorKey);
}
}
return valid;
}
protected boolean validateCapitalAssetLocationAddressFieldsForIndividualSystemType(List<PurchasingCapitalAssetItem> capitalAssetItems) {
boolean valid = true;
for (PurchasingCapitalAssetItem item : capitalAssetItems) {
CapitalAssetSystem system = item.getPurchasingCapitalAssetSystem();
List<CapitalAssetLocation> capitalAssetLocations = system.getCapitalAssetLocations();
StringBuffer errorKey = new StringBuffer("document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "[" + new Integer(item.getPurchasingItem().getItemLineNumber().intValue() - 1) + "].");
errorKey.append("purchasingCapitalAssetSystem.capitalAssetLocations");
int i = 0;
for (CapitalAssetLocation location : capitalAssetLocations) {
errorKey.append("[" + i++ + "].");
valid &= validateCapitalAssetLocationAddressFields(location, errorKey);
}
}
return valid;
}
protected boolean validateCapitalAssetLocationAddressFields(CapitalAssetLocation location, StringBuffer errorKey) {
boolean valid = true;
if (StringUtils.isBlank(location.getCapitalAssetLine1Address())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_ADDRESS_LINE1);
valid &= false;
}
if (StringUtils.isBlank(location.getCapitalAssetCityName())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_CITY);
valid &= false;
}
if (StringUtils.isBlank(location.getCapitalAssetCountryCode())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_COUNTRY);
valid &= false;
}
else if (location.getCapitalAssetCountryCode().equals(KFSConstants.COUNTRY_CODE_UNITED_STATES)) {
if (StringUtils.isBlank(location.getCapitalAssetStateCode())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_STATE);
valid &= false;
}
if (StringUtils.isBlank(location.getCapitalAssetPostalCode())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_POSTAL_CODE);
valid &= false;
}
}
if (!location.isOffCampusIndicator()) {
if (StringUtils.isBlank(location.getCampusCode())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_CAMPUS);
valid &= false;
}
if (StringUtils.isBlank(location.getBuildingCode())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_BUILDING);
valid &= false;
}
if (StringUtils.isBlank(location.getBuildingRoomNumber())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_ROOM);
valid &= false;
}
}
return valid;
}
protected boolean validateAccountsPayableItem(AccountsPayableItem apItem) {
boolean valid = true;
valid &= validatePurapItemCapitalAsset(apItem, (AssetTransactionType) apItem.getCapitalAssetTransactionType());
return valid;
}
// end of methods for purap
/**
* @see org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService#validateFinancialProcessingData(org.kuali.kfs.sys.document.AccountingDocument,
* org.kuali.kfs.fp.businessobject.CapitalAssetInformation)
* @param accountingDocument and capitalAssetInformation
* @return True if the FinancialProcessingData is valid.
*/
public boolean validateFinancialProcessingData(AccountingDocument accountingDocument, CapitalAssetInformation capitalAssetInformation) {
boolean valid = true;
// Check if we need to collect cams data
String dataEntryExpected = this.getCapitalAssetObjectSubTypeLinesFlag(accountingDocument);
if (StringUtils.isBlank(dataEntryExpected)) {
// Data is not expected
if (!isCapitalAssetInformationBlank(capitalAssetInformation)) {
// If no parameter was found or determined that data shouldn't be collected, give error if data was entered
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_NUMBER, CabKeyConstants.CapitalAssetInformation.ERROR_ASSET_DO_NOT_ENTER_ANY_DATA);
return false;
}
else {
// No data to be collected and no data entered. Hence no error
return true;
}
}
else {
// Data is expected
if (isCapitalAssetInformationBlank(capitalAssetInformation)) {
// No data is entered
if (isCapitalAssetDataRequired(accountingDocument, dataEntryExpected)) {
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_NUMBER, CabKeyConstants.CapitalAssetInformation.ERROR_ASSET_REQUIRE_DATA_ENTRY);
return false;
}
else
return true;
}
else if (!isNewAssetBlank(capitalAssetInformation) && !canCreateNewAsset(accountingDocument, dataEntryExpected)) {
// No allow to create new capital asset
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_QUANTITY, CabKeyConstants.CapitalAssetInformation.ERROR_ASSET_UPDATE_ALLOW_ONLY);
return false;
}
else if (!isNewAssetBlank(capitalAssetInformation) && !isUpdateAssetBlank(capitalAssetInformation)) {
// Data exists on both crate new asset and update asset, give error
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_NUMBER, CabKeyConstants.CapitalAssetInformation.ERROR_ASSET_NEW_OR_UPDATE_ONLY);
return false;
}
}
if (!isUpdateAssetBlank(capitalAssetInformation)) {
// Validate update Asset information
valid = validateUpdateCapitalAssetField(capitalAssetInformation, accountingDocument);
}
else {
// Validate New Asset information
valid = checkNewCapitalAssetFieldsExist(capitalAssetInformation);
if (valid) {
valid = validateNewCapitalAssetFields(capitalAssetInformation);
}
}
return valid;
}
/**
* This method...
*
* @param accountingDocument
* @return getCapitalAssetObjectSubTypeLinesFlag = "" ==> no assetObjectSubType code F ==> assetObjectSubType code on source
* lines T ==> assetObjectSubType code on target lines FT ==> assetObjectSubType code on both source and target lines
*/
protected String getCapitalAssetObjectSubTypeLinesFlag(AccountingDocument accountingDocument) {
List<String> financialProcessingCapitalObjectSubTypes = this.getParameterService().getParameterValues(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, CabParameterConstants.CapitalAsset.FINANCIAL_PROCESSING_CAPITAL_OBJECT_SUB_TYPES);
String getCapitalAssetObjectSubTypeLinesFlag = "";
// Check if SourceAccountingLine has objectSub type code
List<SourceAccountingLine> sAccountingLines = accountingDocument.getSourceAccountingLines();
for (SourceAccountingLine sourceAccountingLine : sAccountingLines) {
ObjectCode objectCode = sourceAccountingLine.getObjectCode();
if (ObjectUtils.isNull(objectCode)) {
break;
}
String objectSubTypeCode = objectCode.getFinancialObjectSubTypeCode();
if (financialProcessingCapitalObjectSubTypes.contains(objectSubTypeCode)) {
getCapitalAssetObjectSubTypeLinesFlag = KFSConstants.SOURCE_ACCT_LINE_TYPE_CODE;
break;
}
}
// Check if TargetAccountingLine has objectSub type code
List<TargetAccountingLine> tAccountingLines = accountingDocument.getTargetAccountingLines();
for (TargetAccountingLine targetAccountingLine : tAccountingLines) {
ObjectCode objectCode = targetAccountingLine.getObjectCode();
if (ObjectUtils.isNull(objectCode)) {
break;
}
String objectSubTypeCode = objectCode.getFinancialObjectSubTypeCode();
if (financialProcessingCapitalObjectSubTypes.contains(objectSubTypeCode)) {
getCapitalAssetObjectSubTypeLinesFlag = getCapitalAssetObjectSubTypeLinesFlag.equals(KFSConstants.SOURCE_ACCT_LINE_TYPE_CODE) ? KFSConstants.SOURCE_ACCT_LINE_TYPE_CODE + KFSConstants.TARGET_ACCT_LINE_TYPE_CODE : KFSConstants.TARGET_ACCT_LINE_TYPE_CODE;
break;
}
}
return getCapitalAssetObjectSubTypeLinesFlag;
}
/**
* @see org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService#hasCapitalAssetObjectSubType(org.kuali.kfs.sys.document.AccountingDocument)
*/
public boolean hasCapitalAssetObjectSubType(AccountingDocument accountingDocument) {
boolean hasCapitalAssetObjectSubType = false;
if (!getCapitalAssetObjectSubTypeLinesFlag(accountingDocument).equals("N"))
hasCapitalAssetObjectSubType = true;
return hasCapitalAssetObjectSubType;
}
/**
* if the capital asset data is required for this transaction
*
* @param accountingDocument and dataEntryExpected
* @return boolean false then the capital asset information is not required
*/
private boolean isCapitalAssetDataRequired(AccountingDocument accountingDocument, String dataEntryExpected) {
boolean isCapitalAssetDataRequired = true;
String accountingDocumentType = accountingDocument.getDocumentHeader().getWorkflowDocument().getDocumentType();
// if (isDocumentTypeRestricted(accountingDocument) ||
// accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.INTERNAL_BILLING)) {
if (accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.INTERNAL_BILLING)) {
if (dataEntryExpected.equals(KFSConstants.SOURCE_ACCT_LINE_TYPE_CODE + KFSConstants.TARGET_ACCT_LINE_TYPE_CODE))
isCapitalAssetDataRequired = false;
}
return isCapitalAssetDataRequired;
}
/**
* if this transaction can create new asset
*
* @param accountingDocument and dataEntryExpected
* @return
*/
private boolean canCreateNewAsset(AccountingDocument accountingDocument, String dataEntryExpected) {
boolean canCreateNewAsset = true;
String accountingDocumentType = accountingDocument.getDocumentHeader().getWorkflowDocument().getDocumentType();
if (accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.CASH_RECEIPT)) {
canCreateNewAsset = false;
}
else {
if (isDocumentTypeRestricted(accountingDocument) && dataEntryExpected.equals(KFSConstants.SOURCE_ACCT_LINE_TYPE_CODE))
canCreateNewAsset = false;
}
return canCreateNewAsset;
}
/**
* if this document is restricted
*
* @param accountingDocument
* @return boolean true then this document is restricted
*/
private boolean isDocumentTypeRestricted(AccountingDocument accountingDocument) {
boolean isDocumentTypeRestricted = false;
String accountingDocumentType = accountingDocument.getDocumentHeader().getWorkflowDocument().getDocumentType();
if (accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.GENERAL_ERROR_CORRECTION) || accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.YEAR_END_GENERAL_ERROR_CORRECTION))
isDocumentTypeRestricted = true;
if (accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.DISTRIBUTION_OF_INCOME_AND_EXPENSE) || accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.YEAR_END_DISTRIBUTION_OF_INCOME_AND_EXPENSE))
isDocumentTypeRestricted = true;
if (accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.SERVICE_BILLING))
isDocumentTypeRestricted = true;
return isDocumentTypeRestricted;
}
/**
* To see if capitalAssetInformation is blank
*
* @param capitalAssetInformation
* @return boolean false if the asset is not blank
*/
private boolean isCapitalAssetInformationBlank(CapitalAssetInformation capitalAssetInformation) {
boolean isBlank = true;
if (!isNewAssetBlank(capitalAssetInformation) || !isUpdateAssetBlank(capitalAssetInformation)) {
isBlank = false;
}
return isBlank;
}
/**
* To check if data exists on create new asset
*
* @param capitalAssetInformation
* @return boolean false if the new asset is not blank
*/
private boolean isNewAssetBlank(CapitalAssetInformation capitalAssetInformation) {
boolean isBlank = true;
if (ObjectUtils.isNotNull(capitalAssetInformation.getCapitalAssetTypeCode()) || ObjectUtils.isNotNull(capitalAssetInformation.getVendorName()) || ObjectUtils.isNotNull(capitalAssetInformation.getCapitalAssetQuantity()) || ObjectUtils.isNotNull(capitalAssetInformation.getCapitalAssetManufacturerName()) || ObjectUtils.isNotNull(capitalAssetInformation.getCapitalAssetManufacturerModelNumber()) || ObjectUtils.isNotNull(capitalAssetInformation.getCapitalAssetDescription())) {
isBlank = false;
}
return isBlank;
}
/**
* To check if data exists on update asset
*
* @param capitalAssetInformation
* @return boolean false if the update asset is not blank
*/
private boolean isUpdateAssetBlank(CapitalAssetInformation capitalAssetInformation) {
boolean isBlank = true;
if (ObjectUtils.isNotNull(capitalAssetInformation.getCapitalAssetNumber())) {
isBlank = false;
}
return isBlank;
}
/**
* To validate if the asset is active
*
* @param capitalAssetManagementAsset the asset to be validated
* @return boolean false if the asset is not active
*/
private boolean validateUpdateCapitalAssetField(CapitalAssetInformation capitalAssetInformation, AccountingDocument accountingDocument) {
boolean valid = true;
Map<String, String> params = new HashMap<String, String>();
params.put(KFSPropertyConstants.CAPITAL_ASSET_NUMBER, capitalAssetInformation.getCapitalAssetNumber().toString());
Asset asset = (Asset) this.getBusinessObjectService().findByPrimaryKey(Asset.class, params);
List<Long> assetNumbers = new ArrayList<Long>();
assetNumbers.add(capitalAssetInformation.getCapitalAssetNumber());
if (ObjectUtils.isNull(asset)) {
valid = false;
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.CAPITAL_ASSET_NUMBER);
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_NUMBER, KFSKeyConstants.ERROR_EXISTENCE, label);
}
else if (!(this.getAssetService().isCapitalAsset(asset) && !this.getAssetService().isAssetRetired(asset))) {
// check asset status must be capital asset active.
valid = false;
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_NUMBER, CabKeyConstants.CapitalAssetInformation.ERROR_ASSET_ACTIVE_CAPITAL_ASSET_REQUIRED);
}
else {
String documentNumber = accountingDocument.getDocumentNumber();
String documentType = getDocumentTypeName(accountingDocument);
if (getCapitalAssetManagementModuleService().isFpDocumentEligibleForAssetLock(accountingDocument, documentType) && getCapitalAssetManagementModuleService().isAssetLocked(assetNumbers, documentType, documentNumber)) {
valid = false;
}
}
return valid;
}
/**
* Check if all required fields exist on new asset
*
* @param capitalAssetInformation the fields of add asset to be checked
* @return boolean false if a required field is missing
*/
private boolean checkNewCapitalAssetFieldsExist(CapitalAssetInformation capitalAssetInformation) {
boolean valid = true;
if (StringUtils.isBlank(capitalAssetInformation.getCapitalAssetTypeCode())) {
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.CAPITAL_ASSET_TYPE_CODE);
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_TYPE_CODE, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
if (capitalAssetInformation.getCapitalAssetQuantity() == null || capitalAssetInformation.getCapitalAssetQuantity() <= 0) {
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.CAPITAL_ASSET_QUANTITY);
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_QUANTITY, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
if (StringUtils.isBlank(capitalAssetInformation.getVendorName())) {
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.VENDOR_NAME);
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.VENDOR_NAME, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
if (StringUtils.isBlank(capitalAssetInformation.getCapitalAssetManufacturerName())) {
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.CAPITAL_ASSET_MANUFACTURE_NAME);
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_MANUFACTURE_NAME, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
if (StringUtils.isBlank(capitalAssetInformation.getCapitalAssetDescription())) {
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, CamsPropertyConstants.Asset.CAPITAL_ASSET_DESCRIPTION);
GlobalVariables.getErrorMap().putError(CamsPropertyConstants.Asset.CAPITAL_ASSET_DESCRIPTION, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
int index = 0;
List<CapitalAssetInformationDetail> capitalAssetInformationDetails = capitalAssetInformation.getCapitalAssetInformationDetails();
for (CapitalAssetInformationDetail dtl : capitalAssetInformationDetails) {
String errorPathPrefix = KFSPropertyConstants.DOCUMENT + "." + KFSPropertyConstants.CAPITAL_ASSET_INFORMATION + "." + KFSPropertyConstants.CAPITAL_ASSET_INFORMATION_DETAILS;
if (StringUtils.isBlank(dtl.getCampusCode())) {
String label = this.getDataDictionaryService().getAttributeLabel(Campus.class, KFSPropertyConstants.CAMPUS_CODE);
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.CAMPUS_CODE, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
if (StringUtils.isBlank(dtl.getBuildingCode())) {
String label = this.getDataDictionaryService().getAttributeLabel(Building.class, KFSPropertyConstants.BUILDING_CODE);
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.BUILDING_CODE, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
if (StringUtils.isBlank(dtl.getBuildingRoomNumber())) {
String label = this.getDataDictionaryService().getAttributeLabel(Room.class, KFSPropertyConstants.BUILDING_ROOM_NUMBER);
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.BUILDING_ROOM_NUMBER, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
index++;
}
return valid;
}
/**
* To validate new asset information
*
* @param capitalAssetInformation the information of add asset to be validated
* @return boolean false if data is incorrect
*/
private boolean validateNewCapitalAssetFields(CapitalAssetInformation capitalAssetInformation) {
boolean valid = true;
Map<String, String> params = new HashMap<String, String>();
params.put(KFSPropertyConstants.CAPITAL_ASSET_TYPE_CODE, capitalAssetInformation.getCapitalAssetTypeCode().toString());
AssetType assetType = (AssetType) this.getBusinessObjectService().findByPrimaryKey(AssetType.class, params);
if (ObjectUtils.isNull(assetType)) {
valid = false;
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.CAPITAL_ASSET_TYPE_CODE);
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_TYPE_CODE, KFSKeyConstants.ERROR_EXISTENCE, label);
}
int index = 0;
List<CapitalAssetInformationDetail> capitalAssetInformationDetails = capitalAssetInformation.getCapitalAssetInformationDetails();
for (CapitalAssetInformationDetail dtl : capitalAssetInformationDetails) {
// We have to explicitly call this DD service to uppercase each field. This may not be the best place and maybe form
// populate
// is a better place but we CAMS team don't own FP document. This is the best we can do for now.
SpringContext.getBean(BusinessObjectDictionaryService.class).performForceUppercase(dtl);
String errorPathPrefix = KFSPropertyConstants.DOCUMENT + "." + KFSPropertyConstants.CAPITAL_ASSET_INFORMATION + "." + KFSPropertyConstants.CAPITAL_ASSET_INFORMATION_DETAILS;
if (StringUtils.isNotBlank(dtl.getCapitalAssetTagNumber()) && !dtl.getCapitalAssetTagNumber().equalsIgnoreCase(CamsConstants.Asset.NON_TAGGABLE_ASSET)) {
if (isTagNumberDuplicate(capitalAssetInformationDetails, dtl)) {
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.CAPITAL_ASSET_TAG_NUMBER, CamsKeyConstants.AssetGlobal.ERROR_CAMPUS_TAG_NUMBER_DUPLICATE, dtl.getCapitalAssetTagNumber());
valid = false;
}
}
Map<String, Object> criteria = new HashMap<String, Object>();
criteria.put(KFSPropertyConstants.CAMPUS_CODE, dtl.getCampusCode());
Campus campus = (Campus) SpringContext.getBean(KualiModuleService.class).getResponsibleModuleService(Campus.class).getExternalizableBusinessObject(Campus.class, criteria);
if (ObjectUtils.isNull(campus)) {
valid = false;
String label = this.getDataDictionaryService().getAttributeLabel(Campus.class, KFSPropertyConstants.CAMPUS_CODE);
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.CAMPUS_CODE, KFSKeyConstants.ERROR_EXISTENCE, label);
}
params = new HashMap<String, String>();
params.put(KFSPropertyConstants.CAMPUS_CODE, dtl.getCampusCode());
params.put(KFSPropertyConstants.BUILDING_CODE, dtl.getBuildingCode());
Building building = (Building) this.getBusinessObjectService().findByPrimaryKey(Building.class, params);
if (ObjectUtils.isNull(building)) {
valid = false;
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.BUILDING_CODE, CamsKeyConstants.AssetLocationGlobal.ERROR_INVALID_BUILDING_CODE, dtl.getBuildingCode(), dtl.getCampusCode());
}
params = new HashMap<String, String>();
params.put(KFSPropertyConstants.CAMPUS_CODE, dtl.getCampusCode());
params.put(KFSPropertyConstants.BUILDING_CODE, dtl.getBuildingCode());
params.put(KFSPropertyConstants.BUILDING_ROOM_NUMBER, dtl.getBuildingRoomNumber());
Room room = (Room) this.getBusinessObjectService().findByPrimaryKey(Room.class, params);
if (ObjectUtils.isNull(room)) {
valid = false;
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.BUILDING_ROOM_NUMBER, CamsKeyConstants.AssetLocationGlobal.ERROR_INVALID_ROOM_NUMBER, dtl.getBuildingRoomNumber(), dtl.getBuildingCode(), dtl.getCampusCode());
}
index++;
}
return valid;
}
/**
* To check if the tag number is duplicate or in use
*
* @param capitalAssetInformation, capitalAssetInformationDetail
* @return boolean false if data is duplicate or in use
*/
private boolean isTagNumberDuplicate(List<CapitalAssetInformationDetail> capitalAssetInformationDetails, CapitalAssetInformationDetail dtl) {
boolean duplicateTag = false;
int tagCounter = 0;
if (!this.getAssetService().findActiveAssetsMatchingTagNumber(dtl.getCapitalAssetTagNumber()).isEmpty()) {
// Tag number is already in use
duplicateTag = true;
}
else {
for (CapitalAssetInformationDetail capitalAssetInfoDetl : capitalAssetInformationDetails) {
if (capitalAssetInfoDetl.getCapitalAssetTagNumber().equalsIgnoreCase(dtl.getCapitalAssetTagNumber().toString())) {
tagCounter++;
}
}
if (tagCounter > 1) {
// Tag number already exists in the collection
duplicateTag = true;
}
}
return duplicateTag;
}
/**
* @see org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService#notifyRouteStatusChange(java.lang.String,
* java.lang.String)
*/
public void notifyRouteStatusChange(DocumentHeader documentHeader) {
KualiWorkflowDocument workflowDocument = documentHeader.getWorkflowDocument();
String documentNumber = documentHeader.getDocumentNumber();
String documentType = workflowDocument.getDocumentType();
if (workflowDocument.stateIsCanceled() || workflowDocument.stateIsDisapproved()) {
// release CAB line items
activateCabPOLines(documentNumber);
activateCabGlLines(documentNumber);
}
if (workflowDocument.stateIsProcessed()) {
// update CAB GL lines if fully processed
updatePOLinesStatusAsProcessed(documentNumber);
updateGlLinesStatusAsProcessed(documentNumber);
// report asset numbers to PO
Integer poId = getPurchaseOrderIdentifier(documentNumber);
if (poId != null) {
List<Long> assetNumbers = null;
if (DocumentTypeName.ASSET_ADD_GLOBAL.equalsIgnoreCase(documentType)) {
assetNumbers = getAssetNumbersFromAssetGlobal(documentNumber);
}
else if (DocumentTypeName.ASSET_PAYMENT.equalsIgnoreCase(documentType)) {
assetNumbers = getAssetNumbersFromAssetPayment(documentNumber);
}
if (!assetNumbers.isEmpty()) {
String noteText = buildNoteTextForPurApDoc(documentType, assetNumbers);
SpringContext.getBean(PurchasingAccountsPayableModuleService.class).addAssignedAssetNumbers(poId, workflowDocument.getInitiatorPrincipalId(), noteText);
}
}
}
}
/**
* update cab non-PO lines status code for item/account/glEntry to 'P' as fully processed when possible
*
* @param documentNumber
*/
protected void updateGlLinesStatusAsProcessed(String documentNumber) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CabPropertyConstants.PurchasingAccountsPayableItemAsset.CAMS_DOCUMENT_NUMBER, documentNumber);
Collection<GeneralLedgerEntryAsset> matchingGlAssets = this.getBusinessObjectService().findMatching(GeneralLedgerEntryAsset.class, fieldValues);
if (matchingGlAssets != null && !matchingGlAssets.isEmpty()) {
for (GeneralLedgerEntryAsset generalLedgerEntryAsset : matchingGlAssets) {
GeneralLedgerEntry generalLedgerEntry = generalLedgerEntryAsset.getGeneralLedgerEntry();
// update gl status as processed
generalLedgerEntry.setActivityStatusCode(CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS);
this.getBusinessObjectService().save(generalLedgerEntry);
// release asset lock
if (isFpDocumentFullyProcessed(generalLedgerEntry)) {
getCapitalAssetManagementModuleService().deleteAssetLocks(generalLedgerEntry.getDocumentNumber(), null);
}
}
}
}
/**
* Check all generalLedgerEntries from the same FP document are fully processed.
*
* @param generalLedgerEntry
* @return
*/
protected boolean isFpDocumentFullyProcessed(GeneralLedgerEntry generalLedgerEntry) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CabPropertyConstants.GeneralLedgerEntry.DOCUMENT_NUMBER, generalLedgerEntry.getDocumentNumber());
Collection<GeneralLedgerEntry> matchingGlEntries = this.getBusinessObjectService().findMatching(GeneralLedgerEntry.class, fieldValues);
for (GeneralLedgerEntry glEntry : matchingGlEntries) {
if (!CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS.equals(glEntry.getActivityStatusCode())) {
return false;
}
}
return true;
}
/**
* update CAB PO lines status code for item/account/glEntry to 'P' as fully processed when possible
*
* @param documentNumber
*/
protected void updatePOLinesStatusAsProcessed(String documentNumber) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CabPropertyConstants.PurchasingAccountsPayableItemAsset.CAMS_DOCUMENT_NUMBER, documentNumber);
Collection<PurchasingAccountsPayableItemAsset> matchingAssets = this.getBusinessObjectService().findMatching(PurchasingAccountsPayableItemAsset.class, fieldValues);
if (matchingAssets != null && !matchingAssets.isEmpty()) {
// Map<Long, GeneralLedgerEntry> updateGlLines = new HashMap<Long, GeneralLedgerEntry>();
// update item and account status code to 'P' as fully processed
for (PurchasingAccountsPayableItemAsset itemAsset : matchingAssets) {
itemAsset.setActivityStatusCode(CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS);
for (PurchasingAccountsPayableLineAssetAccount assetAccount : itemAsset.getPurchasingAccountsPayableLineAssetAccounts()) {
assetAccount.setActivityStatusCode(CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS);
GeneralLedgerEntry generalLedgerEntry = assetAccount.getGeneralLedgerEntry();
// updateGlLines.put(generalLedgerEntry.getGeneralLedgerAccountIdentifier(), generalLedgerEntry);
if (isGlEntryFullyProcessed(generalLedgerEntry)) {
generalLedgerEntry.setActivityStatusCode(CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS);
this.getBusinessObjectService().save(generalLedgerEntry);
}
}
// update cab document status code to 'P' as all its items fully processed
PurchasingAccountsPayableDocument purapDocument = itemAsset.getPurchasingAccountsPayableDocument();
if (isDocumentFullyProcessed(purapDocument)) {
purapDocument.setActivityStatusCode(CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS);
}
this.getBusinessObjectService().save(purapDocument);
String lockingInformation = null;
PurchaseOrderDocument poDocument = getPurApInfoService().getCurrentDocumentForPurchaseOrderIdentifier(purapDocument.getPurchaseOrderIdentifier());
// Only individual system will lock on item line number. other system will using preq/cm doc nbr as the locking
// key
if (PurapConstants.CapitalAssetTabStrings.INDIVIDUAL_ASSETS.equalsIgnoreCase(poDocument.getCapitalAssetSystemTypeCode())) {
lockingInformation = itemAsset.getAccountsPayableLineItemIdentifier().toString();
}
// release the asset lock no matter if it's Asset global or Asset Payment since the CAB user can create Asset global
// doc even if Purap Asset numbers existing.
if (isAccountsPayableItemLineFullyProcessed(purapDocument, lockingInformation)) {
getCapitalAssetManagementModuleService().deleteAssetLocks(purapDocument.getDocumentNumber(), lockingInformation);
}
}
}
}
/**
* If lockingInformation is not empty, check all item lines from the same PurAp item are fully processed. If lockingInformation
* is empty, we check all items from the same PREQ/CM document processed as fully processed.
*
* @param itemAsset
* @return
*/
protected boolean isAccountsPayableItemLineFullyProcessed(PurchasingAccountsPayableDocument purapDocument, String lockingInformation) {
for (PurchasingAccountsPayableItemAsset item : purapDocument.getPurchasingAccountsPayableItemAssets()) {
if ((StringUtils.isBlank(lockingInformation) && !CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS.equals(item.getActivityStatusCode())) || (StringUtils.isNotBlank(lockingInformation) && item.getAccountsPayableLineItemIdentifier().equals(lockingInformation) && !CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS.equals(item.getActivityStatusCode()))) {
return false;
}
}
return true;
}
/**
* Check if Gl Entry related accounts are fully processed
*
* @param glEntry
* @return
*/
protected boolean isGlEntryFullyProcessed(GeneralLedgerEntry glEntry) {
for (PurchasingAccountsPayableLineAssetAccount account : glEntry.getPurApLineAssetAccounts()) {
if (!CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS.equalsIgnoreCase(account.getActivityStatusCode())) {
return false;
}
}
return true;
}
/**
* Check if PurApDocument related items are fully processed.
*
* @param purapDocument
* @return
*/
protected boolean isDocumentFullyProcessed(PurchasingAccountsPayableDocument purapDocument) {
for (PurchasingAccountsPayableItemAsset item : purapDocument.getPurchasingAccountsPayableItemAssets()) {
if (!CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS.equalsIgnoreCase(item.getActivityStatusCode())) {
return false;
}
}
return true;
}
/**
* Build the appropriate note text being set to the purchase order document.
*
* @param documentType
* @param assetNumbers
* @return
*/
private String buildNoteTextForPurApDoc(String documentType, List<Long> assetNumbers) {
StringBuffer noteText = new StringBuffer();
if (DocumentTypeName.ASSET_ADD_GLOBAL.equalsIgnoreCase(documentType)) {
noteText.append("Asset Numbers have been created for this document: ");
}
else {
noteText.append("Existing Asset Numbers have been applied for this document: ");
}
for (int i = 0; i < assetNumbers.size(); i++) {
noteText.append(assetNumbers.get(i).toString());
if (i < assetNumbers.size() - 1) {
noteText.append(", ");
}
}
return noteText.toString();
}
/**
* Acquire asset numbers from CAMS asset payment document.
*
* @param documentNumber
* @param assetNumbers
*/
private List<Long> getAssetNumbersFromAssetGlobal(String documentNumber) {
List<Long> assetNumbers = new ArrayList<Long>();
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CamsPropertyConstants.AssetGlobalDetail.DOCUMENT_NUMBER, documentNumber);
Collection<AssetGlobalDetail> assetGlobalDetails = this.getBusinessObjectService().findMatching(AssetGlobalDetail.class, fieldValues);
for (AssetGlobalDetail detail : assetGlobalDetails) {
assetNumbers.add(detail.getCapitalAssetNumber());
}
return assetNumbers;
}
/**
* Acquire asset numbers from CAMS asset global document.
*
* @param documentNumber
* @param assetNumbers
*/
private List<Long> getAssetNumbersFromAssetPayment(String documentNumber) {
List<Long> assetNumbers = new ArrayList<Long>();
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CamsPropertyConstants.DOCUMENT_NUMBER, documentNumber);
Collection<AssetPaymentAssetDetail> paymentAssetDetails = this.getBusinessObjectService().findMatching(AssetPaymentAssetDetail.class, fieldValues);
for (AssetPaymentAssetDetail detail : paymentAssetDetails) {
if (ObjectUtils.isNotNull(detail.getAsset())) {
assetNumbers.add(detail.getCapitalAssetNumber());
}
}
return assetNumbers;
}
/**
* Query PurchasingAccountsPayableItemAsset and return the purchaseOrderIdentifier if the given documentNumber is initiated from
* the PurAp line.
*
* @param documentNumber
* @return
*/
private Integer getPurchaseOrderIdentifier(String camsDocumentNumber) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CabPropertyConstants.PurchasingAccountsPayableItemAsset.CAMS_DOCUMENT_NUMBER, camsDocumentNumber);
Collection<PurchasingAccountsPayableItemAsset> matchingItems = this.getBusinessObjectService().findMatching(PurchasingAccountsPayableItemAsset.class, fieldValues);
for (PurchasingAccountsPayableItemAsset item : matchingItems) {
if (ObjectUtils.isNull(item.getPurchasingAccountsPayableDocument())) {
item.refreshReferenceObject(CabPropertyConstants.PurchasingAccountsPayableItemAsset.PURCHASING_ACCOUNTS_PAYABLE_DOCUMENT);
}
return item.getPurchasingAccountsPayableDocument().getPurchaseOrderIdentifier();
}
return null;
}
/**
* @see org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService#getCurrentPurchaseOrderDocumentNumber(java.lang.String)
*/
public String getCurrentPurchaseOrderDocumentNumber(String camsDocumentNumber) {
Integer poId = getPurchaseOrderIdentifier(camsDocumentNumber);
if (poId != null) {
PurchaseOrderDocument poDocument = getPurApInfoService().getCurrentDocumentForPurchaseOrderIdentifier(poId);
if (ObjectUtils.isNotNull(poDocument)) {
return poDocument.getDocumentNumber();
}
}
return null;
}
/**
* Activates CAB GL Lines
*
* @param documentNumber String
*/
protected void activateCabGlLines(String documentNumber) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CabPropertyConstants.PurchasingAccountsPayableItemAsset.CAMS_DOCUMENT_NUMBER, documentNumber);
Collection<GeneralLedgerEntryAsset> matchingGlAssets = this.getBusinessObjectService().findMatching(GeneralLedgerEntryAsset.class, fieldValues);
if (matchingGlAssets != null && !matchingGlAssets.isEmpty()) {
for (GeneralLedgerEntryAsset generalLedgerEntryAsset : matchingGlAssets) {
GeneralLedgerEntry generalLedgerEntry = generalLedgerEntryAsset.getGeneralLedgerEntry();
generalLedgerEntry.setTransactionLedgerSubmitAmount(KualiDecimal.ZERO);
generalLedgerEntry.setActivityStatusCode(CabConstants.ActivityStatusCode.NEW);
this.getBusinessObjectService().save(generalLedgerEntry);
this.getBusinessObjectService().delete(generalLedgerEntryAsset);
}
}
}
/**
* Activates PO Lines
*
* @param documentNumber String
*/
protected void activateCabPOLines(String documentNumber) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CabPropertyConstants.PurchasingAccountsPayableItemAsset.CAMS_DOCUMENT_NUMBER, documentNumber);
Collection<PurchasingAccountsPayableItemAsset> matchingPoAssets = this.getBusinessObjectService().findMatching(PurchasingAccountsPayableItemAsset.class, fieldValues);
if (matchingPoAssets != null && !matchingPoAssets.isEmpty()) {
for (PurchasingAccountsPayableItemAsset itemAsset : matchingPoAssets) {
PurchasingAccountsPayableDocument purapDocument = itemAsset.getPurchasingAccountsPayableDocument();
purapDocument.setActivityStatusCode(CabConstants.ActivityStatusCode.MODIFIED);
this.getBusinessObjectService().save(purapDocument);
itemAsset.setActivityStatusCode(CabConstants.ActivityStatusCode.MODIFIED);
this.getBusinessObjectService().save(itemAsset);
List<PurchasingAccountsPayableLineAssetAccount> lineAssetAccounts = itemAsset.getPurchasingAccountsPayableLineAssetAccounts();
for (PurchasingAccountsPayableLineAssetAccount assetAccount : lineAssetAccounts) {
assetAccount.setActivityStatusCode(CabConstants.ActivityStatusCode.MODIFIED);
this.getBusinessObjectService().save(assetAccount);
GeneralLedgerEntry generalLedgerEntry = assetAccount.getGeneralLedgerEntry();
KualiDecimal submitAmount = generalLedgerEntry.getTransactionLedgerSubmitAmount();
if (submitAmount == null) {
submitAmount = KualiDecimal.ZERO;
}
submitAmount = submitAmount.subtract(assetAccount.getItemAccountTotalAmount());
generalLedgerEntry.setTransactionLedgerSubmitAmount(submitAmount);
generalLedgerEntry.setActivityStatusCode(CabConstants.ActivityStatusCode.MODIFIED);
this.getBusinessObjectService().save(generalLedgerEntry);
}
}
}
}
/**
* gets the document type based on the instance of a class
*
* @param accountingDocument
* @return
*/
private String getDocumentTypeName(AccountingDocument accountingDocument) {
String documentTypeName = null;
if (accountingDocument instanceof YearEndGeneralErrorCorrectionDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.YEAR_END_GENERAL_ERROR_CORRECTION;
else if (accountingDocument instanceof YearEndDistributionOfIncomeAndExpenseDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.YEAR_END_DISTRIBUTION_OF_INCOME_AND_EXPENSE;
else if (accountingDocument instanceof ServiceBillingDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.SERVICE_BILLING;
else if (accountingDocument instanceof GeneralErrorCorrectionDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.GENERAL_ERROR_CORRECTION;
else if (accountingDocument instanceof CashReceiptDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.CASH_RECEIPT;
else if (accountingDocument instanceof DistributionOfIncomeAndExpenseDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.DISTRIBUTION_OF_INCOME_AND_EXPENSE;
else if (accountingDocument instanceof InternalBillingDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.INTERNAL_BILLING;
else if (accountingDocument instanceof ProcurementCardDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.PROCUREMENT_CARD;
else
throw new RuntimeException("Invalid FP document type.");
return documentTypeName;
}
public ParameterService getParameterService() {
return SpringContext.getBean(ParameterService.class);
}
public BusinessObjectService getBusinessObjectService() {
return SpringContext.getBean(BusinessObjectService.class);
}
public DataDictionaryService getDataDictionaryService() {
return SpringContext.getBean(DataDictionaryService.class);
}
public AssetService getAssetService() {
return SpringContext.getBean(AssetService.class);
}
public KualiModuleService getKualiModuleService() {
return SpringContext.getBean(KualiModuleService.class);
}
public CapitalAssetManagementModuleService getCapitalAssetManagementModuleService() {
return SpringContext.getBean(CapitalAssetManagementModuleService.class);
}
private PurApInfoService getPurApInfoService() {
return SpringContext.getBean(PurApInfoService.class);
}
}
| work/src/org/kuali/kfs/module/cab/service/impl/CapitalAssetBuilderModuleServiceImpl.java | /*
* Copyright 2008 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kfs.module.cab.service.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.kuali.kfs.coa.businessobject.ObjectCode;
import org.kuali.kfs.fp.businessobject.CapitalAssetInformation;
import org.kuali.kfs.fp.businessobject.CapitalAssetInformationDetail;
import org.kuali.kfs.fp.document.CashReceiptDocument;
import org.kuali.kfs.fp.document.DistributionOfIncomeAndExpenseDocument;
import org.kuali.kfs.fp.document.GeneralErrorCorrectionDocument;
import org.kuali.kfs.fp.document.InternalBillingDocument;
import org.kuali.kfs.fp.document.ProcurementCardDocument;
import org.kuali.kfs.fp.document.ServiceBillingDocument;
import org.kuali.kfs.fp.document.YearEndDistributionOfIncomeAndExpenseDocument;
import org.kuali.kfs.fp.document.YearEndGeneralErrorCorrectionDocument;
import org.kuali.kfs.integration.cab.CapitalAssetBuilderAssetTransactionType;
import org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService;
import org.kuali.kfs.integration.cam.CapitalAssetManagementModuleService;
import org.kuali.kfs.integration.purap.CapitalAssetLocation;
import org.kuali.kfs.integration.purap.CapitalAssetSystem;
import org.kuali.kfs.integration.purap.ExternalPurApItem;
import org.kuali.kfs.integration.purap.ItemCapitalAsset;
import org.kuali.kfs.integration.purap.PurchasingAccountsPayableModuleService;
import org.kuali.kfs.module.cab.CabConstants;
import org.kuali.kfs.module.cab.CabKeyConstants;
import org.kuali.kfs.module.cab.CabParameterConstants;
import org.kuali.kfs.module.cab.CabPropertyConstants;
import org.kuali.kfs.module.cab.businessobject.AssetTransactionType;
import org.kuali.kfs.module.cab.businessobject.GeneralLedgerEntry;
import org.kuali.kfs.module.cab.businessobject.GeneralLedgerEntryAsset;
import org.kuali.kfs.module.cab.businessobject.PurchasingAccountsPayableDocument;
import org.kuali.kfs.module.cab.businessobject.PurchasingAccountsPayableItemAsset;
import org.kuali.kfs.module.cab.businessobject.PurchasingAccountsPayableLineAssetAccount;
import org.kuali.kfs.module.cab.document.service.PurApInfoService;
import org.kuali.kfs.module.cam.CamsConstants;
import org.kuali.kfs.module.cam.CamsKeyConstants;
import org.kuali.kfs.module.cam.CamsPropertyConstants;
import org.kuali.kfs.module.cam.CamsConstants.DocumentTypeName;
import org.kuali.kfs.module.cam.businessobject.Asset;
import org.kuali.kfs.module.cam.businessobject.AssetGlobal;
import org.kuali.kfs.module.cam.businessobject.AssetGlobalDetail;
import org.kuali.kfs.module.cam.businessobject.AssetPaymentAssetDetail;
import org.kuali.kfs.module.cam.businessobject.AssetType;
import org.kuali.kfs.module.cam.document.service.AssetService;
import org.kuali.kfs.module.purap.PurapConstants;
import org.kuali.kfs.module.purap.PurapKeyConstants;
import org.kuali.kfs.module.purap.PurapParameterConstants;
import org.kuali.kfs.module.purap.PurapPropertyConstants;
import org.kuali.kfs.module.purap.businessobject.AccountsPayableItem;
import org.kuali.kfs.module.purap.businessobject.AvailabilityMatrix;
import org.kuali.kfs.module.purap.businessobject.PurApAccountingLine;
import org.kuali.kfs.module.purap.businessobject.PurApItem;
import org.kuali.kfs.module.purap.businessobject.PurchasingCapitalAssetItem;
import org.kuali.kfs.module.purap.businessobject.PurchasingItem;
import org.kuali.kfs.module.purap.businessobject.PurchasingItemBase;
import org.kuali.kfs.module.purap.businessobject.PurchasingItemCapitalAssetBase;
import org.kuali.kfs.module.purap.document.AccountsPayableDocument;
import org.kuali.kfs.module.purap.document.PurchaseOrderDocument;
import org.kuali.kfs.module.purap.document.PurchasingDocument;
import org.kuali.kfs.module.purap.document.RequisitionDocument;
import org.kuali.kfs.sys.KFSConstants;
import org.kuali.kfs.sys.KFSKeyConstants;
import org.kuali.kfs.sys.KFSPropertyConstants;
import org.kuali.kfs.sys.businessobject.AccountingLine;
import org.kuali.kfs.sys.businessobject.Building;
import org.kuali.kfs.sys.businessobject.Room;
import org.kuali.kfs.sys.businessobject.SourceAccountingLine;
import org.kuali.kfs.sys.businessobject.TargetAccountingLine;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.sys.document.AccountingDocument;
import org.kuali.kfs.sys.service.impl.KfsParameterConstants;
import org.kuali.rice.kns.bo.Campus;
import org.kuali.rice.kns.bo.DocumentHeader;
import org.kuali.rice.kns.bo.Parameter;
import org.kuali.rice.kns.datadictionary.AttributeDefinition;
import org.kuali.rice.kns.datadictionary.BusinessObjectEntry;
import org.kuali.rice.kns.service.BusinessObjectDictionaryService;
import org.kuali.rice.kns.service.BusinessObjectService;
import org.kuali.rice.kns.service.DataDictionaryService;
import org.kuali.rice.kns.service.DictionaryValidationService;
import org.kuali.rice.kns.service.KualiConfigurationService;
import org.kuali.rice.kns.service.KualiModuleService;
import org.kuali.rice.kns.service.ParameterService;
import org.kuali.rice.kns.util.GlobalVariables;
import org.kuali.rice.kns.util.KualiDecimal;
import org.kuali.rice.kns.util.ObjectUtils;
import org.kuali.rice.kns.workflow.service.KualiWorkflowDocument;
public class CapitalAssetBuilderModuleServiceImpl implements CapitalAssetBuilderModuleService {
private static Logger LOG = Logger.getLogger(CapitalAssetBuilderModuleService.class);
/**
* @see org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService#getAllAssetTransactionTypes()
*/
public List<CapitalAssetBuilderAssetTransactionType> getAllAssetTransactionTypes() {
Class<? extends CapitalAssetBuilderAssetTransactionType> assetTransactionTypeClass = this.getKualiModuleService().getResponsibleModuleService(CapitalAssetBuilderAssetTransactionType.class).getExternalizableBusinessObjectImplementation(CapitalAssetBuilderAssetTransactionType.class);
return (List<CapitalAssetBuilderAssetTransactionType>) this.getBusinessObjectService().findAll(assetTransactionTypeClass);
}
/**
* @see org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService#validatePurchasingAccountsPayableData(org.kuali.kfs.sys.document.AccountingDocument)
*/
public boolean validatePurchasingData(AccountingDocument accountingDocument) {
PurchasingDocument purchasingDocument = (PurchasingDocument) accountingDocument;
String documentType = (purchasingDocument instanceof RequisitionDocument) ? "REQUISITION" : "PURCHASE_ORDER";
if (PurapConstants.CapitalAssetSystemTypes.INDIVIDUAL.equals(purchasingDocument.getCapitalAssetSystemTypeCode())) {
return validateIndividualCapitalAssetSystemFromPurchasing(purchasingDocument.getCapitalAssetSystemStateCode(), purchasingDocument.getPurchasingCapitalAssetItems(), purchasingDocument.getChartOfAccountsCode(), documentType);
}
else if (PurapConstants.CapitalAssetSystemTypes.ONE_SYSTEM.equals(purchasingDocument.getCapitalAssetSystemTypeCode())) {
return validateOneSystemCapitalAssetSystemFromPurchasing(purchasingDocument.getCapitalAssetSystemStateCode(), purchasingDocument.getPurchasingCapitalAssetSystems(), purchasingDocument.getPurchasingCapitalAssetItems(), purchasingDocument.getChartOfAccountsCode(), documentType);
}
else if (PurapConstants.CapitalAssetSystemTypes.MULTIPLE.equals(purchasingDocument.getCapitalAssetSystemTypeCode())) {
return validateMultipleSystemsCapitalAssetSystemFromPurchasing(purchasingDocument.getCapitalAssetSystemStateCode(), purchasingDocument.getPurchasingCapitalAssetSystems(), purchasingDocument.getPurchasingCapitalAssetItems(), purchasingDocument.getChartOfAccountsCode(), documentType);
}
return false;
}
public boolean validateAccountsPayableData(AccountingDocument accountingDocument) {
AccountsPayableDocument apDocument = (AccountsPayableDocument) accountingDocument;
boolean valid = true;
for (PurApItem purApItem : apDocument.getItems()) {
AccountsPayableItem accountsPayableItem = (AccountsPayableItem) purApItem;
// only run on ap items that were line items (not additional charge items) and were cams items
if ((!accountsPayableItem.getItemType().isAdditionalChargeIndicator()) && StringUtils.isNotEmpty(accountsPayableItem.getCapitalAssetTransactionTypeCode())) {
valid &= validateAccountsPayableItem(accountsPayableItem);
}
}
return valid;
}
/**
* Perform the item level capital asset validation to determine if the given document is not allowed to become an Automatic
* Purchase Order (APO). The APO is not allowed if any accounting strings on the document are using an object level indicated as
* capital via a parameter setting.
*/
public boolean doesAccountingLineFailAutomaticPurchaseOrderRules(AccountingLine accountingLine) {
PurApAccountingLine purapAccountingLine = (PurApAccountingLine) accountingLine;
purapAccountingLine.refreshNonUpdateableReferences();
return getParameterService().getParameterEvaluator(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, CabParameterConstants.CapitalAsset.CAPITAL_ASSET_OBJECT_LEVELS, purapAccountingLine.getObjectCode().getFinancialObjectLevelCode()).evaluationSucceeds();
}
/**
* Perform the document level capital asset validation to determine if the given document is not allowed to become an Automatic
* Purchase Order (APO). The APO is not allowed if any capital asset items exist on the document.
*/
public boolean doesDocumentFailAutomaticPurchaseOrderRules(AccountingDocument accountingDocument) {
PurchasingDocument purchasingDocument = (PurchasingDocument) accountingDocument;
return ObjectUtils.isNotNull(purchasingDocument.getPurchasingCapitalAssetItems()) && !purchasingDocument.getPurchasingCapitalAssetItems().isEmpty();
}
public boolean validateAutomaticPurchaseOrderRule(AccountingDocument accountingDocument) {
PurchasingDocument purchasingDocument = (PurchasingDocument) accountingDocument;
for (PurApItem item : purchasingDocument.getItems()) {
if (doesItemNeedCapitalAsset(item.getItemTypeCode(), item.getSourceAccountingLines())) {
// if the item needs capital asset, we cannot have an APO, so return false.
return false;
}
}
return true;
}
public boolean doesItemNeedCapitalAsset(String itemTypeCode, List accountingLines) {
if (PurapConstants.ItemTypeCodes.ITEM_TYPE_TRADE_IN_CODE.equals(itemTypeCode)) {
// FIXME: Chris - this should be true but need to look to see where itemline number is referenced first
// return true;
return false;
}// else
for (Iterator iterator = accountingLines.iterator(); iterator.hasNext();) {
PurApAccountingLine accountingLine = (PurApAccountingLine) iterator.next();
accountingLine.refreshReferenceObject(KFSPropertyConstants.OBJECT_CODE);
if (isCapitalAssetObjectCode(accountingLine.getObjectCode())) {
return true;
}
}
return false;
}
public boolean validateUpdateCAMSView(AccountingDocument accountingDocument) {
PurchasingDocument purchasingDocument = (PurchasingDocument) accountingDocument;
boolean valid = true;
for (PurApItem purapItem : purchasingDocument.getItems()) {
if (purapItem.getItemType().isLineItemIndicator()) {
if (!doesItemNeedCapitalAsset(purapItem.getItemTypeCode(), purapItem.getSourceAccountingLines())) {
PurchasingCapitalAssetItem camsItem = ((PurchasingItem) purapItem).getPurchasingCapitalAssetItem();
if (camsItem != null && !camsItem.isEmpty()) {
valid = false;
GlobalVariables.getErrorMap().putError("newPurchasingItemCapitalAssetLine", PurapKeyConstants.ERROR_CAPITAL_ASSET_ITEM_NOT_CAMS_ELIGIBLE, "in line item # " + purapItem.getItemLineNumber());
}
}
}
}
return valid;
}
public boolean validateAddItemCapitalAssetBusinessRules(ItemCapitalAsset asset) {
boolean valid = true;
if (asset.getCapitalAssetNumber() == null) {
valid = false;
}
else {
valid = SpringContext.getBean(DictionaryValidationService.class).isBusinessObjectValid((PurchasingItemCapitalAssetBase) asset);
}
if (!valid) {
String propertyName = "newPurchasingItemCapitalAssetLine." + PurapPropertyConstants.CAPITAL_ASSET_NUMBER;
String errorKey = PurapKeyConstants.ERROR_CAPITAL_ASSET_ASSET_NUMBER_MUST_BE_LONG_NOT_NULL;
GlobalVariables.getErrorMap().putError(propertyName, errorKey);
}
return valid;
}
public boolean warningObjectLevelCapital(AccountingDocument accountingDocument) {
org.kuali.kfs.module.purap.document.PurchasingAccountsPayableDocument purapDocument = (org.kuali.kfs.module.purap.document.PurchasingAccountsPayableDocument) accountingDocument;
for (PurApItem item : purapDocument.getItems()) {
if (item.getItemType().isLineItemIndicator() && item.getItemType().isQuantityBasedGeneralLedgerIndicator()) {
List<PurApAccountingLine> accounts = item.getSourceAccountingLines();
BigDecimal unitPrice = item.getItemUnitPrice();
String itemIdentifier = item.getItemIdentifierString();
for (PurApAccountingLine account : accounts) {
ObjectCode objectCode = account.getObjectCode();
if (!validateLevelCapitalAssetIndication(unitPrice, objectCode, itemIdentifier)) {
// found an error
return false;
}
}
}
}
// no need for error
return true;
}
/**
* Validates the capital asset field requirements based on system parameter and chart for individual system type. This also
* calls validations for quantity on locations equal quantity on line items, validates that the transaction type allows asset
* number and validates the non quantity driven allowed indicator.
*
* @param systemState
* @param capitalAssetItems
* @param chartCode
* @param documentType
* @return
*/
protected boolean validateIndividualCapitalAssetSystemFromPurchasing(String systemState, List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String documentType) {
// For Individual Asset system type, the List of CapitalAssetSystems in the input parameter for
// validateAllFieldRequirementsByChart
// should be null. So we'll pass in a null here.
boolean valid = validateAllFieldRequirementsByChart(systemState, null, capitalAssetItems, chartCode, documentType, PurapConstants.CapitalAssetSystemTypes.INDIVIDUAL);
valid &= validateQuantityOnLocationsEqualsQuantityOnItem(capitalAssetItems, PurapConstants.CapitalAssetSystemTypes.INDIVIDUAL, systemState);
valid &= validateIndividualSystemPurchasingTransactionTypesAllowingAssetNumbers(capitalAssetItems);
valid &= validateNonQuantityDrivenAllowedIndicatorAndTradeIn(capitalAssetItems);
return valid;
}
/**
* Validates the capital asset field requirements based on system parameter and chart for one system type. This also calls
* validations that the transaction type allows asset number and validates the non quantity driven allowed indicator.
*
* @param systemState
* @param capitalAssetSystems
* @param capitalAssetItems
* @param chartCode
* @param documentType
* @return
*/
protected boolean validateOneSystemCapitalAssetSystemFromPurchasing(String systemState, List<CapitalAssetSystem> capitalAssetSystems, List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String documentType) {
boolean valid = validateAllFieldRequirementsByChart(systemState, capitalAssetSystems, capitalAssetItems, chartCode, documentType, PurapConstants.CapitalAssetSystemTypes.ONE_SYSTEM);
String capitalAssetTransactionType = capitalAssetItems.get(0).getCapitalAssetTransactionTypeCode();
String prefix = "document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEMS + "[0].";
valid &= validatePurchasingTransactionTypesAllowingAssetNumbers(capitalAssetSystems.get(0), capitalAssetTransactionType, prefix);
valid &= validateNonQuantityDrivenAllowedIndicatorAndTradeIn(capitalAssetItems);
return valid;
}
/**
* Validates the capital asset field requirements based on system parameter and chart for multiple system type. This also calls
* validations that the transaction type allows asset number and validates the non quantity driven allowed indicator.
*
* @param systemState
* @param capitalAssetSystems
* @param capitalAssetItems
* @param chartCode
* @param documentType
* @return
*/
protected boolean validateMultipleSystemsCapitalAssetSystemFromPurchasing(String systemState, List<CapitalAssetSystem> capitalAssetSystems, List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String documentType) {
boolean valid = validateAllFieldRequirementsByChart(systemState, capitalAssetSystems, capitalAssetItems, chartCode, documentType, PurapConstants.CapitalAssetSystemTypes.MULTIPLE);
String capitalAssetTransactionType = capitalAssetItems.get(0).getCapitalAssetTransactionTypeCode();
String prefix = "document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEMS + "[0].";
valid &= validatePurchasingTransactionTypesAllowingAssetNumbers(capitalAssetSystems.get(0), capitalAssetTransactionType, prefix);
valid &= validateNonQuantityDrivenAllowedIndicatorAndTradeIn(capitalAssetItems);
return valid;
}
/**
* Validates all the field requirements by chart. It obtains a List of parameters where the parameter names are like
* "CHARTS_REQUIRING%" then loop through these parameters. If the system type is individual then invoke the
* validateFieldRequirementByChartForIndividualSystemType for further validation, otherwise invoke the
* validateFieldRequirementByChartForOneOrMultipleSystemType for further validation.
*
* @param systemState
* @param capitalAssetSystems
* @param capitalAssetItems
* @param chartCode
* @param documentType
* @param systemType
* @return
*/
protected boolean validateAllFieldRequirementsByChart(String systemState, List<CapitalAssetSystem> capitalAssetSystems, List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String documentType, String systemType) {
boolean valid = true;
List<Parameter> results = new ArrayList<Parameter>();
Map<String, String> criteria = new HashMap<String, String>();
criteria.put(CabPropertyConstants.Parameter.PARAMETER_NAMESPACE_CODE, CabConstants.Parameters.NAMESPACE);
criteria.put(CabPropertyConstants.Parameter.PARAMETER_DETAIL_TYPE_CODE, CabConstants.Parameters.DETAIL_TYPE_DOCUMENT);
criteria.put(CabPropertyConstants.Parameter.PARAMETER_NAME, "CHARTS_REQUIRING%" + documentType);
results.addAll(SpringContext.getBean(ParameterService.class).retrieveParametersGivenLookupCriteria(criteria));
for (Parameter parameter : results) {
if (ObjectUtils.isNotNull(parameter)) {
if (systemType.equals(PurapConstants.CapitalAssetSystemTypes.INDIVIDUAL)) {
valid &= validateFieldRequirementByChartForIndividualSystemType(systemState, capitalAssetItems, chartCode, parameter.getParameterName(), parameter.getParameterValue());
}
else {
valid &= validateFieldRequirementByChartForOneOrMultipleSystemType(systemType, systemState, capitalAssetSystems, capitalAssetItems, chartCode, parameter.getParameterName(), parameter.getParameterValue());
}
}
}
return valid;
}
/**
* Validates all the field requirements by chart. It obtains a List of parameters where the parameter names are like
* "CHARTS_REQUIRING%" then loop through these parameters. If any of the parameter's values is null, then return false
*
* @param accountingDocument
* @return
*/
public boolean validateAllFieldRequirementsByChart(AccountingDocument accountingDocument) {
PurchasingDocument purchasingDocument = (PurchasingDocument) accountingDocument;
String documentType = (purchasingDocument instanceof RequisitionDocument) ? "REQUISITION" : "PURCHASE_ORDER";
boolean valid = true;
List<Parameter> results = new ArrayList<Parameter>();
Map<String, String> criteria = new HashMap<String, String>();
criteria.put(CabPropertyConstants.Parameter.PARAMETER_NAMESPACE_CODE, CabConstants.Parameters.NAMESPACE);
criteria.put(CabPropertyConstants.Parameter.PARAMETER_DETAIL_TYPE_CODE, CabConstants.Parameters.DETAIL_TYPE_DOCUMENT);
criteria.put(CabPropertyConstants.Parameter.PARAMETER_NAME, "CHARTS_REQUIRING%" + documentType);
results.addAll(SpringContext.getBean(ParameterService.class).retrieveParametersGivenLookupCriteria(criteria));
for (Parameter parameter : results) {
if (ObjectUtils.isNotNull(parameter)) {
if (parameter.getParameterValue() != null) {
return false;
}
}
}
return valid;
}
/**
* Validates for PURCHASING_OBJECT_SUB_TYPES parameter. If at least one object code of any accounting line entered is of this
* type, then return false.
*
* @param accountingDocument
* @return
*/
public boolean validatePurchasingObjectSubType(AccountingDocument accountingDocument) {
boolean valid = true;
PurchasingDocument purchasingDocument = (PurchasingDocument) accountingDocument;
for (PurApItem item : purchasingDocument.getItems()) {
String itemTypeCode = item.getItemTypeCode();
List accountingLines = item.getSourceAccountingLines();
for (Iterator iterator = accountingLines.iterator(); iterator.hasNext();) {
PurApAccountingLine accountingLine = (PurApAccountingLine) iterator.next();
accountingLine.refreshReferenceObject(KFSPropertyConstants.OBJECT_CODE);
if (isCapitalAssetObjectCode(accountingLine.getObjectCode())) {
return false;
}
}
}
return valid;
}
/**
* Validates field requirement by chart for one or multiple system types.
*
* @param systemType
* @param systemState
* @param capitalAssetSystems
* @param capitalAssetItems
* @param chartCode
* @param parameterName
* @param parameterValueString
* @return
*/
protected boolean validateFieldRequirementByChartForOneOrMultipleSystemType(String systemType, String systemState, List<CapitalAssetSystem> capitalAssetSystems, List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String parameterName, String parameterValueString) {
boolean valid = true;
boolean needValidation = (this.getParameterService().getParameterEvaluator(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, parameterName, chartCode).evaluationSucceeds());
if (needValidation) {
if (parameterName.startsWith("CHARTS_REQUIRING_LOCATIONS_ADDRESS")) {
return validateCapitalAssetLocationAddressFieldsOneOrMultipleSystemType(capitalAssetSystems);
}
String mappedName = PurapConstants.CAMS_REQUIREDNESS_FIELDS.REQUIREDNESS_FIELDS_BY_PARAMETER_NAMES.get(parameterName);
if (mappedName != null) {
// Check the availability matrix here, if this field doesn't exist according to the avail. matrix, then no need
// to validate any further.
String availableValue = getValueFromAvailabilityMatrix(mappedName, systemType, systemState);
if (availableValue.equals(PurapConstants.CapitalAssetAvailability.NONE)) {
return true;
}
// capitalAssetTransactionType field is off the item
if (mappedName.equals(PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE_CODE)) {
String[] mappedNames = { PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS, mappedName };
for (PurchasingCapitalAssetItem item : capitalAssetItems) {
StringBuffer keyBuffer = new StringBuffer("document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "[" + new Integer(item.getPurchasingItem().getItemLineNumber().intValue() - 1) + "].");
valid &= validateFieldRequirementByChartHelper(item, ArrayUtils.subarray(mappedNames, 1, mappedNames.length), keyBuffer, item.getPurchasingItem().getItemLineNumber());
}
}
// all the other fields are off the system.
else {
List<String> mappedNamesList = new ArrayList<String>();
mappedNamesList.add(PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEMS);
if (mappedName.indexOf(".") < 0) {
mappedNamesList.add(mappedName);
}
else {
mappedNamesList.addAll(mappedNameSplitter(mappedName));
}
// For One system type, we would only have 1 CapitalAssetSystem, however, for multiple we may have more than
// one systems in the future. Either way, this for loop should allow both the one system and multiple system
// types to work fine.
int count = 0;
for (CapitalAssetSystem system : capitalAssetSystems) {
StringBuffer keyBuffer = new StringBuffer("document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEMS + "[" + new Integer(count) + "].");
valid &= validateFieldRequirementByChartHelper(system, ArrayUtils.subarray(mappedNamesList.toArray(), 1, mappedNamesList.size()), keyBuffer, null);
count++;
}
}
}
}
return valid;
}
/**
* Validates the field requirement by chart for individual system type.
*
* @param systemState
* @param capitalAssetItems
* @param chartCode
* @param parameterName
* @param parameterValueString
* @return
*/
protected boolean validateFieldRequirementByChartForIndividualSystemType(String systemState, List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String parameterName, String parameterValueString) {
boolean valid = true;
boolean needValidation = (this.getParameterService().getParameterEvaluator(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, parameterName, chartCode).evaluationSucceeds());
if (needValidation) {
if (parameterName.startsWith("CHARTS_REQUIRING_LOCATIONS_ADDRESS")) {
return validateCapitalAssetLocationAddressFieldsForIndividualSystemType(capitalAssetItems);
}
String mappedName = PurapConstants.CAMS_REQUIREDNESS_FIELDS.REQUIREDNESS_FIELDS_BY_PARAMETER_NAMES.get(parameterName);
if (mappedName != null) {
// Check the availability matrix here, if this field doesn't exist according to the avail. matrix, then no need
// to validate any further.
String availableValue = getValueFromAvailabilityMatrix(mappedName, PurapConstants.CapitalAssetSystemTypes.INDIVIDUAL, systemState);
if (availableValue.equals(PurapConstants.CapitalAssetAvailability.NONE)) {
return true;
}
// capitalAssetTransactionType field is off the item
List<String> mappedNamesList = new ArrayList<String>();
if (mappedName.equals(PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE_CODE)) {
mappedNamesList.add(PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS);
mappedNamesList.add(mappedName);
}
// all the other fields are off the system which is off the item
else {
mappedNamesList.add(PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS);
mappedNamesList.add(PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEM);
if (mappedName.indexOf(".") < 0) {
mappedNamesList.add(mappedName);
}
else {
mappedNamesList.addAll(mappedNameSplitter(mappedName));
}
}
// For Individual system type, we'll always iterate through the item, then if the field is off the system, we'll get
// it through
// the purchasingCapitalAssetSystem of the item.
for (PurchasingCapitalAssetItem item : capitalAssetItems) {
StringBuffer keyBuffer = new StringBuffer("document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "[" + new Integer(item.getPurchasingItem().getItemLineNumber().intValue() - 1) + "].");
valid &= validateFieldRequirementByChartHelper(item, ArrayUtils.subarray(mappedNamesList.toArray(), 1, mappedNamesList.size()), keyBuffer, item.getPurchasingItem().getItemLineNumber());
}
}
}
return valid;
}
/**
* Utility method to split a long String using the "." as the delimiter then add each of the array element into a List of String
* and return the List of String.
*
* @param mappedName The String to be splitted.
* @return The List of String after being splitted, with the "." as delimiter.
*/
protected List<String> mappedNameSplitter(String mappedName) {
List<String> result = new ArrayList<String>();
String[] mappedNamesArray = mappedName.split("\\.");
for (int i = 0; i < mappedNamesArray.length; i++) {
result.add(mappedNamesArray[i]);
}
return result;
}
/**
* Validates the field requirement by chart recursively and give error messages when it returns false.
*
* @param bean The object to be used to obtain the property value
* @param mappedNames The array of Strings which when combined together, they form the field property
* @param errorKey The error key to be used for adding error messages to the error map.
* @param itemNumber The Integer that represents the item number that we're currently iterating.
* @return true if it passes the validation.
*/
protected boolean validateFieldRequirementByChartHelper(Object bean, Object[] mappedNames, StringBuffer errorKey, Integer itemNumber) {
boolean valid = true;
Object value = ObjectUtils.getPropertyValue(bean, (String) mappedNames[0]);
if (ObjectUtils.isNull(value)) {
errorKey.append(mappedNames[0]);
String fieldName = SpringContext.getBean(DataDictionaryService.class).getAttributeErrorLabel(bean.getClass(), (String) mappedNames[0]);
if (itemNumber != null) {
fieldName = fieldName + " in Item " + itemNumber;
}
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, fieldName);
return false;
}
else if (value instanceof Collection) {
if (((Collection) value).isEmpty()) {
// if this collection doesn't contain anything, when it's supposed to contain some strings with values, return
// false.
errorKey.append(mappedNames[0]);
String mappedNameStr = (String) mappedNames[0];
String methodToInvoke = "get" + (mappedNameStr.substring(0, 1)).toUpperCase() + mappedNameStr.substring(1, mappedNameStr.length() - 1) + "Class";
Class offendingClass;
try {
offendingClass = (Class) bean.getClass().getMethod(methodToInvoke, null).invoke(bean, null);
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
BusinessObjectEntry boe = SpringContext.getBean(DataDictionaryService.class).getDataDictionary().getBusinessObjectEntry(offendingClass.getSimpleName());
List<AttributeDefinition> offendingAttributes = boe.getAttributes();
AttributeDefinition offendingAttribute = offendingAttributes.get(0);
String fieldName = SpringContext.getBean(DataDictionaryService.class).getAttributeShortLabel(offendingClass, offendingAttribute.getName());
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, (String) mappedNames[0]);
return false;
}
int count = 0;
for (Iterator iter = ((Collection) value).iterator(); iter.hasNext();) {
errorKey.append(mappedNames[0] + "[" + count + "].");
count++;
valid &= validateFieldRequirementByChartHelper(iter.next(), ArrayUtils.subarray(mappedNames, 1, mappedNames.length), errorKey, itemNumber);
}
return valid;
}
else if (StringUtils.isBlank(value.toString())) {
errorKey.append(mappedNames[0]);
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, (String) mappedNames[0]);
return false;
}
else if (mappedNames.length > 1) {
// this means we have not reached the end of a single field to be traversed yet, so continue with the recursion.
errorKey.append(mappedNames[0]).append(".");
valid &= validateFieldRequirementByChartHelper(value, ArrayUtils.subarray(mappedNames, 1, mappedNames.length), errorKey, itemNumber);
return valid;
}
else {
return true;
}
}
protected String getValueFromAvailabilityMatrix(String fieldName, String systemType, String systemState) {
for (AvailabilityMatrix am : PurapConstants.CAMS_AVAILABILITY_MATRIX.MATRIX_LIST) {
if (am.fieldName.equals(fieldName) && am.systemState.equals(systemState) && am.systemType.equals(systemType)) {
return am.availableValue;
}
}
// if we can't find any matching from availability matrix, return null for now.
return null;
}
/**
* Validates that the total quantity on all locations equals to the quantity on the line item. This is only used for IND system
* type.
*
* @param capitalAssetItems
* @return true if the total quantity on all locations equals to the quantity on the line item.
*/
protected boolean validateQuantityOnLocationsEqualsQuantityOnItem(List<PurchasingCapitalAssetItem> capitalAssetItems, String systemType, String systemState) {
boolean valid = true;
String availableValue = getValueFromAvailabilityMatrix(PurapPropertyConstants.CAPITAL_ASSET_LOCATIONS + "." + PurapPropertyConstants.QUANTITY, systemType, systemState);
if (availableValue.equals(PurapConstants.CapitalAssetAvailability.NONE)) {
// If the location quantity isn't available on the document given the system type and system state, we don't need to
// validate this, just return true.
return true;
}
int count = 0;
for (PurchasingCapitalAssetItem item : capitalAssetItems) {
if (item.getPurchasingItem() != null && item.getPurchasingItem().getItemType().isQuantityBasedGeneralLedgerIndicator() && !item.getPurchasingCapitalAssetSystem().getCapitalAssetLocations().isEmpty()) {
KualiDecimal total = new KualiDecimal(0);
for (CapitalAssetLocation location : item.getPurchasingCapitalAssetSystem().getCapitalAssetLocations()) {
if (ObjectUtils.isNotNull(location.getItemQuantity())) {
total = total.add(location.getItemQuantity());
}
}
if (!item.getPurchasingItem().getItemQuantity().equals(total)) {
valid = false;
String errorKey = PurapKeyConstants.ERROR_CAPITAL_ASSET_LOCATIONS_QUANTITY_MUST_EQUAL_ITEM_QUANTITY;
String propertyName = "document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "[" + count + "]." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEM + ".newPurchasingCapitalAssetLocationLine." + PurapPropertyConstants.QUANTITY;
GlobalVariables.getErrorMap().putError(propertyName, errorKey, Integer.toString(count + 1));
}
}
count++;
}
return valid;
}
/**
* Validates for the individual system type that for each of the items, the capitalAssetTransactionTypeCode matches the system
* parameter PURCHASING_ASSET_TRANSACTION_TYPES_ALLOWING_ASSET_NUMBERS, the method will return true but if it doesn't match the
* system parameter, then loop through each of the itemCapitalAssets. If there is any non-null capitalAssetNumber then return
* false.
*
* @param capitalAssetItems the List of PurchasingCapitalAssetItems on the document to be validated
* @return false if the capital asset transaction type does not match the system parameter that allows asset numbers but the
* itemCapitalAsset contains at least one asset numbers.
*/
protected boolean validateIndividualSystemPurchasingTransactionTypesAllowingAssetNumbers(List<PurchasingCapitalAssetItem> capitalAssetItems) {
boolean valid = true;
int count = 0;
for (PurchasingCapitalAssetItem capitalAssetItem : capitalAssetItems) {
String prefix = "document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "[" + count + "].";
valid &= validatePurchasingTransactionTypesAllowingAssetNumbers(capitalAssetItem.getPurchasingCapitalAssetSystem(), capitalAssetItem.getCapitalAssetTransactionTypeCode(), prefix);
count++;
}
return valid;
}
/**
* Generic validation that if the capitalAssetTransactionTypeCode does not match the system parameter
* PURCHASING_ASSET_TRANSACTION_TYPES_ALLOWING_ASSET_NUMBERS and at least one of the itemCapitalAssets contain a non-null
* capitalAssetNumber then return false. This method is used by one system and multiple system types as well as being used as a
* helper method for validateIndividualSystemPurchasingTransactionTypesAllowingAssetNumbers method.
*
* @param capitalAssetSystem the capitalAssetSystem containing a List of itemCapitalAssets to be validated.
* @param capitalAssetTransactionType the capitalAssetTransactionTypeCode containing asset numbers to be validated.
* @return false if the capital asset transaction type does not match the system parameter that allows asset numbers but the
* itemCapitalAsset contains at least one asset numbers.
*/
protected boolean validatePurchasingTransactionTypesAllowingAssetNumbers(CapitalAssetSystem capitalAssetSystem, String capitalAssetTransactionType, String prefix) {
boolean allowedAssetNumbers = (this.getParameterService().getParameterEvaluator(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, CabParameterConstants.CapitalAsset.PURCHASING_ASSET_TRANSACTION_TYPES_ALLOWING_ASSET_NUMBERS, capitalAssetTransactionType).evaluationSucceeds());
if (allowedAssetNumbers) {
// If this is a transaction type that allows asset numbers, we don't need to validate anymore, just return true here.
return true;
}
else {
for (ItemCapitalAsset asset : capitalAssetSystem.getItemCapitalAssets()) {
if (asset.getCapitalAssetNumber() != null) {
String propertyName = prefix + PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE_CODE;
GlobalVariables.getErrorMap().putError(propertyName, PurapKeyConstants.ERROR_CAPITAL_ASSET_ASSET_NUMBERS_NOT_ALLOWED_TRANS_TYPE, capitalAssetTransactionType);
return false;
}
}
}
return true;
}
/**
* TODO: rename this method removing trade in reference? Validates that if the non quantity drive allowed indicator on the
* capital asset transaction type is false and the item is of non quantity type
*
* @param capitalAssetItems The List of PurchasingCapitalAssetItem to be validated.
* @return false if the indicator is false and there is at least one non quantity items on the list.
*/
protected boolean validateNonQuantityDrivenAllowedIndicatorAndTradeIn(List<PurchasingCapitalAssetItem> capitalAssetItems) {
boolean valid = true;
int count = 0;
for (PurchasingCapitalAssetItem capitalAssetItem : capitalAssetItems) {
String prefix = "document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "[" + count + "].";
if (StringUtils.isNotBlank(capitalAssetItem.getCapitalAssetTransactionTypeCode())) {
// ((PurchasingCapitalAssetItemBase)
// capitalAssetItem).refreshReferenceObject(PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE);
if (!capitalAssetItem.getCapitalAssetTransactionType().getCapitalAssetNonquantityDrivenAllowIndicator()) {
if (!capitalAssetItem.getPurchasingItem().getItemType().isQuantityBasedGeneralLedgerIndicator()) {
String propertyName = prefix + PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE_CODE;
GlobalVariables.getErrorMap().putError(propertyName, PurapKeyConstants.ERROR_CAPITAL_ASSET_TRANS_TYPE_NOT_ALLOWING_NON_QUANTITY_ITEMS, capitalAssetItem.getCapitalAssetTransactionTypeCode());
valid &= false;
}
}
}
count++;
}
return valid;
}
/**
* Wrapper to do Capital Asset validations, generating errors instead of warnings. Makes sure that the given item's data
* relevant to its later possible classification as a Capital Asset is internally consistent, by marshaling and calling the
* methods marked as Capital Asset validations. This implementation assumes that all object codes are valid (real) object codes.
*
* @param recurringPaymentType The item's document's RecurringPaymentType
* @param item A PurchasingItemBase object
* @param apoCheck True if this check is for APO purposes
* @return True if the item passes all Capital Asset validations
*/
public boolean validateItemCapitalAssetWithErrors(String recurringPaymentTypeCode, ExternalPurApItem item, boolean apoCheck) {
PurchasingItemBase purchasingItem = (PurchasingItemBase) item;
List<String> previousErrorPath = GlobalVariables.getErrorMap().getErrorPath();
GlobalVariables.getErrorMap().clearErrorPath();
GlobalVariables.getErrorMap().addToErrorPath(PurapConstants.CAPITAL_ASSET_TAB_ERRORS);
boolean result = validatePurchasingItemCapitalAsset(recurringPaymentTypeCode, purchasingItem);
// Now that we're done with cams related validations, reset the error path to what it was previously.
GlobalVariables.getErrorMap().clearErrorPath();
for (String path : previousErrorPath) {
GlobalVariables.getErrorMap().addToErrorPath(path);
}
return result;
}
/**
* Makes sure that the given item's data relevant to its later possible classification as a Capital Asset is internally
* consistent, by marshaling and calling the methods marked as Capital Asset validations. This implementation assumes that all
* object codes are valid (real) object codes.
*
* @param recurringPaymentType The item's document's RecurringPaymentType
* @param item A PurchasingItemBase object
* @param warn A boolean which should be set to true if warnings are to be set on the calling document for most of the
* validations, rather than errors.
* @return True if the item passes all Capital Asset validations
*/
protected boolean validatePurchasingItemCapitalAsset(String recurringPaymentTypeCode, PurchasingItem item) {
boolean valid = true;
String capitalAssetTransactionTypeCode = "";
AssetTransactionType capitalAssetTransactionType = null;
String itemIdentifier = item.getItemIdentifierString();
if (item.getPurchasingCapitalAssetItem() != null) {
capitalAssetTransactionTypeCode = item.getPurchasingCapitalAssetItem().getCapitalAssetTransactionTypeCode();
// ((PurchasingCapitalAssetItemBase)
// item.getPurchasingCapitalAssetItem()).refreshReferenceObject(PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE);
capitalAssetTransactionType = (AssetTransactionType) item.getPurchasingCapitalAssetItem().getCapitalAssetTransactionType();
}
// These checks do not depend on Accounting Line information, but do depend on transaction type.
if (!StringUtils.isEmpty(capitalAssetTransactionTypeCode)) {
valid &= validateCapitalAssetTransactionTypeVersusRecurrence(capitalAssetTransactionType, recurringPaymentTypeCode, itemIdentifier);
}
return valid &= validatePurapItemCapitalAsset(item, capitalAssetTransactionType);
}
/**
* This method validated purapItem giving a transtype
*
* @param recurringPaymentType
* @param item
* @param warn
* @return
*/
protected boolean validatePurapItemCapitalAsset(PurApItem item, AssetTransactionType capitalAssetTransactionType) {
boolean valid = true;
String itemIdentifier = item.getItemIdentifierString();
boolean quantityBased = item.getItemType().isQuantityBasedGeneralLedgerIndicator();
BigDecimal itemUnitPrice = item.getItemUnitPrice();
HashSet<String> capitalOrExpenseSet = new HashSet<String>(); // For the first validation on every accounting line.
// Do the checks that depend on Accounting Line information.
for (PurApAccountingLine accountingLine : item.getSourceAccountingLines()) {
// Because of ObjectCodeCurrent, we had to refresh this.
accountingLine.refreshReferenceObject(KFSPropertyConstants.OBJECT_CODE);
ObjectCode objectCode = accountingLine.getObjectCode();
String capitalOrExpense = objectCodeCapitalOrExpense(objectCode);
capitalOrExpenseSet.add(capitalOrExpense); // HashSets accumulate distinct values (and nulls) only.
valid &= validateAccountingLinesNotCapitalAndExpense(capitalOrExpenseSet, itemIdentifier, objectCode);
// Do the checks involving capital asset transaction type.
if (capitalAssetTransactionType != null) {
valid &= validateObjectCodeVersusTransactionType(objectCode, capitalAssetTransactionType, itemIdentifier, quantityBased);
}
}
return valid;
}
/**
* Capital Asset validation: An item cannot have among its associated accounting lines both object codes that indicate it is a
* Capital Asset, and object codes that indicate that the item is not a Capital Asset. Whether an object code indicates that the
* item is a Capital Asset is determined by whether its level is among a specific set of levels that are deemed acceptable for
* such items.
*
* @param capitalOrExpenseSet A HashSet containing the distinct values of either "Capital" or "Expense" that have been added to
* it.
* @param warn A boolean which should be set to true if warnings are to be set on the calling document
* @param itemIdentifier A String identifying the item for error display
* @param objectCode An ObjectCode, for error display
* @return True if the given HashSet contains at most one of either "Capital" or "Expense"
*/
protected boolean validateAccountingLinesNotCapitalAndExpense(HashSet<String> capitalOrExpenseSet, String itemIdentifier, ObjectCode objectCode) {
boolean valid = true;
// If the set contains more than one distinct string, fail.
if (capitalOrExpenseSet.size() > 1) {
GlobalVariables.getErrorMap().putError(KFSConstants.FINANCIAL_OBJECT_LEVEL_CODE_PROPERTY_NAME, CabKeyConstants.ERROR_ITEM_CAPITAL_AND_EXPENSE, itemIdentifier, objectCode.getFinancialObjectCodeName());
valid &= false;
}
return valid;
}
protected boolean validateLevelCapitalAssetIndication(BigDecimal unitPrice, ObjectCode objectCode, String itemIdentifier) {
String capitalAssetPriceThresholdParam = this.getParameterService().getParameterValue(AssetGlobal.class, CabParameterConstants.CapitalAsset.CAPITALIZATION_LIMIT_AMOUNT);
BigDecimal priceThreshold = null;
try {
priceThreshold = new BigDecimal(capitalAssetPriceThresholdParam);
}
catch (NumberFormatException nfe) {
throw new RuntimeException("the parameter for CAPITAL_ASSET_OBJECT_LEVELS came was not able to be converted to a number.", nfe);
}
if (unitPrice.compareTo(priceThreshold) >= 0) {
List<String> possibleCAMSObjectLevels = this.getParameterService().getParameterValues(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, CabParameterConstants.CapitalAsset.POSSIBLE_CAPITAL_ASSET_OBJECT_LEVELS);
if (possibleCAMSObjectLevels.contains(objectCode.getFinancialObjectLevelCode())) {
String warning = SpringContext.getBean(KualiConfigurationService.class).getPropertyString(CabKeyConstants.WARNING_ABOVE_THRESHOLD_SUGESTS_CAPITAL_ASSET_LEVEL);
warning = StringUtils.replace(warning, "{0}", itemIdentifier);
warning = StringUtils.replace(warning, "{1}", priceThreshold.toString());
GlobalVariables.getMessageList().add(warning);
return false;
}
}
return true;
}
/**
* Capital Asset validation: If the item has a transaction type, check that the transaction type is acceptable for the object
* code sub-types of all the object codes on the associated accounting lines.
*
* @param objectCode
* @param capitalAssetTransactionType
* @param warn A boolean which should be set to true if warnings are to be set on the calling document
* @param itemIdentifier
* @return
*/
protected boolean validateObjectCodeVersusTransactionType(ObjectCode objectCode, CapitalAssetBuilderAssetTransactionType capitalAssetTransactionType, String itemIdentifier, boolean quantityBasedItem) {
boolean valid = true;
String[] objectCodeSubTypes = {};
if (quantityBasedItem) {
String capitalAssetQuantitySubtypeRequiredText = capitalAssetTransactionType.getCapitalAssetQuantitySubtypeRequiredText();
if (capitalAssetQuantitySubtypeRequiredText != null) {
objectCodeSubTypes = StringUtils.split(capitalAssetQuantitySubtypeRequiredText, ";");
}
}
else {
String capitalAssetNonquantitySubtypeRequiredText = capitalAssetTransactionType.getCapitalAssetNonquantitySubtypeRequiredText();
if (capitalAssetNonquantitySubtypeRequiredText != null) {
objectCodeSubTypes = StringUtils.split(capitalAssetNonquantitySubtypeRequiredText, ";");
}
}
boolean found = false;
for (String subType : objectCodeSubTypes) {
if (StringUtils.equals(subType, objectCode.getFinancialObjectSubTypeCode())) {
found = true;
break;
}
}
if (!found) {
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.ITEM_CAPITAL_ASSET_TRANSACTION_TYPE, CabKeyConstants.ERROR_ITEM_TRAN_TYPE_OBJECT_CODE_SUBTYPE, itemIdentifier, capitalAssetTransactionType.getCapitalAssetTransactionTypeDescription(), objectCode.getFinancialObjectCodeName(), objectCode.getFinancialObjectSubType().getFinancialObjectSubTypeName());
valid &= false;
}
return valid;
}
/**
* Capital Asset validation: If the item has a transaction type, check that if the document specifies that recurring payments
* are to be made, that the transaction type is one that is appropriate for this situation, and that if the document does not
* specify that recurring payments are to be made, that the transaction type is one that is appropriate for that situation.
*
* @param capitalAssetTransactionType
* @param recurringPaymentType
* @param warn A boolean which should be set to true if warnings are to be set on the calling document
* @param itemIdentifier
* @return
*/
protected boolean validateCapitalAssetTransactionTypeVersusRecurrence(CapitalAssetBuilderAssetTransactionType capitalAssetTransactionType, String recurringPaymentTypeCode, String itemIdentifier) {
boolean valid = true;
// If there is a tran type ...
if ((capitalAssetTransactionType != null) && (capitalAssetTransactionType.getCapitalAssetTransactionTypeCode() != null)) {
String recurringTransactionTypeCodes = this.getParameterService().getParameterValue(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, CabParameterConstants.CapitalAsset.RECURRING_CAMS_TRAN_TYPES);
if (StringUtils.isNotEmpty(recurringPaymentTypeCode)) { // If there is a recurring payment type ...
if (!StringUtils.contains(recurringTransactionTypeCodes, capitalAssetTransactionType.getCapitalAssetTransactionTypeCode())) {
// There should be a recurring tran type code.
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.ITEM_CAPITAL_ASSET_TRANSACTION_TYPE, CabKeyConstants.ERROR_ITEM_WRONG_TRAN_TYPE, itemIdentifier, capitalAssetTransactionType.getCapitalAssetTransactionTypeDescription(), CabConstants.ValidationStrings.RECURRING);
valid &= false;
}
}
else { // If the payment type is not recurring ...
// There should not be a recurring transaction type code.
if (StringUtils.contains(recurringTransactionTypeCodes, capitalAssetTransactionType.getCapitalAssetTransactionTypeCode())) {
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.ITEM_CAPITAL_ASSET_TRANSACTION_TYPE, CabKeyConstants.ERROR_ITEM_WRONG_TRAN_TYPE, itemIdentifier, capitalAssetTransactionType.getCapitalAssetTransactionTypeDescription(), CabConstants.ValidationStrings.NON_RECURRING);
valid &= false;
}
}
}
else { // If there is no transaction type ...
if (StringUtils.isNotEmpty(recurringPaymentTypeCode)) { // If there is a recurring payment type ...
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.ITEM_CAPITAL_ASSET_TRANSACTION_TYPE, CabKeyConstants.ERROR_ITEM_NO_TRAN_TYPE, itemIdentifier, CabConstants.ValidationStrings.RECURRING);
valid &= false;
}
else { // If the payment type is not recurring ...
GlobalVariables.getErrorMap().putError(PurapPropertyConstants.ITEM_CAPITAL_ASSET_TRANSACTION_TYPE, CabKeyConstants.ERROR_ITEM_NO_TRAN_TYPE, itemIdentifier, CabConstants.ValidationStrings.NON_RECURRING);
valid &= false;
}
}
return valid;
}
/**
* Utility wrapping isCapitalAssetObjectCode for the use of processItemCapitalAssetValidation.
*
* @param oc An ObjectCode
* @return A String indicating that the given object code is either Capital or Expense
*/
protected String objectCodeCapitalOrExpense(ObjectCode oc) {
String capital = CabConstants.ValidationStrings.CAPITAL;
String expense = CabConstants.ValidationStrings.EXPENSE;
return (isCapitalAssetObjectCode(oc) ? capital : expense);
}
/**
* Predicate to determine whether the given object code is of a specified object sub type required for purap cams.
*
* @param oc An ObjectCode
* @return True if the ObjectSubType is the one designated for capital assets.
*/
protected boolean isCapitalAssetObjectCode(ObjectCode oc) {
String capitalAssetObjectSubType = this.getParameterService().getParameterValue(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, PurapParameterConstants.CapitalAsset.PURCHASING_OBJECT_SUB_TYPES);
return (StringUtils.containsIgnoreCase(capitalAssetObjectSubType, oc.getFinancialObjectSubTypeCode()) ? true : false);
}
protected boolean validateCapitalAssetLocationAddressFieldsOneOrMultipleSystemType(List<CapitalAssetSystem> capitalAssetSystems) {
boolean valid = true;
int systemCount = 0;
for (CapitalAssetSystem system : capitalAssetSystems) {
List<CapitalAssetLocation> capitalAssetLocations = system.getCapitalAssetLocations();
StringBuffer errorKey = new StringBuffer("document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEMS + "[" + new Integer(systemCount++) + "].");
errorKey.append("capitalAssetLocations");
int locationCount = 0;
for (CapitalAssetLocation location : capitalAssetLocations) {
errorKey.append("[" + locationCount++ + "].");
valid &= validateCapitalAssetLocationAddressFields(location, errorKey);
}
}
return valid;
}
protected boolean validateCapitalAssetLocationAddressFieldsForIndividualSystemType(List<PurchasingCapitalAssetItem> capitalAssetItems) {
boolean valid = true;
for (PurchasingCapitalAssetItem item : capitalAssetItems) {
CapitalAssetSystem system = item.getPurchasingCapitalAssetSystem();
List<CapitalAssetLocation> capitalAssetLocations = system.getCapitalAssetLocations();
StringBuffer errorKey = new StringBuffer("document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "[" + new Integer(item.getPurchasingItem().getItemLineNumber().intValue() - 1) + "].");
errorKey.append("purchasingCapitalAssetSystem.capitalAssetLocations");
int i = 0;
for (CapitalAssetLocation location : capitalAssetLocations) {
errorKey.append("[" + i++ + "].");
valid &= validateCapitalAssetLocationAddressFields(location, errorKey);
}
}
return valid;
}
protected boolean validateCapitalAssetLocationAddressFields(CapitalAssetLocation location, StringBuffer errorKey) {
boolean valid = true;
if (StringUtils.isBlank(location.getCapitalAssetLine1Address())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_ADDRESS_LINE1);
valid &= false;
}
if (StringUtils.isBlank(location.getCapitalAssetCityName())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_CITY);
valid &= false;
}
if (StringUtils.isBlank(location.getCapitalAssetCountryCode())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_COUNTRY);
valid &= false;
}
else if (location.getCapitalAssetCountryCode().equals(KFSConstants.COUNTRY_CODE_UNITED_STATES)) {
if (StringUtils.isBlank(location.getCapitalAssetStateCode())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_STATE);
valid &= false;
}
if (StringUtils.isBlank(location.getCapitalAssetPostalCode())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_POSTAL_CODE);
valid &= false;
}
}
if (!location.isOffCampusIndicator()) {
if (StringUtils.isBlank(location.getCampusCode())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_CAMPUS);
valid &= false;
}
if (StringUtils.isBlank(location.getBuildingCode())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_BUILDING);
valid &= false;
}
if (StringUtils.isBlank(location.getBuildingRoomNumber())) {
GlobalVariables.getErrorMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED, PurapPropertyConstants.CAPITAL_ASSET_LOCATION_ROOM);
valid &= false;
}
}
return valid;
}
protected boolean validateAccountsPayableItem(AccountsPayableItem apItem) {
boolean valid = true;
valid &= validatePurapItemCapitalAsset(apItem, (AssetTransactionType) apItem.getCapitalAssetTransactionType());
return valid;
}
// end of methods for purap
/**
* @see org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService#validateFinancialProcessingData(org.kuali.kfs.sys.document.AccountingDocument,
* org.kuali.kfs.fp.businessobject.CapitalAssetInformation)
* @param accountingDocument and capitalAssetInformation
* @return True if the FinancialProcessingData is valid.
*/
public boolean validateFinancialProcessingData(AccountingDocument accountingDocument, CapitalAssetInformation capitalAssetInformation) {
boolean valid = true;
// Check if we need to collect cams data
String dataEntryExpected = this.getCapitalAssetObjectSubTypeLinesFlag(accountingDocument);
if (StringUtils.isBlank(dataEntryExpected)) {
// Data is not expected
if (!isCapitalAssetInformationBlank(capitalAssetInformation)) {
// If no parameter was found or determined that data shouldn't be collected, give error if data was entered
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_NUMBER, CabKeyConstants.CapitalAssetInformation.ERROR_ASSET_DO_NOT_ENTER_ANY_DATA);
return false;
}
else {
// No data to be collected and no data entered. Hence no error
return true;
}
}
else {
// Data is expected
if (isCapitalAssetInformationBlank(capitalAssetInformation)) {
// No data is entered
if (isCapitalAssetDataRequired(accountingDocument, dataEntryExpected)) {
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_NUMBER, CabKeyConstants.CapitalAssetInformation.ERROR_ASSET_REQUIRE_DATA_ENTRY);
return false;
}
else
return true;
}
else if (!isNewAssetBlank(capitalAssetInformation) && !canCreateNewAsset(accountingDocument, dataEntryExpected)) {
// No allow to create new capital asset
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_QUANTITY, CabKeyConstants.CapitalAssetInformation.ERROR_ASSET_UPDATE_ALLOW_ONLY);
return false;
}
else if (!isNewAssetBlank(capitalAssetInformation) && !isUpdateAssetBlank(capitalAssetInformation)) {
// Data exists on both crate new asset and update asset, give error
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_NUMBER, CabKeyConstants.CapitalAssetInformation.ERROR_ASSET_NEW_OR_UPDATE_ONLY);
return false;
}
}
if (!isUpdateAssetBlank(capitalAssetInformation)) {
// Validate update Asset information
valid = validateUpdateCapitalAssetField(capitalAssetInformation, accountingDocument);
}
else {
// Validate New Asset information
valid = checkNewCapitalAssetFieldsExist(capitalAssetInformation);
if (valid) {
valid = validateNewCapitalAssetFields(capitalAssetInformation);
}
}
return valid;
}
/**
* This method...
*
* @param accountingDocument
* @return getCapitalAssetObjectSubTypeLinesFlag = "" ==> no assetObjectSubType code F ==> assetObjectSubType code on source
* lines T ==> assetObjectSubType code on target lines FT ==> assetObjectSubType code on both source and target lines
*/
protected String getCapitalAssetObjectSubTypeLinesFlag(AccountingDocument accountingDocument) {
List<String> financialProcessingCapitalObjectSubTypes = this.getParameterService().getParameterValues(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, CabParameterConstants.CapitalAsset.FINANCIAL_PROCESSING_CAPITAL_OBJECT_SUB_TYPES);
String getCapitalAssetObjectSubTypeLinesFlag = "";
// Check if SourceAccountingLine has objectSub type code
List<SourceAccountingLine> sAccountingLines = accountingDocument.getSourceAccountingLines();
for (SourceAccountingLine sourceAccountingLine : sAccountingLines) {
ObjectCode objectCode = sourceAccountingLine.getObjectCode();
if (ObjectUtils.isNull(objectCode)) {
break;
}
String objectSubTypeCode = objectCode.getFinancialObjectSubTypeCode();
if (financialProcessingCapitalObjectSubTypes.contains(objectSubTypeCode)) {
getCapitalAssetObjectSubTypeLinesFlag = KFSConstants.SOURCE_ACCT_LINE_TYPE_CODE;
break;
}
}
// Check if TargetAccountingLine has objectSub type code
List<TargetAccountingLine> tAccountingLines = accountingDocument.getTargetAccountingLines();
for (TargetAccountingLine targetAccountingLine : tAccountingLines) {
ObjectCode objectCode = targetAccountingLine.getObjectCode();
if (ObjectUtils.isNull(objectCode)) {
break;
}
String objectSubTypeCode = objectCode.getFinancialObjectSubTypeCode();
if (financialProcessingCapitalObjectSubTypes.contains(objectSubTypeCode)) {
getCapitalAssetObjectSubTypeLinesFlag = getCapitalAssetObjectSubTypeLinesFlag.equals(KFSConstants.SOURCE_ACCT_LINE_TYPE_CODE) ? KFSConstants.SOURCE_ACCT_LINE_TYPE_CODE + KFSConstants.TARGET_ACCT_LINE_TYPE_CODE : KFSConstants.TARGET_ACCT_LINE_TYPE_CODE;
break;
}
}
return getCapitalAssetObjectSubTypeLinesFlag;
}
/**
* @see org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService#hasCapitalAssetObjectSubType(org.kuali.kfs.sys.document.AccountingDocument)
*/
public boolean hasCapitalAssetObjectSubType(AccountingDocument accountingDocument) {
boolean hasCapitalAssetObjectSubType = false;
if (!getCapitalAssetObjectSubTypeLinesFlag(accountingDocument).equals("N"))
hasCapitalAssetObjectSubType = true;
return hasCapitalAssetObjectSubType;
}
/**
* if the capital asset data is required for this transaction
*
* @param accountingDocument and dataEntryExpected
* @return boolean false then the capital asset information is not required
*/
private boolean isCapitalAssetDataRequired(AccountingDocument accountingDocument, String dataEntryExpected) {
boolean isCapitalAssetDataRequired = true;
String accountingDocumentType = accountingDocument.getDocumentHeader().getWorkflowDocument().getDocumentType();
// if (isDocumentTypeRestricted(accountingDocument) ||
// accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.INTERNAL_BILLING)) {
if (accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.INTERNAL_BILLING)) {
if (dataEntryExpected.equals(KFSConstants.SOURCE_ACCT_LINE_TYPE_CODE + KFSConstants.TARGET_ACCT_LINE_TYPE_CODE))
isCapitalAssetDataRequired = false;
}
return isCapitalAssetDataRequired;
}
/**
* if this transaction can create new asset
*
* @param accountingDocument and dataEntryExpected
* @return
*/
private boolean canCreateNewAsset(AccountingDocument accountingDocument, String dataEntryExpected) {
boolean canCreateNewAsset = true;
String accountingDocumentType = accountingDocument.getDocumentHeader().getWorkflowDocument().getDocumentType();
if (accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.CASH_RECEIPT)) {
canCreateNewAsset = false;
}
else {
if (isDocumentTypeRestricted(accountingDocument) && dataEntryExpected.equals(KFSConstants.SOURCE_ACCT_LINE_TYPE_CODE))
canCreateNewAsset = false;
}
return canCreateNewAsset;
}
/**
* if this document is restricted
*
* @param accountingDocument
* @return boolean true then this document is restricted
*/
private boolean isDocumentTypeRestricted(AccountingDocument accountingDocument) {
boolean isDocumentTypeRestricted = false;
String accountingDocumentType = accountingDocument.getDocumentHeader().getWorkflowDocument().getDocumentType();
if (accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.GENERAL_ERROR_CORRECTION) || accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.YEAR_END_GENERAL_ERROR_CORRECTION))
isDocumentTypeRestricted = true;
if (accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.DISTRIBUTION_OF_INCOME_AND_EXPENSE) || accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.YEAR_END_DISTRIBUTION_OF_INCOME_AND_EXPENSE))
isDocumentTypeRestricted = true;
if (accountingDocumentType.equals(KFSConstants.FinancialDocumentTypeCodes.SERVICE_BILLING))
isDocumentTypeRestricted = true;
return isDocumentTypeRestricted;
}
/**
* To see if capitalAssetInformation is blank
*
* @param capitalAssetInformation
* @return boolean false if the asset is not blank
*/
private boolean isCapitalAssetInformationBlank(CapitalAssetInformation capitalAssetInformation) {
boolean isBlank = true;
if (!isNewAssetBlank(capitalAssetInformation) || !isUpdateAssetBlank(capitalAssetInformation)) {
isBlank = false;
}
return isBlank;
}
/**
* To check if data exists on create new asset
*
* @param capitalAssetInformation
* @return boolean false if the new asset is not blank
*/
private boolean isNewAssetBlank(CapitalAssetInformation capitalAssetInformation) {
boolean isBlank = true;
if (ObjectUtils.isNotNull(capitalAssetInformation.getCapitalAssetTypeCode()) || ObjectUtils.isNotNull(capitalAssetInformation.getVendorName()) || ObjectUtils.isNotNull(capitalAssetInformation.getCapitalAssetQuantity()) || ObjectUtils.isNotNull(capitalAssetInformation.getCapitalAssetManufacturerName()) || ObjectUtils.isNotNull(capitalAssetInformation.getCapitalAssetManufacturerModelNumber()) || ObjectUtils.isNotNull(capitalAssetInformation.getCapitalAssetDescription())) {
isBlank = false;
}
return isBlank;
}
/**
* To check if data exists on update asset
*
* @param capitalAssetInformation
* @return boolean false if the update asset is not blank
*/
private boolean isUpdateAssetBlank(CapitalAssetInformation capitalAssetInformation) {
boolean isBlank = true;
if (ObjectUtils.isNotNull(capitalAssetInformation.getCapitalAssetNumber())) {
isBlank = false;
}
return isBlank;
}
/**
* To validate if the asset is active
*
* @param capitalAssetManagementAsset the asset to be validated
* @return boolean false if the asset is not active
*/
private boolean validateUpdateCapitalAssetField(CapitalAssetInformation capitalAssetInformation, AccountingDocument accountingDocument) {
boolean valid = true;
Map<String, String> params = new HashMap<String, String>();
params.put(KFSPropertyConstants.CAPITAL_ASSET_NUMBER, capitalAssetInformation.getCapitalAssetNumber().toString());
Asset asset = (Asset) this.getBusinessObjectService().findByPrimaryKey(Asset.class, params);
List<Long> assetNumbers = new ArrayList<Long>();
assetNumbers.add(capitalAssetInformation.getCapitalAssetNumber());
if (ObjectUtils.isNull(asset)) {
valid = false;
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.CAPITAL_ASSET_NUMBER);
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_NUMBER, KFSKeyConstants.ERROR_EXISTENCE, label);
}
else if (!(this.getAssetService().isCapitalAsset(asset) && !this.getAssetService().isAssetRetired(asset))) {
// check asset status must be capital asset active.
valid = false;
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_NUMBER, CabKeyConstants.CapitalAssetInformation.ERROR_ASSET_ACTIVE_CAPITAL_ASSET_REQUIRED);
}
else {
String documentNumber = accountingDocument.getDocumentNumber();
String documentType = getDocumentTypeName(accountingDocument);
if (getCapitalAssetManagementModuleService().isFpDocumentEligibleForAssetLock(accountingDocument, documentType) && getCapitalAssetManagementModuleService().isAssetLocked(assetNumbers, documentType, documentNumber)) {
valid = false;
}
}
return valid;
}
/**
* Check if all required fields exist on new asset
*
* @param capitalAssetInformation the fields of add asset to be checked
* @return boolean false if a required field is missing
*/
private boolean checkNewCapitalAssetFieldsExist(CapitalAssetInformation capitalAssetInformation) {
boolean valid = true;
if (StringUtils.isBlank(capitalAssetInformation.getCapitalAssetTypeCode())) {
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.CAPITAL_ASSET_TYPE_CODE);
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_TYPE_CODE, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
if (capitalAssetInformation.getCapitalAssetQuantity() == null || capitalAssetInformation.getCapitalAssetQuantity() <= 0) {
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.CAPITAL_ASSET_QUANTITY);
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_QUANTITY, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
if (StringUtils.isBlank(capitalAssetInformation.getVendorName())) {
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.VENDOR_NAME);
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.VENDOR_NAME, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
if (StringUtils.isBlank(capitalAssetInformation.getCapitalAssetManufacturerName())) {
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.CAPITAL_ASSET_MANUFACTURE_NAME);
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_MANUFACTURE_NAME, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
if (StringUtils.isBlank(capitalAssetInformation.getCapitalAssetDescription())) {
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, CamsPropertyConstants.Asset.CAPITAL_ASSET_DESCRIPTION);
GlobalVariables.getErrorMap().putError(CamsPropertyConstants.Asset.CAPITAL_ASSET_DESCRIPTION, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
int index = 0;
List<CapitalAssetInformationDetail> capitalAssetInformationDetails = capitalAssetInformation.getCapitalAssetInformationDetails();
for (CapitalAssetInformationDetail dtl : capitalAssetInformationDetails) {
String errorPathPrefix = KFSPropertyConstants.DOCUMENT + "." + KFSPropertyConstants.CAPITAL_ASSET_INFORMATION + "." + KFSPropertyConstants.CAPITAL_ASSET_INFORMATION_DETAILS;
if (StringUtils.isBlank(dtl.getCampusCode())) {
String label = this.getDataDictionaryService().getAttributeLabel(Campus.class, KFSPropertyConstants.CAMPUS_CODE);
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.CAMPUS_CODE, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
if (StringUtils.isBlank(dtl.getBuildingCode())) {
String label = this.getDataDictionaryService().getAttributeLabel(Building.class, KFSPropertyConstants.BUILDING_CODE);
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.BUILDING_CODE, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
if (StringUtils.isBlank(dtl.getBuildingRoomNumber())) {
String label = this.getDataDictionaryService().getAttributeLabel(Room.class, KFSPropertyConstants.BUILDING_ROOM_NUMBER);
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.BUILDING_ROOM_NUMBER, KFSKeyConstants.ERROR_REQUIRED, label);
valid = false;
}
index++;
}
return valid;
}
/**
* To validate new asset information
*
* @param capitalAssetInformation the information of add asset to be validated
* @return boolean false if data is incorrect
*/
private boolean validateNewCapitalAssetFields(CapitalAssetInformation capitalAssetInformation) {
boolean valid = true;
Map<String, String> params = new HashMap<String, String>();
params.put(KFSPropertyConstants.CAPITAL_ASSET_TYPE_CODE, capitalAssetInformation.getCapitalAssetTypeCode().toString());
AssetType assetType = (AssetType) this.getBusinessObjectService().findByPrimaryKey(AssetType.class, params);
if (ObjectUtils.isNull(assetType)) {
valid = false;
String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.CAPITAL_ASSET_TYPE_CODE);
GlobalVariables.getErrorMap().putError(KFSPropertyConstants.CAPITAL_ASSET_TYPE_CODE, KFSKeyConstants.ERROR_EXISTENCE, label);
}
int index = 0;
List<CapitalAssetInformationDetail> capitalAssetInformationDetails = capitalAssetInformation.getCapitalAssetInformationDetails();
for (CapitalAssetInformationDetail dtl : capitalAssetInformationDetails) {
// We have to explicitly call this DD service to uppercase each field. This may not be the best place and maybe form
// populate
// is a better place but we CAMS team don't own FP document. This is the best we can do for now.
SpringContext.getBean(BusinessObjectDictionaryService.class).performForceUppercase(dtl);
String errorPathPrefix = KFSPropertyConstants.DOCUMENT + "." + KFSPropertyConstants.CAPITAL_ASSET_INFORMATION + "." + KFSPropertyConstants.CAPITAL_ASSET_INFORMATION_DETAILS;
if (StringUtils.isNotBlank(dtl.getCapitalAssetTagNumber()) && !dtl.getCapitalAssetTagNumber().equalsIgnoreCase(CamsConstants.Asset.NON_TAGGABLE_ASSET)) {
if (isTagNumberDuplicate(capitalAssetInformationDetails, dtl)) {
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.CAPITAL_ASSET_TAG_NUMBER, CamsKeyConstants.AssetGlobal.ERROR_CAMPUS_TAG_NUMBER_DUPLICATE, dtl.getCapitalAssetTagNumber());
valid = false;
}
}
Map<String, Object> criteria = new HashMap<String, Object>();
criteria.put(KFSPropertyConstants.CAMPUS_CODE, dtl.getCampusCode());
Campus campus = (Campus) SpringContext.getBean(KualiModuleService.class).getResponsibleModuleService(Campus.class).getExternalizableBusinessObject(Campus.class, criteria);
if (ObjectUtils.isNull(campus)) {
valid = false;
String label = this.getDataDictionaryService().getAttributeLabel(Campus.class, KFSPropertyConstants.CAMPUS_CODE);
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.CAMPUS_CODE, KFSKeyConstants.ERROR_EXISTENCE, label);
}
params = new HashMap<String, String>();
params.put(KFSPropertyConstants.CAMPUS_CODE, dtl.getCampusCode());
params.put(KFSPropertyConstants.BUILDING_CODE, dtl.getBuildingCode());
Building building = (Building) this.getBusinessObjectService().findByPrimaryKey(Building.class, params);
if (ObjectUtils.isNull(building)) {
valid = false;
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.BUILDING_CODE, CamsKeyConstants.AssetLocationGlobal.ERROR_INVALID_BUILDING_CODE, dtl.getBuildingCode(), dtl.getCampusCode());
}
params = new HashMap<String, String>();
params.put(KFSPropertyConstants.CAMPUS_CODE, dtl.getCampusCode());
params.put(KFSPropertyConstants.BUILDING_CODE, dtl.getBuildingCode());
params.put(KFSPropertyConstants.BUILDING_ROOM_NUMBER, dtl.getBuildingRoomNumber());
Room room = (Room) this.getBusinessObjectService().findByPrimaryKey(Room.class, params);
if (ObjectUtils.isNull(room)) {
valid = false;
GlobalVariables.getErrorMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.BUILDING_ROOM_NUMBER, CamsKeyConstants.AssetLocationGlobal.ERROR_INVALID_ROOM_NUMBER, dtl.getBuildingRoomNumber(), dtl.getBuildingCode(), dtl.getCampusCode());
}
index++;
}
return valid;
}
/**
* To check if the tag number is duplicate or in use
*
* @param capitalAssetInformation, capitalAssetInformationDetail
* @return boolean false if data is duplicate or in use
*/
private boolean isTagNumberDuplicate(List<CapitalAssetInformationDetail> capitalAssetInformationDetails, CapitalAssetInformationDetail dtl) {
boolean duplicateTag = false;
int tagCounter = 0;
if (!this.getAssetService().findActiveAssetsMatchingTagNumber(dtl.getCapitalAssetTagNumber()).isEmpty()) {
// Tag number is already in use
duplicateTag = true;
}
else {
for (CapitalAssetInformationDetail capitalAssetInfoDetl : capitalAssetInformationDetails) {
if (capitalAssetInfoDetl.getCapitalAssetTagNumber().equalsIgnoreCase(dtl.getCapitalAssetTagNumber().toString())) {
tagCounter++;
}
}
if (tagCounter > 1) {
// Tag number already exists in the collection
duplicateTag = true;
}
}
return duplicateTag;
}
/**
* @see org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService#notifyRouteStatusChange(java.lang.String,
* java.lang.String)
*/
public void notifyRouteStatusChange(DocumentHeader documentHeader) {
KualiWorkflowDocument workflowDocument = documentHeader.getWorkflowDocument();
String documentNumber = documentHeader.getDocumentNumber();
String documentType = workflowDocument.getDocumentType();
if (workflowDocument.stateIsCanceled() || workflowDocument.stateIsDisapproved()) {
// release CAB line items
activateCabPOLines(documentNumber);
activateCabGlLines(documentNumber);
}
if (workflowDocument.stateIsProcessed()) {
// update CAB GL lines if fully processed
updatePOLinesStatusAsProcessed(documentNumber);
updateGlLinesStatusAsProcessed(documentNumber);
// report asset numbers to PO
Integer poId = getPurchaseOrderIdentifier(documentNumber);
if (poId != null) {
List<Long> assetNumbers = null;
if (DocumentTypeName.ASSET_ADD_GLOBAL.equalsIgnoreCase(documentType)) {
assetNumbers = getAssetNumbersFromAssetGlobal(documentNumber);
}
else if (DocumentTypeName.ASSET_PAYMENT.equalsIgnoreCase(documentType)) {
assetNumbers = getAssetNumbersFromAssetPayment(documentNumber);
}
if (!assetNumbers.isEmpty()) {
String noteText = buildNoteTextForPurApDoc(documentType, assetNumbers);
SpringContext.getBean(PurchasingAccountsPayableModuleService.class).addAssignedAssetNumbers(poId, workflowDocument.getInitiatorPrincipalId(), noteText);
}
}
}
}
/**
* update cab non-PO lines status code for item/account/glEntry to 'P' as fully processed when possible
*
* @param documentNumber
*/
protected void updateGlLinesStatusAsProcessed(String documentNumber) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CabPropertyConstants.PurchasingAccountsPayableItemAsset.CAMS_DOCUMENT_NUMBER, documentNumber);
Collection<GeneralLedgerEntryAsset> matchingGlAssets = this.getBusinessObjectService().findMatching(GeneralLedgerEntryAsset.class, fieldValues);
if (matchingGlAssets != null && !matchingGlAssets.isEmpty()) {
for (GeneralLedgerEntryAsset generalLedgerEntryAsset : matchingGlAssets) {
GeneralLedgerEntry generalLedgerEntry = generalLedgerEntryAsset.getGeneralLedgerEntry();
// update gl status as processed
generalLedgerEntry.setActivityStatusCode(CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS);
this.getBusinessObjectService().save(generalLedgerEntry);
// release asset lock
if (isFpDocumentFullyProcessed(generalLedgerEntry)) {
getCapitalAssetManagementModuleService().deleteAssetLocks(generalLedgerEntry.getDocumentNumber(), null);
}
}
}
}
/**
* Check all generalLedgerEntries from the same FP document are fully processed.
*
* @param generalLedgerEntry
* @return
*/
protected boolean isFpDocumentFullyProcessed(GeneralLedgerEntry generalLedgerEntry) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CabPropertyConstants.GeneralLedgerEntry.DOCUMENT_NUMBER, generalLedgerEntry.getDocumentNumber());
Collection<GeneralLedgerEntry> matchingGlEntries = this.getBusinessObjectService().findMatching(GeneralLedgerEntry.class, fieldValues);
for (GeneralLedgerEntry glEntry : matchingGlEntries) {
if (!CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS.equals(glEntry.getActivityStatusCode())) {
return false;
}
}
return true;
}
/**
* update CAB PO lines status code for item/account/glEntry to 'P' as fully processed when possible
*
* @param documentNumber
*/
protected void updatePOLinesStatusAsProcessed(String documentNumber) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CabPropertyConstants.PurchasingAccountsPayableItemAsset.CAMS_DOCUMENT_NUMBER, documentNumber);
Collection<PurchasingAccountsPayableItemAsset> matchingAssets = this.getBusinessObjectService().findMatching(PurchasingAccountsPayableItemAsset.class, fieldValues);
if (matchingAssets != null && !matchingAssets.isEmpty()) {
// Map<Long, GeneralLedgerEntry> updateGlLines = new HashMap<Long, GeneralLedgerEntry>();
// update item and account status code to 'P' as fully processed
for (PurchasingAccountsPayableItemAsset itemAsset : matchingAssets) {
itemAsset.setActivityStatusCode(CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS);
for (PurchasingAccountsPayableLineAssetAccount assetAccount : itemAsset.getPurchasingAccountsPayableLineAssetAccounts()) {
assetAccount.setActivityStatusCode(CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS);
GeneralLedgerEntry generalLedgerEntry = assetAccount.getGeneralLedgerEntry();
// updateGlLines.put(generalLedgerEntry.getGeneralLedgerAccountIdentifier(), generalLedgerEntry);
if (isGlEntryFullyProcessed(generalLedgerEntry)) {
generalLedgerEntry.setActivityStatusCode(CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS);
this.getBusinessObjectService().save(generalLedgerEntry);
}
}
// update cab document status code to 'P' as all its items fully processed
PurchasingAccountsPayableDocument purapDocument = itemAsset.getPurchasingAccountsPayableDocument();
if (isDocumentFullyProcessed(purapDocument)) {
purapDocument.setActivityStatusCode(CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS);
}
this.getBusinessObjectService().save(purapDocument);
String lockingInformation = null;
PurchaseOrderDocument poDocument = getPurApInfoService().getCurrentDocumentForPurchaseOrderIdentifier(purapDocument.getPurchaseOrderIdentifier());
// Only individual system will lock on item line number. other system will using preq/cm doc nbr as the locking
// key
if (PurapConstants.CapitalAssetTabStrings.INDIVIDUAL_ASSETS.equalsIgnoreCase(poDocument.getCapitalAssetSystemTypeCode())) {
lockingInformation = itemAsset.getAccountsPayableLineItemIdentifier().toString();
}
// release the asset lock no matter if it's Asset global or Asset Payment since the CAB user can create Asset global
// doc even if Purap Asset numbers existing.
if (isAccountsPayableItemLineFullyProcessed(purapDocument, lockingInformation)) {
getCapitalAssetManagementModuleService().deleteAssetLocks(purapDocument.getDocumentNumber(), lockingInformation);
}
}
}
}
/**
* If lockingInformation is not empty, check all item lines from the same PurAp item are fully processed. If lockingInformation
* is empty, we check all items from the same PREQ/CM document processed as fully processed.
*
* @param itemAsset
* @return
*/
protected boolean isAccountsPayableItemLineFullyProcessed(PurchasingAccountsPayableDocument purapDocument, String lockingInformation) {
for (PurchasingAccountsPayableItemAsset item : purapDocument.getPurchasingAccountsPayableItemAssets()) {
if ((StringUtils.isBlank(lockingInformation) && !CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS.equals(item.getActivityStatusCode())) || (StringUtils.isNotBlank(lockingInformation) && item.getAccountsPayableLineItemIdentifier().equals(lockingInformation) && !CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS.equals(item.getActivityStatusCode()))) {
return false;
}
}
return true;
}
/**
* Check if Gl Entry related accounts are fully processed
*
* @param glEntry
* @return
*/
protected boolean isGlEntryFullyProcessed(GeneralLedgerEntry glEntry) {
for (PurchasingAccountsPayableLineAssetAccount account : glEntry.getPurApLineAssetAccounts()) {
if (!CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS.equalsIgnoreCase(account.getActivityStatusCode())) {
return false;
}
}
return true;
}
/**
* Check if PurApDocument related items are fully processed.
*
* @param purapDocument
* @return
*/
protected boolean isDocumentFullyProcessed(PurchasingAccountsPayableDocument purapDocument) {
for (PurchasingAccountsPayableItemAsset item : purapDocument.getPurchasingAccountsPayableItemAssets()) {
if (!CabConstants.ActivityStatusCode.PROCESSED_IN_CAMS.equalsIgnoreCase(item.getActivityStatusCode())) {
return false;
}
}
return true;
}
/**
* Build the appropriate note text being set to the purchase order document.
*
* @param documentType
* @param assetNumbers
* @return
*/
private String buildNoteTextForPurApDoc(String documentType, List<Long> assetNumbers) {
StringBuffer noteText = new StringBuffer();
if (DocumentTypeName.ASSET_ADD_GLOBAL.equalsIgnoreCase(documentType)) {
noteText.append("Asset Numbers have been created for this document: ");
}
else {
noteText.append("Existing Asset Numbers have been applied for this document: ");
}
for (int i = 0; i < assetNumbers.size(); i++) {
noteText.append(assetNumbers.get(i).toString());
if (i < assetNumbers.size() - 1) {
noteText.append(", ");
}
}
return noteText.toString();
}
/**
* Acquire asset numbers from CAMS asset payment document.
*
* @param documentNumber
* @param assetNumbers
*/
private List<Long> getAssetNumbersFromAssetGlobal(String documentNumber) {
List<Long> assetNumbers = new ArrayList<Long>();
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CamsPropertyConstants.AssetGlobalDetail.DOCUMENT_NUMBER, documentNumber);
Collection<AssetGlobalDetail> assetGlobalDetails = this.getBusinessObjectService().findMatching(AssetGlobalDetail.class, fieldValues);
for (AssetGlobalDetail detail : assetGlobalDetails) {
assetNumbers.add(detail.getCapitalAssetNumber());
}
return assetNumbers;
}
/**
* Acquire asset numbers from CAMS asset global document.
*
* @param documentNumber
* @param assetNumbers
*/
private List<Long> getAssetNumbersFromAssetPayment(String documentNumber) {
List<Long> assetNumbers = new ArrayList<Long>();
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CamsPropertyConstants.DOCUMENT_NUMBER, documentNumber);
Collection<AssetPaymentAssetDetail> paymentAssetDetails = this.getBusinessObjectService().findMatching(AssetPaymentAssetDetail.class, fieldValues);
for (AssetPaymentAssetDetail detail : paymentAssetDetails) {
if (ObjectUtils.isNotNull(detail.getAsset())) {
assetNumbers.add(detail.getCapitalAssetNumber());
}
}
return assetNumbers;
}
/**
* Query PurchasingAccountsPayableItemAsset and return the purchaseOrderIdentifier if the given documentNumber is initiated from
* the PurAp line.
*
* @param documentNumber
* @return
*/
private Integer getPurchaseOrderIdentifier(String camsDocumentNumber) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CabPropertyConstants.PurchasingAccountsPayableItemAsset.CAMS_DOCUMENT_NUMBER, camsDocumentNumber);
Collection<PurchasingAccountsPayableItemAsset> matchingItems = this.getBusinessObjectService().findMatching(PurchasingAccountsPayableItemAsset.class, fieldValues);
for (PurchasingAccountsPayableItemAsset item : matchingItems) {
if (ObjectUtils.isNull(item.getPurchasingAccountsPayableDocument())) {
item.refreshReferenceObject(CabPropertyConstants.PurchasingAccountsPayableItemAsset.PURCHASING_ACCOUNTS_PAYABLE_DOCUMENT);
}
return item.getPurchasingAccountsPayableDocument().getPurchaseOrderIdentifier();
}
return null;
}
/**
* @see org.kuali.kfs.integration.cab.CapitalAssetBuilderModuleService#getCurrentPurchaseOrderDocumentNumber(java.lang.String)
*/
public String getCurrentPurchaseOrderDocumentNumber(String camsDocumentNumber) {
Integer poId = getPurchaseOrderIdentifier(camsDocumentNumber);
if (poId != null) {
PurchaseOrderDocument poDocument = getPurApInfoService().getCurrentDocumentForPurchaseOrderIdentifier(poId);
if (ObjectUtils.isNotNull(poDocument)) {
return poDocument.getDocumentNumber();
}
}
return null;
}
/**
* Activates CAB GL Lines
*
* @param documentNumber String
*/
protected void activateCabGlLines(String documentNumber) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CabPropertyConstants.PurchasingAccountsPayableItemAsset.CAMS_DOCUMENT_NUMBER, documentNumber);
Collection<GeneralLedgerEntryAsset> matchingGlAssets = this.getBusinessObjectService().findMatching(GeneralLedgerEntryAsset.class, fieldValues);
if (matchingGlAssets != null && !matchingGlAssets.isEmpty()) {
for (GeneralLedgerEntryAsset generalLedgerEntryAsset : matchingGlAssets) {
GeneralLedgerEntry generalLedgerEntry = generalLedgerEntryAsset.getGeneralLedgerEntry();
generalLedgerEntry.setTransactionLedgerSubmitAmount(KualiDecimal.ZERO);
generalLedgerEntry.setActivityStatusCode(CabConstants.ActivityStatusCode.NEW);
this.getBusinessObjectService().save(generalLedgerEntry);
this.getBusinessObjectService().delete(generalLedgerEntryAsset);
}
}
}
/**
* Activates PO Lines
*
* @param documentNumber String
*/
protected void activateCabPOLines(String documentNumber) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(CabPropertyConstants.PurchasingAccountsPayableItemAsset.CAMS_DOCUMENT_NUMBER, documentNumber);
Collection<PurchasingAccountsPayableItemAsset> matchingPoAssets = this.getBusinessObjectService().findMatching(PurchasingAccountsPayableItemAsset.class, fieldValues);
if (matchingPoAssets != null && !matchingPoAssets.isEmpty()) {
for (PurchasingAccountsPayableItemAsset itemAsset : matchingPoAssets) {
PurchasingAccountsPayableDocument purapDocument = itemAsset.getPurchasingAccountsPayableDocument();
purapDocument.setActivityStatusCode(CabConstants.ActivityStatusCode.MODIFIED);
this.getBusinessObjectService().save(purapDocument);
itemAsset.setActivityStatusCode(CabConstants.ActivityStatusCode.MODIFIED);
this.getBusinessObjectService().save(itemAsset);
List<PurchasingAccountsPayableLineAssetAccount> lineAssetAccounts = itemAsset.getPurchasingAccountsPayableLineAssetAccounts();
for (PurchasingAccountsPayableLineAssetAccount assetAccount : lineAssetAccounts) {
assetAccount.setActivityStatusCode(CabConstants.ActivityStatusCode.MODIFIED);
this.getBusinessObjectService().save(assetAccount);
GeneralLedgerEntry generalLedgerEntry = assetAccount.getGeneralLedgerEntry();
KualiDecimal submitAmount = generalLedgerEntry.getTransactionLedgerSubmitAmount();
if (submitAmount == null) {
submitAmount = KualiDecimal.ZERO;
}
submitAmount = submitAmount.subtract(assetAccount.getItemAccountTotalAmount());
generalLedgerEntry.setTransactionLedgerSubmitAmount(submitAmount);
generalLedgerEntry.setActivityStatusCode(CabConstants.ActivityStatusCode.MODIFIED);
this.getBusinessObjectService().save(generalLedgerEntry);
}
}
}
}
/**
* gets the document type based on the instance of a class
*
* @param accountingDocument
* @return
*/
private String getDocumentTypeName(AccountingDocument accountingDocument) {
String documentTypeName = null;
if (accountingDocument instanceof YearEndGeneralErrorCorrectionDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.YEAR_END_GENERAL_ERROR_CORRECTION;
else if (accountingDocument instanceof YearEndDistributionOfIncomeAndExpenseDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.YEAR_END_DISTRIBUTION_OF_INCOME_AND_EXPENSE;
else if (accountingDocument instanceof ServiceBillingDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.SERVICE_BILLING;
else if (accountingDocument instanceof GeneralErrorCorrectionDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.GENERAL_ERROR_CORRECTION;
else if (accountingDocument instanceof CashReceiptDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.CASH_RECEIPT;
else if (accountingDocument instanceof DistributionOfIncomeAndExpenseDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.DISTRIBUTION_OF_INCOME_AND_EXPENSE;
else if (accountingDocument instanceof InternalBillingDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.INTERNAL_BILLING;
else if (accountingDocument instanceof ProcurementCardDocument)
documentTypeName = KFSConstants.FinancialDocumentTypeCodes.PROCUREMENT_CARD;
else
throw new RuntimeException("Invalid FP document type.");
return documentTypeName;
}
public ParameterService getParameterService() {
return SpringContext.getBean(ParameterService.class);
}
public BusinessObjectService getBusinessObjectService() {
return SpringContext.getBean(BusinessObjectService.class);
}
public DataDictionaryService getDataDictionaryService() {
return SpringContext.getBean(DataDictionaryService.class);
}
public AssetService getAssetService() {
return SpringContext.getBean(AssetService.class);
}
public KualiModuleService getKualiModuleService() {
return SpringContext.getBean(KualiModuleService.class);
}
public CapitalAssetManagementModuleService getCapitalAssetManagementModuleService() {
return SpringContext.getBean(CapitalAssetManagementModuleService.class);
}
private PurApInfoService getPurApInfoService() {
return SpringContext.getBean(PurApInfoService.class);
}
}
| fix for Jira KULPURAP-4046
| work/src/org/kuali/kfs/module/cab/service/impl/CapitalAssetBuilderModuleServiceImpl.java | fix for Jira KULPURAP-4046 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.