answer
stringlengths 17
10.2M
|
|---|
package org.threadly.concurrent;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Delayed;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.LockSupport;
import org.threadly.concurrent.BlockingQueueConsumer.ConsumerAcceptor;
import org.threadly.concurrent.collections.DynamicDelayQueue;
import org.threadly.concurrent.collections.DynamicDelayedUpdater;
import org.threadly.concurrent.future.ListenableFuture;
import org.threadly.concurrent.future.ListenableFutureTask;
import org.threadly.concurrent.future.ListenableRunnableFuture;
import org.threadly.concurrent.limiter.PrioritySchedulerLimiter;
import org.threadly.concurrent.lock.LockFactory;
import org.threadly.concurrent.lock.NativeLock;
import org.threadly.concurrent.lock.VirtualLock;
/**
* Executor to run tasks, schedule tasks.
* Unlike {@link java.util.concurrent.ScheduledThreadPoolExecutor}
* this scheduled executor's pool size can grow and shrink
* based off usage. It also has the benefit that you can
* provide "low priority" tasks which will attempt to use
* existing workers and not instantly create new threads on
* demand. Thus allowing you to better take the benefits
* of a thread pool for tasks which specific execution time
* is less important.
*
* @author jent - Mike Jensen
*/
public class PriorityScheduledExecutor implements PrioritySchedulerInterface,
LockFactory {
protected static final TaskPriority DEFAULT_PRIORITY = TaskPriority.High;
protected static final int DEFAULT_LOW_PRIORITY_MAX_WAIT_IN_MS = 500;
protected static final boolean DEFAULT_NEW_THREADS_DAEMON = true;
protected static final int WORKER_CONTENTION_LEVEL = 2; // level at which no worker contention is considered
protected static final int LOW_PRIORITY_WAIT_TOLLERANCE_IN_MS = 2;
protected static final String QUEUE_CONSUMER_THREAD_NAME_HIGH_PRIORITY;
protected static final String QUEUE_CONSUMER_THREAD_NAME_LOW_PRIORITY;
static {
String threadNameSuffix = "task consumer for " + PriorityScheduledExecutor.class.getSimpleName();
QUEUE_CONSUMER_THREAD_NAME_HIGH_PRIORITY = "high priority " + threadNameSuffix;
QUEUE_CONSUMER_THREAD_NAME_LOW_PRIORITY = "low priority " + threadNameSuffix;
}
protected final TaskPriority defaultPriority;
protected final VirtualLock highPriorityLock;
protected final VirtualLock lowPriorityLock;
protected final VirtualLock workersLock;
protected final DynamicDelayQueue<TaskWrapper> highPriorityQueue;
protected final DynamicDelayQueue<TaskWrapper> lowPriorityQueue;
protected final Deque<Worker> availableWorkers; // is locked around workersLock
protected final ThreadFactory threadFactory;
protected final TaskConsumer highPriorityConsumer; // is locked around highPriorityLock
protected final TaskConsumer lowPriorityConsumer; // is locked around lowPriorityLock
private final AtomicBoolean shutdownStarted;
private volatile boolean shutdownFinishing; // once true, never goes to false
private volatile int corePoolSize;
private volatile int maxPoolSize;
private volatile long keepAliveTimeInMs;
private volatile long maxWaitForLowPriorityInMs;
private volatile boolean allowCorePoolTimeout;
private long lastHighDelay; // is locked around workersLock
private int currentPoolSize; // is locked around workersLock
/**
* Constructs a new thread pool, though no threads will be started
* till it accepts it's first request. This constructs a default
* priority of high (which makes sense for most use cases).
* It also defaults low priority worker wait as 500ms. It also
* defaults to all newly created threads being daemon threads.
*
* @param corePoolSize pool size that should be maintained
* @param maxPoolSize maximum allowed thread count
* @param keepAliveTimeInMs time to wait for a given thread to be idle before killing
*/
public PriorityScheduledExecutor(int corePoolSize, int maxPoolSize,
long keepAliveTimeInMs) {
this(corePoolSize, maxPoolSize, keepAliveTimeInMs,
DEFAULT_PRIORITY, DEFAULT_LOW_PRIORITY_MAX_WAIT_IN_MS,
DEFAULT_NEW_THREADS_DAEMON);
}
/**
* Constructs a new thread pool, though no threads will be started
* till it accepts it's first request. This constructs a default
* priority of high (which makes sense for most use cases).
* It also defaults low priority worker wait as 500ms.
*
* @param corePoolSize pool size that should be maintained
* @param maxPoolSize maximum allowed thread count
* @param keepAliveTimeInMs time to wait for a given thread to be idle before killing
* @param useDaemonThreads boolean for if newly created threads should be daemon
*/
public PriorityScheduledExecutor(int corePoolSize, int maxPoolSize,
long keepAliveTimeInMs, boolean useDaemonThreads) {
this(corePoolSize, maxPoolSize, keepAliveTimeInMs,
DEFAULT_PRIORITY, DEFAULT_LOW_PRIORITY_MAX_WAIT_IN_MS,
useDaemonThreads);
}
/**
* Constructs a new thread pool, though no threads will be started
* till it accepts it's first request. This provides the extra
* parameters to tune what tasks submitted without a priority will be
* scheduled as. As well as the maximum wait for low priority tasks.
* The longer low priority tasks wait for a worker, the less chance they will
* have to make a thread. But it also makes low priority tasks execution time
* less predictable.
*
* @param corePoolSize pool size that should be maintained
* @param maxPoolSize maximum allowed thread count
* @param keepAliveTimeInMs time to wait for a given thread to be idle before killing
* @param defaultPriority priority to give tasks which do not specify it
* @param maxWaitForLowPriorityInMs time low priority tasks wait for a worker
*/
public PriorityScheduledExecutor(int corePoolSize, int maxPoolSize,
long keepAliveTimeInMs, TaskPriority defaultPriority,
long maxWaitForLowPriorityInMs) {
this(corePoolSize, maxPoolSize, keepAliveTimeInMs,
defaultPriority, maxWaitForLowPriorityInMs,
DEFAULT_NEW_THREADS_DAEMON);
}
/**
* Constructs a new thread pool, though no threads will be started
* till it accepts it's first request. This provides the extra
* parameters to tune what tasks submitted without a priority will be
* scheduled as. As well as the maximum wait for low priority tasks.
* The longer low priority tasks wait for a worker, the less chance they will
* have to make a thread. But it also makes low priority tasks execution time
* less predictable.
*
* @param corePoolSize pool size that should be maintained
* @param maxPoolSize maximum allowed thread count
* @param keepAliveTimeInMs time to wait for a given thread to be idle before killing
* @param defaultPriority priority to give tasks which do not specify it
* @param maxWaitForLowPriorityInMs time low priority tasks wait for a worker
* @param useDaemonThreads boolean for if newly created threads should be daemon
*/
public PriorityScheduledExecutor(int corePoolSize, int maxPoolSize,
long keepAliveTimeInMs, TaskPriority defaultPriority,
long maxWaitForLowPriorityInMs,
final boolean useDaemonThreads) {
this(corePoolSize, maxPoolSize, keepAliveTimeInMs,
defaultPriority, maxWaitForLowPriorityInMs,
new ThreadFactory() {
private final ThreadFactory defaultFactory = Executors.defaultThreadFactory();
@Override
public Thread newThread(Runnable runnable) {
Thread thread = defaultFactory.newThread(runnable);
thread.setDaemon(useDaemonThreads);
return thread;
}
});
}
/**
* Constructs a new thread pool, though no threads will be started
* till it accepts it's first request. This provides the extra
* parameters to tune what tasks submitted without a priority will be
* scheduled as. As well as the maximum wait for low priority tasks.
* The longer low priority tasks wait for a worker, the less chance they will
* have to make a thread. But it also makes low priority tasks execution time
* less predictable.
*
* @param corePoolSize pool size that should be maintained
* @param maxPoolSize maximum allowed thread count
* @param keepAliveTimeInMs time to wait for a given thread to be idle before killing
* @param defaultPriority priority to give tasks which do not specify it
* @param maxWaitForLowPriorityInMs time low priority tasks wait for a worker
* @param threadFactory thread factory for producing new threads within executor
*/
public PriorityScheduledExecutor(int corePoolSize, int maxPoolSize,
long keepAliveTimeInMs, TaskPriority defaultPriority,
long maxWaitForLowPriorityInMs, ThreadFactory threadFactory) {
if (corePoolSize < 1) {
throw new IllegalArgumentException("corePoolSize must be >= 1");
} else if (maxPoolSize < corePoolSize) {
throw new IllegalArgumentException("maxPoolSize must be >= corePoolSize");
} else if (keepAliveTimeInMs < 0) {
throw new IllegalArgumentException("keepAliveTimeInMs must be >= 0");
} else if (maxWaitForLowPriorityInMs < 0) {
throw new IllegalArgumentException("maxWaitForLowPriorityInMs must be >= 0");
}
if (defaultPriority == null) {
defaultPriority = DEFAULT_PRIORITY;
}
if (threadFactory == null) {
threadFactory = Executors.defaultThreadFactory();
}
this.defaultPriority = defaultPriority;
highPriorityLock = makeLock();
lowPriorityLock = makeLock();
workersLock = makeLock();
highPriorityQueue = new DynamicDelayQueue<TaskWrapper>(highPriorityLock);
lowPriorityQueue = new DynamicDelayQueue<TaskWrapper>(lowPriorityLock);
availableWorkers = new ArrayDeque<Worker>(maxPoolSize);
this.threadFactory = threadFactory;
highPriorityConsumer = new TaskConsumer(highPriorityQueue, highPriorityLock,
new ConsumerAcceptor<TaskWrapper>() {
@Override
public void acceptConsumedItem(TaskWrapper task) throws InterruptedException {
runHighPriorityTask(task);
}
});
lowPriorityConsumer = new TaskConsumer(lowPriorityQueue, lowPriorityLock,
new ConsumerAcceptor<TaskWrapper>() {
@Override
public void acceptConsumedItem(TaskWrapper task) throws InterruptedException {
runLowPriorityTask(task);
}
});
shutdownStarted = new AtomicBoolean(false);
shutdownFinishing = false;
this.corePoolSize = corePoolSize;
this.maxPoolSize = maxPoolSize;
this.keepAliveTimeInMs = keepAliveTimeInMs;
this.maxWaitForLowPriorityInMs = maxWaitForLowPriorityInMs;
this.allowCorePoolTimeout = false;
this.lastHighDelay = 0;
currentPoolSize = 0;
}
/**
* If a section of code wants a different default priority, or wanting to provide
* a specific default priority in for {@link CallableDistributor},
* {@link TaskExecutorDistributor}, or {@link TaskSchedulerDistributor}.
*
* @param priority default priority for PrioritySchedulerInterface implementation
* @return a PrioritySchedulerInterface with the default priority specified
*/
public PrioritySchedulerInterface makeWithDefaultPriority(TaskPriority priority) {
if (priority == defaultPriority) {
return this;
} else {
return new PrioritySchedulerWrapper(this, priority);
}
}
@Override
public TaskPriority getDefaultPriority() {
return defaultPriority;
}
/**
* Getter for the current set core pool size.
*
* @return current core pool size
*/
public int getCorePoolSize() {
return corePoolSize;
}
/**
* Getter for the currently set max pool size.
*
* @return current max pool size
*/
public int getMaxPoolSize() {
return maxPoolSize;
}
/**
* Getter for the currently set keep alive time.
*
* @return current keep alive time
*/
public long getKeepAliveTime() {
return keepAliveTimeInMs;
}
/**
* Getter for the current qty of workers constructed (ether running or idle).
*
* @return current worker count
*/
public int getCurrentPoolSize() {
synchronized (workersLock) {
return currentPoolSize;
}
}
/**
* Change the set core pool size.
*
* @param corePoolSize New pool size. Must be >= 1 and <= the set max pool size.
*/
public void setCorePoolSize(int corePoolSize) {
if (corePoolSize < 1) {
throw new IllegalArgumentException("corePoolSize must be >= 1");
} else if (maxPoolSize < corePoolSize) {
throw new IllegalArgumentException("maxPoolSize must be >= corePoolSize");
}
this.corePoolSize = corePoolSize;
}
/**
* Change the set max pool size.
*
* @param maxPoolSize New max pool size. Must be >= 1 and >= the set core pool size.
*/
public void setMaxPoolSize(int maxPoolSize) {
if (maxPoolSize < 1) {
throw new IllegalArgumentException("maxPoolSize must be >= 1");
} else if (maxPoolSize < corePoolSize) {
throw new IllegalArgumentException("maxPoolSize must be >= corePoolSize");
}
this.maxPoolSize = maxPoolSize;
}
/**
* Change the set idle thread keep alive time.
*
* @param keepAliveTimeInMs New keep alive time in milliseconds. Must be >= 0.
*/
public void setKeepAliveTime(long keepAliveTimeInMs) {
if (keepAliveTimeInMs < 0) {
throw new IllegalArgumentException("keepAliveTimeInMs must be >= 0");
}
this.keepAliveTimeInMs = keepAliveTimeInMs;
}
/**
* Changes the max wait time for an idle worker for low priority tasks.
* Changing this will only take effect for future low priority tasks, it
* will have no impact for the current low priority task attempting to get
* a worker.
*
* @param maxWaitForLowPriorityInMs new time to wait for a thread in milliseconds. Must be >= 0.
*/
public void setMaxWaitForLowPriority(long maxWaitForLowPriorityInMs) {
if (maxWaitForLowPriorityInMs < 0) {
throw new IllegalArgumentException("maxWaitForLowPriorityInMs must be >= 0");
}
this.maxWaitForLowPriorityInMs = maxWaitForLowPriorityInMs;
}
/**
* Getter for the maximum amount of time a low priority task will
* wait for an available worker.
*
* @return currently set max wait for low priority task
*/
public long getMaxWaitForLowPriority() {
return maxWaitForLowPriorityInMs;
}
/**
* Returns how many tasks are either waiting to be executed,
* or are scheduled to be executed at a future point.
*
* @return qty of tasks waiting execution or scheduled to be executed later
*/
public int getScheduledTaskCount() {
return highPriorityQueue.size() + lowPriorityQueue.size();
}
/**
* Returns a count of how many tasks are either waiting to be executed,
* or are scheduled to be executed at a future point for a specific priority.
*
* @param priority priority for tasks to be counted
* @return qty of tasks waiting execution or scheduled to be executed later
*/
public int getScheduledTaskCount(TaskPriority priority) {
if (priority == null) {
return getScheduledTaskCount();
}
switch (priority) {
case High:
return highPriorityQueue.size();
case Low:
return lowPriorityQueue.size();
default:
throw new UnsupportedOperationException("Not implemented for priority: " + priority);
}
}
/**
* Prestarts all core threads. This will make new idle workers to accept future tasks.
*/
public void prestartAllCoreThreads() {
synchronized (workersLock) {
boolean startedThreads = false;
while (currentPoolSize < corePoolSize) {
availableWorkers.addFirst(makeNewWorker());
startedThreads = true;
}
if (startedThreads) {
workersLock.signalAll();
}
}
}
/**
* Changes the setting weather core threads are allowed to
* be killed if they remain idle.
*
* @param value true if core threads should be expired when idle.
*/
public void allowCoreThreadTimeOut(boolean value) {
allowCorePoolTimeout = value;
}
@Override
public boolean isShutdown() {
return shutdownStarted.get();
}
protected List<Runnable> clearTaskQueue() {
synchronized (highPriorityLock) {
synchronized (lowPriorityLock) {
highPriorityConsumer.stop();
lowPriorityConsumer.stop();
List<Runnable> removedTasks = new ArrayList<Runnable>(highPriorityQueue.size() +
lowPriorityQueue.size());
synchronized (highPriorityQueue.getLock()) {
Iterator<TaskWrapper> it = highPriorityQueue.iterator();
while (it.hasNext()) {
TaskWrapper tw = it.next();
tw.cancel();
removedTasks.add(tw.task);
}
lowPriorityQueue.clear();
}
synchronized (lowPriorityQueue.getLock()) {
Iterator<TaskWrapper> it = lowPriorityQueue.iterator();
while (it.hasNext()) {
TaskWrapper tw = it.next();
tw.cancel();
removedTasks.add(tw.task);
}
lowPriorityQueue.clear();
}
return removedTasks;
}
}
}
protected void shutdownAllWorkers() {
synchronized (workersLock) {
Iterator<Worker> it = availableWorkers.iterator();
while (it.hasNext()) {
Worker w = it.next();
it.remove();
killWorker(w);
}
}
}
/**
* Stops any new tasks from being submitted to the pool. But allows all currently scheduled
* tasks to be run. If scheduled tasks are present they will also be unable to reschedule.
*
* If you wish to not want to run any queued tasks you should use {#link shutdownNow()).
*/
public void shutdown() {
if (! shutdownStarted.getAndSet(true)) {
addToHighPriorityQueue(new OneTimeTaskWrapper(new ShutdownRunnable(),
TaskPriority.High, 1));
}
}
/**
* Stops any new tasks from being able to be executed and removes workers from the pool.
*
* This implementation refuses new submissions after this call. And will NOT interrupt any
* tasks which are currently running. But any tasks which are waiting in queue to be run
* (but have not started yet), will not be run. Those waiting tasks will be removed, and
* as workers finish with their current tasks the threads will be joined.
*
* @return List of runnables which were waiting to execute
*/
public List<Runnable> shutdownNow() {
shutdownStarted.set(true);
shutdownFinishing = true;
List<Runnable> awaitingTasks = clearTaskQueue();
shutdownAllWorkers();
return awaitingTasks;
}
protected void verifyNotShutdown() {
if (isShutdown()) {
throw new IllegalStateException("Thread pool shutdown");
}
}
/**
* Makes a new {@link PrioritySchedulerLimiter} that uses this pool as it's execution source.
*
* @param maxConcurrency maximum number of threads to run in parallel in sub pool
* @return newly created {@link PrioritySchedulerLimiter} that uses this pool as it's execution source
*/
public PrioritySchedulerInterface makeSubPool(int maxConcurrency) {
return makeSubPool(maxConcurrency, null);
}
/**
* Makes a new {@link PrioritySchedulerLimiter} that uses this pool as it's execution source.
*
* @param maxConcurrency maximum number of threads to run in parallel in sub pool
* @param subPoolName name to describe threads while running under this sub pool
* @return newly created {@link PrioritySchedulerLimiter} that uses this pool as it's execution source
*/
public PrioritySchedulerInterface makeSubPool(int maxConcurrency, String subPoolName) {
if (maxConcurrency > corePoolSize) {
throw new IllegalArgumentException("A sub pool should be smaller than the parent pool");
}
return new PrioritySchedulerLimiter(this, maxConcurrency, subPoolName);
}
protected static boolean removeFromTaskQueue(DynamicDelayQueue<TaskWrapper> queue,
Runnable task) {
synchronized (queue.getLock()) {
Iterator<TaskWrapper> it = queue.iterator();
while (it.hasNext()) {
TaskWrapper tw = it.next();
if (tw.task.equals(task)) {
tw.cancel();
it.remove();
return true;
}
}
}
return false;
}
/**
* Removes the task from the execution queue. It is possible
* for the task to still run until this call has returned.
*
* @param task The original task provided to the executor
* @return true if the task was found and removed
*/
public boolean remove(Runnable task) {
return removeFromTaskQueue(highPriorityQueue, task) ||
removeFromTaskQueue(lowPriorityQueue, task);
}
@Override
public void execute(Runnable task) {
schedule(task, 0, defaultPriority);
}
@Override
public void execute(Runnable task, TaskPriority priority) {
schedule(task, 0, priority);
}
@Override
public ListenableFuture<?> submit(Runnable task) {
return submitScheduled(task, null, 0, defaultPriority);
}
@Override
public <T> ListenableFuture<T> submit(Runnable task, T result) {
return submitScheduled(task, result, 0, defaultPriority);
}
@Override
public ListenableFuture<?> submit(Runnable task, TaskPriority priority) {
return submitScheduled(task, null, 0, priority);
}
@Override
public <T> ListenableFuture<T> submit(Runnable task, T result, TaskPriority priority) {
return submitScheduled(task, result, 0, priority);
}
@Override
public <T> ListenableFuture<T> submit(Callable<T> task) {
return submitScheduled(task, 0, defaultPriority);
}
@Override
public <T> ListenableFuture<T> submit(Callable<T> task, TaskPriority priority) {
return submitScheduled(task, 0, priority);
}
@Override
public void schedule(Runnable task, long delayInMs) {
schedule(task, delayInMs, defaultPriority);
}
@Override
public void schedule(Runnable task, long delayInMs,
TaskPriority priority) {
if (task == null) {
throw new IllegalArgumentException("Must provide a task");
} else if (delayInMs < 0) {
throw new IllegalArgumentException("delayInMs must be >= 0");
}
if (priority == null) {
priority = defaultPriority;
}
addToQueue(new OneTimeTaskWrapper(task, priority, delayInMs));
}
@Override
public ListenableFuture<?> submitScheduled(Runnable task, long delayInMs) {
return submitScheduled(task, delayInMs, defaultPriority);
}
@Override
public <T> ListenableFuture<T> submitScheduled(Runnable task, T result, long delayInMs) {
return submitScheduled(task, result, delayInMs, defaultPriority);
}
@Override
public ListenableFuture<?> submitScheduled(Runnable task, long delayInMs,
TaskPriority priority) {
return submitScheduled(task, null, delayInMs, priority);
}
@Override
public <T> ListenableFuture<T> submitScheduled(Runnable task, T result,
long delayInMs,
TaskPriority priority) {
if (task == null) {
throw new IllegalArgumentException("Must provide a task");
} else if (delayInMs < 0) {
throw new IllegalArgumentException("delayInMs must be >= 0");
}
if (priority == null) {
priority = defaultPriority;
}
ListenableRunnableFuture<T> rf = new ListenableFutureTask<T>(false, task, result);
addToQueue(new OneTimeTaskWrapper(rf, priority, delayInMs));
return rf;
}
@Override
public <T> ListenableFuture<T> submitScheduled(Callable<T> task, long delayInMs) {
return submitScheduled(task, delayInMs, defaultPriority);
}
@Override
public <T> ListenableFuture<T> submitScheduled(Callable<T> task, long delayInMs,
TaskPriority priority) {
if (task == null) {
throw new IllegalArgumentException("Must provide a task");
} else if (delayInMs < 0) {
throw new IllegalArgumentException("delayInMs must be >= 0");
}
if (priority == null) {
priority = defaultPriority;
}
ListenableRunnableFuture<T> rf = new ListenableFutureTask<T>(false, task);
addToQueue(new OneTimeTaskWrapper(rf, priority, delayInMs));
return rf;
}
@Override
public void scheduleWithFixedDelay(Runnable task, long initialDelay,
long recurringDelay) {
scheduleWithFixedDelay(task, initialDelay, recurringDelay,
defaultPriority);
}
@Override
public void scheduleWithFixedDelay(Runnable task, long initialDelay,
long recurringDelay, TaskPriority priority) {
if (task == null) {
throw new IllegalArgumentException("Must provide a task");
} else if (initialDelay < 0) {
throw new IllegalArgumentException("initialDelay must be >= 0");
} else if (recurringDelay < 0) {
throw new IllegalArgumentException("recurringDelay must be >= 0");
}
if (priority == null) {
priority = defaultPriority;
}
addToQueue(new RecurringTaskWrapper(task, priority, initialDelay, recurringDelay));
}
protected void addToQueue(TaskWrapper task) {
verifyNotShutdown();
switch (task.priority) {
case High:
addToHighPriorityQueue(task);
break;
case Low:
addToLowPriorityQueue(task);
break;
default:
throw new UnsupportedOperationException("Priority not implemented: " + task.priority);
}
}
private void addToHighPriorityQueue(TaskWrapper task) {
ClockWrapper.stopForcingUpdate();
try {
ClockWrapper.updateClock();
highPriorityQueue.add(task);
} finally {
ClockWrapper.resumeForcingUpdate();
}
highPriorityConsumer.maybeStart(threadFactory,
QUEUE_CONSUMER_THREAD_NAME_HIGH_PRIORITY);
}
private void addToLowPriorityQueue(TaskWrapper task) {
ClockWrapper.stopForcingUpdate();
try {
ClockWrapper.updateClock();
lowPriorityQueue.add(task);
} finally {
ClockWrapper.resumeForcingUpdate();
}
lowPriorityConsumer.maybeStart(threadFactory,
QUEUE_CONSUMER_THREAD_NAME_LOW_PRIORITY);
}
protected Worker getExistingWorker(long maxWaitTimeInMs) throws InterruptedException {
synchronized (workersLock) {
long startTime = ClockWrapper.getAccurateTime();
long waitTime = maxWaitTimeInMs;
while (availableWorkers.isEmpty() && waitTime > 0) {
if (waitTime == Long.MAX_VALUE) { // prevent overflow
workersLock.await();
} else {
long elapsedTime = ClockWrapper.getAccurateTime() - startTime;
waitTime = maxWaitTimeInMs - elapsedTime;
if (waitTime > 0) {
workersLock.await(waitTime);
}
}
}
if (availableWorkers.isEmpty()) {
return null; // we exceeded the wait time
} else {
// always remove from the front, to get the newest worker
return availableWorkers.removeFirst();
}
}
}
protected Worker makeNewWorker() {
synchronized (workersLock) {
Worker w = new Worker();
currentPoolSize++;
w.start();
// will be added to available workers when done with first task
return w;
}
}
protected void runHighPriorityTask(TaskWrapper task) throws InterruptedException {
Worker w = null;
synchronized (workersLock) {
if (! shutdownFinishing) {
if (currentPoolSize >= maxPoolSize) {
lastHighDelay = task.getDelayEstimateInMillis();
// we can't make the pool any bigger
w = getExistingWorker(Long.MAX_VALUE);
} else {
lastHighDelay = 0;
if (availableWorkers.isEmpty()) {
w = makeNewWorker();
} else {
// always remove from the front, to get the newest worker
w = availableWorkers.removeFirst();
}
}
}
}
if (w != null) { // may be null if shutdown
w.nextTask(task);
}
}
protected void runLowPriorityTask(TaskWrapper task) throws InterruptedException {
Worker w = null;
synchronized (workersLock) {
if (! shutdownFinishing) {
// wait for high priority tasks that have been waiting longer than us if all workers are consumed
long waitAmount;
while (currentPoolSize >= maxPoolSize &&
availableWorkers.size() < WORKER_CONTENTION_LEVEL && // only care if there is worker contention
! shutdownFinishing &&
(waitAmount = task.getDelayEstimateInMillis() - lastHighDelay) > LOW_PRIORITY_WAIT_TOLLERANCE_IN_MS) {
if (highPriorityQueue.isEmpty()) {
lastHighDelay = 0; // no waiting high priority tasks, so no need to wait on low priority tasks
} else {
workersLock.await(waitAmount);
ClockWrapper.updateClock(); // update for getDelayEstimateInMillis
}
}
if (! shutdownFinishing) { // check again that we are still running
long waitTime;
if (currentPoolSize >= maxPoolSize) {
waitTime = Long.MAX_VALUE;
} else {
waitTime = maxWaitForLowPriorityInMs;
}
w = getExistingWorker(waitTime);
if (w == null) {
// this means we expired past our wait time, so create a worker if we can
if (currentPoolSize >= maxPoolSize) {
// more workers were created while waiting, now have reached our max
w = getExistingWorker(Long.MAX_VALUE);
} else {
w = makeNewWorker();
}
}
}
}
}
if (w != null) { // may be null if shutdown
w.nextTask(task);
}
}
protected void lookForExpiredWorkers() {
synchronized (workersLock) {
long now = ClockWrapper.getLastKnownTime();
// we search backwards because the oldest workers will be at the back of the stack
while ((currentPoolSize > corePoolSize || allowCorePoolTimeout) &&
! availableWorkers.isEmpty() &&
now - availableWorkers.getLast().getLastRunTime() > keepAliveTimeInMs) {
Worker w = availableWorkers.removeLast();
killWorker(w);
}
}
}
private void killWorker(Worker w) {
synchronized (workersLock) {
/* we check running around workersLock since we want to make sure
* we don't decrement the pool size more than once for a single worker
*/
if (w.running) {
currentPoolSize
// it may not always be here, but it sometimes can (for example when a worker is interrupted)
availableWorkers.remove(w);
w.stop(); // will set running to false for worker
}
}
}
protected void workerDone(Worker worker) {
synchronized (workersLock) {
if (! shutdownFinishing) {
// always add to the front so older workers are at the back
availableWorkers.addFirst(worker);
lookForExpiredWorkers();
workersLock.signal();
} else {
killWorker(worker);
}
}
}
@Override
public VirtualLock makeLock() {
return new NativeLock();
}
@Override
public boolean isNativeLockFactory() {
return true;
}
/**
* Runnable which will consume tasks from the appropriate
* and given the provided implementation to get a worker
* and execute consumed tasks.
*
* @author jent - Mike Jensen
*/
protected class TaskConsumer extends BlockingQueueConsumer<TaskWrapper> {
private final VirtualLock queueLock;
public TaskConsumer(DynamicDelayQueue<TaskWrapper> queue,
VirtualLock queueLock,
ConsumerAcceptor<TaskWrapper> taskAcceptor) {
super(queue, taskAcceptor);
this.queueLock = queueLock;
}
@Override
public TaskWrapper getNext() throws InterruptedException {
TaskWrapper task;
/* must lock as same lock for removal to
* ensure that task can be found for removal
*/
synchronized (queueLock) {
task = queue.take();
task.executing(); // for recurring tasks this will put them back into the queue
}
return task;
}
}
/**
* Runnable which will run on pool threads. It
* accepts runnables to run, and tracks usage.
*
* @author jent - Mike Jensen
*/
protected class Worker implements Runnable {
protected final Thread thread;
private volatile long lastRunTime;
private volatile boolean running;
private volatile TaskWrapper nextTask;
protected Worker() {
thread = threadFactory.newThread(this);
running = false;
lastRunTime = ClockWrapper.getLastKnownTime();
nextTask = null;
}
// should only be called from killWorker
public void stop() {
if (! running) {
return;
} else {
running = false;
LockSupport.unpark(thread);
}
}
public void start() {
if (thread.isAlive()) {
return;
} else {
running = true;
thread.start();
}
}
public void nextTask(TaskWrapper task) {
if (! running) {
throw new IllegalStateException("Worker has been killed");
} else if (nextTask != null) {
throw new IllegalStateException("Already has a task");
}
nextTask = task;
LockSupport.unpark(thread);
}
public void blockTillNextTask() {
while (nextTask == null && running) {
LockSupport.park(this);
if (Thread.interrupted() && // clear interrupt
shutdownFinishing) { // if shutting down, kill worker
killWorker(this); // if provided a new task, we will still run that task before quitting
}
}
}
@Override
public void run() {
while (running) {
try {
blockTillNextTask();
if (nextTask != null) {
nextTask.run();
}
} catch (Throwable t) {
UncaughtExceptionHandler handler = Thread.getDefaultUncaughtExceptionHandler();
if (handler != null) {
handler.uncaughtException(thread, t);
} else {
t.printStackTrace(System.err);
}
} finally {
nextTask = null;
if (running) {
// only check if still running, otherwise worker has already been killed
if (Thread.interrupted() && // clear interrupt
shutdownFinishing) { // if shutting down kill worker
killWorker(this);
} else {
lastRunTime = ClockWrapper.getLastKnownTime();
workerDone(this);
}
}
}
}
}
public long getLastRunTime() {
return lastRunTime;
}
}
/**
* Behavior for task after it finishes completion.
*
* @author jent - Mike Jensen
*/
protected enum TaskType {OneTime, Recurring};
/**
* Abstract implementation for all tasks handled by this pool.
*
* @author jent - Mike Jensen
*/
protected abstract static class TaskWrapper implements Delayed, Runnable {
public final TaskType taskType;
public final TaskPriority priority;
protected final Runnable task;
protected volatile boolean canceled;
public TaskWrapper(TaskType taskType,
Runnable task,
TaskPriority priority) {
this.taskType = taskType;
this.priority = priority;
this.task = task;
canceled = false;
}
public void cancel() {
canceled = true;
if (task instanceof Future<?>) {
((Future<?>)task).cancel(false);
}
}
public abstract void executing();
protected abstract long getDelayEstimateInMillis();
@Override
public int compareTo(Delayed o) {
if (this == o) {
return 0;
} else {
long thisDelay = this.getDelay(TimeUnit.MILLISECONDS);
long otherDelay = o.getDelay(TimeUnit.MILLISECONDS);
if (thisDelay == otherDelay) {
return 0;
} else if (thisDelay > otherDelay) {
return 1;
} else {
return -1;
}
}
}
@Override
public String toString() {
return task.toString();
}
}
/**
* Wrapper for tasks which only executes once.
*
* @author jent - Mike Jensen
*/
protected static class OneTimeTaskWrapper extends TaskWrapper {
private final long runTime;
protected OneTimeTaskWrapper(Runnable task, TaskPriority priority, long delay) {
super(TaskType.OneTime, task, priority);
runTime = ClockWrapper.getAccurateTime() + delay;
}
@Override
public long getDelay(TimeUnit unit) {
return TimeUnit.MILLISECONDS.convert(runTime - ClockWrapper.getAccurateTime(), unit);
}
@Override
protected long getDelayEstimateInMillis() {
return runTime - ClockWrapper.getLastKnownTime();
}
@Override
public void executing() {
// ignored
}
@Override
public void run() {
if (! canceled) {
task.run();
}
}
}
/**
* Wrapper for tasks which reschedule after completion.
*
* @author jent - Mike Jensen
*/
protected class RecurringTaskWrapper extends TaskWrapper
implements DynamicDelayedUpdater {
private final long recurringDelay;
//private volatile long maxExpectedRuntime;
private volatile boolean executing;
private long nextRunTime;
protected RecurringTaskWrapper(Runnable task, TaskPriority priority,
long initialDelay, long recurringDelay) {
super(TaskType.Recurring, task, priority);
this.recurringDelay = recurringDelay;
//maxExpectedRuntime = -1;
executing = false;
this.nextRunTime = ClockWrapper.getAccurateTime() + initialDelay;
}
@Override
public long getDelay(TimeUnit unit) {
if (executing) {
return Long.MAX_VALUE;
} else {
return TimeUnit.MILLISECONDS.convert(getNextDelayInMillis(), unit);
}
}
private long getNextDelayInMillis() {
return nextRunTime - ClockWrapper.getAccurateTime();
}
@Override
protected long getDelayEstimateInMillis() {
return nextRunTime - ClockWrapper.getLastKnownTime();
}
@Override
public void allowDelayUpdate() {
executing = false;
}
@Override
public void executing() {
if (canceled) {
return;
}
executing = true;
/* add to queue before started, so that it can be removed if necessary
* We add to the end because the task wont re-run till it has finished,
* so there is no reason to sort at this point
*/
switch (priority) {
case High:
highPriorityQueue.addLast(this);
break;
case Low:
lowPriorityQueue.addLast(this);
break;
default:
throw new UnsupportedOperationException("Not implemented for priority: " + priority);
}
}
private void reschedule() {
nextRunTime = ClockWrapper.getAccurateTime() + recurringDelay;
// now that nextRunTime has been set, resort the queue
switch (priority) {
case High:
synchronized (highPriorityLock) {
if (! shutdownStarted.get()) {
ClockWrapper.stopForcingUpdate();
try {
ClockWrapper.updateClock();
highPriorityQueue.reposition(this, getNextDelayInMillis(), this);
} finally {
ClockWrapper.resumeForcingUpdate();
}
}
}
break;
case Low:
synchronized (lowPriorityLock) {
if (! shutdownStarted.get()) {
ClockWrapper.stopForcingUpdate();
try {
ClockWrapper.updateClock();
lowPriorityQueue.reposition(this, getNextDelayInMillis(), this);
} finally {
ClockWrapper.resumeForcingUpdate();
}
}
}
break;
default:
throw new UnsupportedOperationException("Not implemented for priority: " + priority);
}
}
@Override
public void run() {
if (canceled) {
return;
}
try {
//long startTime = ClockWrapper.getLastKnownTime();
task.run();
/*long runTime = ClockWrapper.getLastKnownTime() - startTime;
if (runTime > maxExpectedRuntime) {
maxExpectedRuntime = runTime;
}*/
} finally {
if (! canceled) {
reschedule();
}
}
}
}
/**
* Runnable to be run after all current tasks to finish the shutdown sequence.
*
* @author jent - Mike Jensen
*/
protected class ShutdownRunnable implements Runnable {
@Override
public void run() {
shutdownNow();
}
}
}
|
package policycompass.fcmmanager.services;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import javax.ws.rs.HeaderParam;
import org.codehaus.jettison.json.JSONObject;
import policycompass.fcmmanager.controllers.*;
import policycompass.fcmmanager.simulation.pcjfcm;
@Path("/fcmmanager")
public class FCMModelService {
@GET
@Path("/wekaoutputtest")
@Produces({MediaType.APPLICATION_JSON})
public Response retrieveWekaOutput() throws Exception {
Response rb = null;
rb = Response.ok(FCMModels.wekaOutputTEST()).build();
return rb;
}
@POST
@Path("/wekaoutput")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response retrieveWekaOutput(String wekaInput) throws Exception {
Response rb = null;
rb = Response.ok(FCMModels.wekaOutput(wekaInput)).build();
return rb;
}
@GET
@Path("/models")
@Produces(MediaType.APPLICATION_JSON)
public Response retrieveAllModels() throws Exception {
Response rb = null;
rb = Response.ok(FCMModels.retrieveFCMModelList()).build();
return rb;
}
@GET
@Path("/models/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response retrieveFCMModel(@HeaderParam("X-User-Path") String userPath, @HeaderParam("X-User-Token") String userToken, @PathParam("id") int id) throws Exception {
Response rb = null;
rb = Response.ok(FCMModels.retrieveFCMModel(userPath, userToken, id)).build();
return rb;
}
@GET
@Path("/modelsid")
@Produces(MediaType.APPLICATION_JSON)
public Response retrieveFCMModelID() throws Exception {
Response rb = null;
rb = Response.ok(FCMModels.getFCMModelID()).build();
return rb;
}
@POST
@Path("/models")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response createFCMModel(@HeaderParam("X-User-Path") String userPath, @HeaderParam("X-User-Token") String userToken, JSONObject fcmmodel) {
return Response.ok(FCMModels.createFCMModel(userPath, userToken, fcmmodel)).build();
// return Response.ok(fcmmodel).build();
}
@PUT
@Path("/models/{id}")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response updateFCMModel(@PathParam("id") int id, JSONObject fcmmodel,@HeaderParam("X-User-Path") String userPath, @HeaderParam("X-User-Token") String userToken) {
return Response.ok(FCMModels.updateFCMModel(id, fcmmodel, userPath, userToken)).build();
// FCMModels.updateFCMModel(id, fcmmodel);
// return Response.ok(fcmmodel).build();
}
@DELETE
@Path("/models/{id}")
@Produces({MediaType.APPLICATION_JSON})
public Response deleteFCMModel(@PathParam("id") int id, @HeaderParam("X-User-Path") String userPath, @HeaderParam("X-User-Token") String userToken) {
return Response.ok(FCMModels.deleteFCMModel(id, userPath, userToken)).build();
//return Response.status(204).build();
}
@GET
@Path("/loaddata")
@Produces(MediaType.APPLICATION_JSON)
public Response LoadDataService() throws Exception {
Response rb = null;
rb = Response.ok(FCMModels.LoadData()).build();
return rb;
}
@GET
@Path("/metrics/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response retrieveFCMModelsByMetrics(@PathParam("id") int id) throws Exception {
Response rb = null;
rb = Response.ok(FCMModels.retrieveFCMModelsListByMetrics(id)).build();
return rb;
}
@GET
@Path("/datasets/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response retrieveFCMModelsByDatasets(@PathParam("id") int id) throws Exception {
Response rb = null;
rb = Response.ok(FCMModels.retrieveFCMModelsListByDatasets(id)).build();
return rb;
}
@GET
@Path("/individuals/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response retrieveFCMModelsByIndividuals(@PathParam("id") int id) throws Exception {
Response rb = null;
rb = Response.ok(FCMModels.retrieveFCMModelsListByIndividuals(id)).build();
return rb;
}
@GET
@Path("/activators")
@Produces(MediaType.APPLICATION_JSON)
public Response retrieveAllActivators() throws Exception {
Response rb = null;
rb = Response.ok(FCMConceptActivators.retrieveFCMActivatorList()).build();
return rb;
}
@POST
@Path("/simulation")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response runFCMSimulation(JSONObject fcmmodel) {
return Response.ok(pcjfcm.runFCMSimulation(fcmmodel)).build();
// return Response.ok(fcmmodel).build();
}
@POST
@Path("/impactanalysis/{id}")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response runImpactAnaylsis(@PathParam("id") int id, JSONObject fcmmodel) {
return Response.ok(pcjfcm.runImpactAnalysis(id, fcmmodel)).build();
// return Response.ok(fcmmodel).build();
}
}
|
package pt.lighthouselabs.obd.reader.io;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
import com.google.inject.Inject;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import pt.lighthouselabs.obd.commands.ObdCommand;
import pt.lighthouselabs.obd.commands.protocol.EchoOffObdCommand;
import pt.lighthouselabs.obd.commands.protocol.LineFeedOffObdCommand;
import pt.lighthouselabs.obd.commands.protocol.ObdResetCommand;
import pt.lighthouselabs.obd.commands.protocol.SelectProtocolObdCommand;
import pt.lighthouselabs.obd.commands.protocol.TimeoutObdCommand;
import pt.lighthouselabs.obd.commands.temperature.AmbientAirTemperatureObdCommand;
import pt.lighthouselabs.obd.enums.ObdProtocols;
import pt.lighthouselabs.obd.reader.R;
import pt.lighthouselabs.obd.reader.activity.ConfigActivity;
import pt.lighthouselabs.obd.reader.activity.MainActivity;
import pt.lighthouselabs.obd.reader.io.ObdCommandJob.ObdCommandJobState;
import roboguice.service.RoboService;
/**
* This service is primarily responsible for establishing and maintaining a
* permanent connection between the device where the application runs and a more
* OBD Bluetooth interface.
* <p/>
* Secondarily, it will serve as a repository of ObdCommandJobs and at the same
* time the application state-machine.
*/
public class ObdGatewayService extends RoboService {
public static final int NOTIFICATION_ID = 1;
private static final String TAG = ObdGatewayService.class.getName();
private static final UUID MY_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private final IBinder binder = new ObdGatewayServiceBinder();
@Inject
SharedPreferences prefs;
@Inject
private Context ctx;
@Inject
private NotificationManager notificationManager;
private boolean isRunning = false;
private boolean isQueueRunning = false;
private BlockingQueue<ObdCommandJob> jobsQueue = new LinkedBlockingQueue<ObdCommandJob>();
private Long queueCounter = 0L;
private BluetoothDevice dev = null;
private BluetoothSocket sock = null;
private BluetoothSocket sockFallback = null;
@Override
public IBinder onBind(Intent intent) {
return binder;
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "Creating service..");
Log.d(TAG, "Service created.");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "Destroying service...");
notificationManager.cancel(NOTIFICATION_ID);
Log.d(TAG, "Service destroyed.");
}
public void startService() {
Log.d(TAG, "Starting service..");
// get the remote Bluetooth device
final String remoteDevice = prefs.getString(ConfigActivity.BLUETOOTH_LIST_KEY, null);
if (remoteDevice == null || "".equals(remoteDevice)) {
Toast.makeText(ctx, "No Bluetooth device selected", Toast.LENGTH_LONG).show();
// log error
Log.e(TAG, "No Bluetooth device has been selected.");
// TODO kill this service gracefully
stopService();
}
final BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
dev = btAdapter.getRemoteDevice(remoteDevice);
/*
* TODO clean
*
* Get more preferences
*/
boolean imperialUnits = prefs.getBoolean(ConfigActivity.IMPERIAL_UNITS_KEY,
false);
ArrayList<ObdCommand> cmds = ConfigActivity.getObdCommands(prefs);
Log.d(TAG, "Stopping Bluetooth discovery.");
btAdapter.cancelDiscovery();
showNotification("Tap to open OBD-Reader", "Starting OBD connection..", R.drawable.ic_launcher, true, true, false);
try {
startObdConnection();
} catch (Exception e) {
Log.e(
TAG,
"There was an error while establishing connection. -> "
+ e.getMessage()
);
// in case of failure, stop this service.
stopService();
}
}
private void startObdConnection() throws IOException {
Log.d(TAG, "Starting OBD connection..");
try {
// Instantiate a BluetoothSocket for the remote device and connect it.
sock = dev.createRfcommSocketToServiceRecord(MY_UUID);
sock.connect();
} catch (Exception e1) {
Log.e(TAG, "There was an error while establishing Bluetooth connection. Falling back..", e1);
Class<?> clazz = sock.getRemoteDevice().getClass();
Class<?>[] paramTypes = new Class<?>[]{Integer.TYPE};
try {
Method m = clazz.getMethod("createRfcommSocket", paramTypes);
Object[] params = new Object[]{Integer.valueOf(1)};
sockFallback = (BluetoothSocket) m.invoke(sock.getRemoteDevice(), params);
sockFallback.connect();
sock = sockFallback;
} catch (Exception e2) {
Log.e(TAG, "Couldn't fallback while establishing Bluetooth connection. Stopping app..", e2);
stopService();
return;
}
}
// Let's configure the connection.
Log.d(TAG, "Queing jobs for connection configuration..");
queueJob(new ObdCommandJob(new ObdResetCommand()));
queueJob(new ObdCommandJob(new EchoOffObdCommand()));
/*
* Will send second-time based on tests.
*
* TODO this can be done w/o having to queue jobs by just issuing
* command.run(), command.getResult() and validate the result.
*/
queueJob(new ObdCommandJob(new EchoOffObdCommand()));
queueJob(new ObdCommandJob(new LineFeedOffObdCommand()));
queueJob(new ObdCommandJob(new TimeoutObdCommand(62)));
// For now set protocol to AUTO
queueJob(new ObdCommandJob(new SelectProtocolObdCommand(ObdProtocols.AUTO)));
// Job for returning dummy data
queueJob(new ObdCommandJob(new AmbientAirTemperatureObdCommand()));
queueCounter = 0L;
Log.d(TAG, "Initialization jobs queued.");
isRunning = true;
}
/**
* Runs the queue until the service is stopped
*/
private void executeQueue() {
Log.d(TAG, "Executing queue..");
isQueueRunning = true;
while (!jobsQueue.isEmpty()) {
ObdCommandJob job = null;
try {
job = jobsQueue.take();
// log job
Log.d(TAG, "Taking job[" + job.getId() + "] from queue..");
if (job.getState().equals(ObdCommandJobState.NEW)) {
Log.d(TAG, "Job state is NEW. Run it..");
job.setState(ObdCommandJobState.RUNNING);
job.getCommand().run(sock.getInputStream(), sock.getOutputStream());
} else
// log not new job
Log.e(TAG,
"Job state was not new, so it shouldn't be in queue. BUG ALERT!");
} catch (Exception e) {
job.setState(ObdCommandJobState.EXECUTION_ERROR);
Log.e(TAG, "Failed to run command. -> " + e.getMessage());
}
if (job != null) {
Log.d(TAG, "Job is finished.");
job.setState(ObdCommandJobState.FINISHED);
((MainActivity) ctx).stateUpdate(job);
}
}
// will run next time a job is queued
isQueueRunning = false;
}
/**
* This method will add a job to the queue while setting its ID to the
* internal queue counter.
*
* @param job the job to queue.
*/
public void queueJob(ObdCommandJob job) {
queueCounter++;
Log.d(TAG, "Adding job[" + queueCounter + "] to queue..");
job.setId(queueCounter);
try {
jobsQueue.put(job);
Log.d(TAG, "Job queued successfully.");
} catch (InterruptedException e) {
job.setState(ObdCommandJobState.QUEUE_ERROR);
Log.e(TAG, "Failed to queue job.");
}
if (!isQueueRunning)
executeQueue();
}
/**
* Stop OBD connection and queue processing.
*/
public void stopService() {
Log.d(TAG, "Stopping service..");
notificationManager.cancel(NOTIFICATION_ID);
jobsQueue.removeAll(jobsQueue); // TODO is this safe?
isRunning = false;
if (sock != null)
// close socket
try {
sock.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
// kill service
stopSelf();
}
/**
* Show a notification while this service is running.
*/
private void showNotification(String contentTitle, String contentText,
int icon, boolean ongoing, boolean notify, boolean vibrate) {
final PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
new Intent(ctx, MainActivity.class), 0);
final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
ctx);
notificationBuilder.setContentTitle(contentTitle)
.setContentText(contentText).setSmallIcon(icon)
.setContentIntent(contentIntent)
.setWhen(System.currentTimeMillis());
// can cancel?
if (ongoing)
notificationBuilder.setOngoing(true);
else
notificationBuilder.setAutoCancel(true);
// vibrate?
if (vibrate)
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
if (notify)
notificationManager.notify(NOTIFICATION_ID,
notificationBuilder.getNotification());
}
public boolean isRunning() {
return isRunning;
}
public class ObdGatewayServiceBinder extends Binder {
public ObdGatewayService getService() {
return ObdGatewayService.this;
}
}
}
|
package org.ojacquemart.eurobets.firebase.rx;
import com.firebase.client.*;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Action0;
import rx.functions.Func1;
import rx.subscriptions.Subscriptions;
import java.util.ArrayList;
import java.util.List;
public class RxFirebase {
/**
* Essentially a struct so that we can pass all children events through as a single object.
*/
public static class FirebaseChildEvent {
public DataSnapshot snapshot;
public EventType eventType;
public String prevName;
public FirebaseChildEvent(DataSnapshot snapshot, EventType eventType, String prevName) {
this.snapshot = snapshot;
this.eventType = eventType;
this.prevName = prevName;
}
}
public static Observable<FirebaseChildEvent> observeChildren(final Query ref) {
return Observable.create(new Observable.OnSubscribe<FirebaseChildEvent>() {
@Override
public void call(final Subscriber<? super FirebaseChildEvent> subscriber) {
final ChildEventListener listener = ref.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String prevName) {
subscriber.onNext(new FirebaseChildEvent(dataSnapshot, EventType.CHILD_ADDED, prevName));
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String prevName) {
subscriber.onNext(new FirebaseChildEvent(dataSnapshot, EventType.CHILD_CHANGED, prevName));
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
subscriber.onNext(new FirebaseChildEvent(dataSnapshot, EventType.CHILD_REMOVED, null));
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String prevName) {
subscriber.onNext(new FirebaseChildEvent(dataSnapshot, EventType.CHILD_MOVED, prevName));
}
@Override
public void onCancelled(FirebaseError error) {
// Turn the FirebaseError into a throwable to conform to the API
subscriber.onError(new FirebaseException(error.getMessage()));
}
});
// When the subscription is cancelled, remove the listener
subscriber.add(Subscriptions.create(new Action0() {
@Override
public void call() {
ref.removeEventListener(listener);
}
}));
}
});
}
private static Func1<FirebaseChildEvent, Boolean> makeEventFilter(final EventType eventType) {
return firebaseChildEvent -> firebaseChildEvent.eventType == eventType;
}
public static Observable<FirebaseChildEvent> observeChildAdded(Query ref) {
return observeChildren(ref).filter(makeEventFilter(EventType.CHILD_ADDED));
}
public static Observable<FirebaseChildEvent> observeChildChanged(Query ref) {
return observeChildren(ref).filter(makeEventFilter(EventType.CHILD_CHANGED));
}
public static Observable<FirebaseChildEvent> observeChildMoved(Query ref) {
return observeChildren(ref).filter(makeEventFilter(EventType.CHILD_MOVED));
}
public static Observable<FirebaseChildEvent> observeChildRemoved(Query ref) {
return observeChildren(ref).filter(makeEventFilter(EventType.CHILD_REMOVED));
}
public static Observable<DataSnapshot> observe(final Query ref) {
return Observable.create(new Observable.OnSubscribe<DataSnapshot>() {
@Override
public void call(final Subscriber<? super DataSnapshot> subscriber) {
final ValueEventListener listener = ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
subscriber.onNext(dataSnapshot);
}
@Override
public void onCancelled(FirebaseError error) {
// Turn the FirebaseError into a throwable to conform to the API
subscriber.onError(new FirebaseException(error.getMessage()));
}
});
// When the subscription is cancelled, remove the listener
subscriber.add(Subscriptions.create(() -> ref.removeEventListener(listener)));
}
});
}
public static <T> Observable<List<T>> observeList(final Query ref, Class<T> clazz) {
return Observable.create(new Observable.OnSubscribe<List<T>>() {
@Override
public void call(final Subscriber<? super List<T>> subscriber) {
final ValueEventListener listener = ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<T> items = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
items.add(ds.getValue(clazz));
}
subscriber.onNext(items);
}
@Override
public void onCancelled(FirebaseError error) {
// Turn the FirebaseError into a throwable to conform to the API
subscriber.onError(new FirebaseException(error.getMessage()));
}
});
// When the subscription is cancelled, remove the listener
subscriber.add(Subscriptions.create(() -> ref.removeEventListener(listener)));
}
});
}
}
|
package org.grouplens.lenskit.eval.maven;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import org.grouplens.lenskit.eval.config.EvalConfig;
import java.io.File;
import java.io.IOException;
import static org.apache.commons.exec.CommandLine.parse;
import static org.apache.commons.io.FileUtils.copyFile;
/**
* Run an R script for statistical analysis.
*
* @author GroupLens Research <ekstrand@cs.umn.edu>
*/
@Mojo(name = "run-r",
requiresDependencyResolution = ResolutionScope.RUNTIME,
threadSafe = true)
public class RScriptMojo extends AbstractMojo {
/**
* The project. Gives access to Maven state.
*/
@Parameter(property = "project",
required = true,
readonly = true)
private MavenProject mavenProject;
/**
* The session. Gives access to Maven session state.
*/
@Parameter(property = "session",
required = true,
readonly = true)
private MavenSession mavenSession;
/**
* Name of R script.
*
*/
@Parameter(property = "lenskit.analyze.script",
defaultValue = "chart.R")
private String analysisScript;
/**
* Name or path to executable Rscript program.
*
*/
@Parameter(property = "rscript.executable",
defaultValue = "Rscript")
private String rscriptExecutable;
/**
* Location of output data from the eval script.
*/
@Parameter(property = EvalConfig.ANALYSIS_DIR_PROPERTY,
defaultValue = ".")
private String analysisDir;
@Override
public void execute() throws MojoExecutionException {
getLog().info("The analysis directory is " + analysisDir);
getLog().info("The analysisScript is " + analysisScript);
getLog().info("The R executable is " + rscriptExecutable);
// Copy the script file into the working directory. We could just execute
// it from its original location, but it will be easier for our users to
// have the copy from the src directory next to its results in target.
File scriptFile = new File(analysisScript);
File scriptCopy = new File(analysisDir, scriptFile.getName());
try {
if (! scriptFile.getCanonicalPath().equals(scriptCopy.getCanonicalPath())) {
copyFile(scriptFile, scriptCopy);
}
} catch (IOException e1) {
throw new MojoExecutionException("Unable to copy scriptFile " + scriptFile.getAbsolutePath()
+ " into working directory " + scriptCopy.getAbsolutePath());
}
// Generate the command line for executing R.
final CommandLine command =
new CommandLine(rscriptExecutable)
.addArgument(scriptCopy.getAbsolutePath(), false);
getLog().debug("command: " + command);
// Execute the command line, in the working directory.
final DefaultExecutor executor = new DefaultExecutor();
executor.setWorkingDirectory(new File(analysisDir));
try {
if (executor.execute(command) != 0) {
throw new MojoExecutionException( "Error code returned for: " + command.toString() );
}
} catch (ExecuteException e) {
throw new MojoExecutionException("Error executing command: " + command.toString());
} catch (IOException e) {
throw new MojoExecutionException("IO Exception while executing command: " + command.toString());
}
}
}
|
package com.yahoo.vespa.flags;
import com.yahoo.component.Vtag;
import com.yahoo.vespa.defaults.Defaults;
import com.yahoo.vespa.flags.custom.PreprovisionCapacity;
import java.util.List;
import java.util.Optional;
import java.util.TreeMap;
import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID;
import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME;
import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE;
import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION;
import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID;
/**
* Definitions of feature flags.
*
* <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag}
* or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p>
*
* <ol>
* <li>The unbound flag</li>
* <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding
* an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li>
* <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should
* declare this in the unbound flag definition in this file (referring to
* {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g.
* {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li>
* </ol>
*
* <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically
* there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p>
*
* @author hakonhall
*/
public class Flags {
private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>();
public static final UnboundIntFlag DROP_CACHES = defineIntFlag("drop-caches", 3,
"The int value to write into /proc/sys/vm/drop_caches for each tick. " +
"1 is page cache, 2 is dentries inodes, 3 is both page cache and dentries inodes, etc.",
"Takes effect on next tick.",
HOSTNAME);
public static final UnboundBooleanFlag ENABLE_CROWDSTRIKE = defineFeatureFlag(
"enable-crowdstrike", true,
"Whether to enable CrowdStrike.", "Takes effect on next host admin tick",
HOSTNAME);
public static final UnboundBooleanFlag ENABLE_NESSUS = defineFeatureFlag(
"enable-nessus", true,
"Whether to enable Nessus.", "Takes effect on next host admin tick",
HOSTNAME);
public static final UnboundListFlag<String> DISABLED_HOST_ADMIN_TASKS = defineListFlag(
"disabled-host-admin-tasks", List.of(), String.class,
"List of host-admin task names (as they appear in the log, e.g. root>main>UpgradeTask) that should be skipped",
"Takes effect on next host admin tick",
HOSTNAME, NODE_TYPE);
public static final UnboundStringFlag DOCKER_VERSION = defineStringFlag(
"docker-version", "1.13.1-91.git07f3374",
"The version of the docker to use of the format VERSION-REL: The YUM package to be installed will be " +
"2:docker-VERSION-REL.el7.centos.x86_64 in AWS (and without '.centos' otherwise). " +
"If docker-version is not of this format, it must be parseable by YumPackageName::fromString.",
"Takes effect on next tick.",
HOSTNAME);
public static final UnboundLongFlag THIN_POOL_GB = defineLongFlag(
"thin-pool-gb", -1,
"The size of the disk reserved for the thin pool with dynamic provisioning in AWS, in base-2 GB. " +
"If <0, the default is used (which may depend on the zone and node type).",
"Takes effect immediately (but used only during provisioning).",
NODE_TYPE);
public static final UnboundDoubleFlag CONTAINER_CPU_CAP = defineDoubleFlag(
"container-cpu-cap", 0,
"Hard limit on how many CPUs a container may use. This value is multiplied by CPU allocated to node, so " +
"to cap CPU at 200%, set this to 2, etc.",
"Takes effect on next node agent tick. Change is orchestrated, but does NOT require container restart",
HOSTNAME, APPLICATION_ID);
public static final UnboundBooleanFlag USE_BUCKET_SPACE_METRIC = defineFeatureFlag(
"use-bucket-space-metric", true,
"Whether to use vds.datastored.bucket_space.buckets_total (true) instead of " +
"vds.datastored.alldisks.buckets (false, legacy).",
"Takes effect on the next deployment of the application",
APPLICATION_ID);
public static final UnboundStringFlag TLS_INSECURE_MIXED_MODE = defineStringFlag(
"tls-insecure-mixed-mode", "tls_client_mixed_server",
"TLS insecure mixed mode. Allowed values: ['plaintext_client_mixed_server', 'tls_client_mixed_server', 'tls_client_tls_server']",
"Takes effect on restart of Docker container",
NODE_TYPE, APPLICATION_ID, HOSTNAME);
public static final UnboundStringFlag TLS_INSECURE_AUTHORIZATION_MODE = defineStringFlag(
"tls-insecure-authorization-mode", "log_only",
"TLS insecure authorization mode. Allowed values: ['disable', 'log_only', 'enforce']",
"Takes effect on restart of Docker container",
NODE_TYPE, APPLICATION_ID, HOSTNAME);
public static final UnboundBooleanFlag USE_ADAPTIVE_DISPATCH = defineFeatureFlag(
"use-adaptive-dispatch", false,
"Should adaptive dispatch be used over round robin",
"Takes effect at redeployment",
APPLICATION_ID);
public static final UnboundIntFlag REBOOT_INTERVAL_IN_DAYS = defineIntFlag(
"reboot-interval-in-days", 30,
"No reboots are scheduled 0x-1x reboot intervals after the previous reboot, while reboot is " +
"scheduled evenly distributed in the 1x-2x range (and naturally guaranteed at the 2x boundary).",
"Takes effect on next run of NodeRebooter");
public static final UnboundBooleanFlag ENABLE_DYNAMIC_PROVISIONING = defineFeatureFlag(
"enable-dynamic-provisioning", false,
"Provision a new docker host when we otherwise can't allocate a docker node",
"Takes effect on next deployment",
APPLICATION_ID);
public static final UnboundListFlag<PreprovisionCapacity> PREPROVISION_CAPACITY = defineListFlag(
"preprovision-capacity", List.of(), PreprovisionCapacity.class,
"List of node resources and their count that should be present in zone to receive new deployments. When a " +
"preprovisioned is taken, new will be provisioned within next iteration of maintainer.",
"Takes effect on next iteration of HostProvisionMaintainer.");
public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag(
"default-term-wise-limit", 1.0,
"Node resource memory in Gb for admin cluster nodes",
"Takes effect at redeployment",
APPLICATION_ID);
public static final UnboundBooleanFlag HOST_HARDENING = defineFeatureFlag(
"host-hardening", false,
"Whether to enable host hardening Linux baseline.",
"Takes effect on next tick or on host-admin restart (may vary where used).",
HOSTNAME);
public static final UnboundStringFlag ZOOKEEPER_SERVER_MAJOR_MINOR_VERSION = defineStringFlag(
"zookeeper-server-version", "3.5",
"The version of ZooKeeper server to use (major.minor, not full version)",
"Takes effect on restart of Docker container",
NODE_TYPE, APPLICATION_ID, HOSTNAME);
public static final UnboundStringFlag TLS_FOR_ZOOKEEPER_QUORUM_COMMUNICATION = defineStringFlag(
"tls-for-zookeeper-quorum-communication", "OFF",
"How to setup TLS for ZooKeeper quorum communication. Valid values are OFF, PORT_UNIFICATION, TLS_WITH_PORT_UNIFICATION, TLS_ONLY",
"Takes effect on restart of config server",
NODE_TYPE, HOSTNAME);
public static final UnboundStringFlag TLS_FOR_ZOOKEEPER_CLIENT_SERVER_COMMUNICATION = defineStringFlag(
"tls-for-zookeeper-client-server-communication", "OFF",
"How to setup TLS for ZooKeeper client/server communication. Valid values are OFF, PORT_UNIFICATION, TLS_WITH_PORT_UNIFICATION, TLS_ONLY",
"Takes effect on restart of config server",
NODE_TYPE, HOSTNAME);
public static final UnboundBooleanFlag USE_TLS_FOR_ZOOKEEPER_CLIENT = defineFeatureFlag(
"use-tls-for-zookeeper-client", false,
"Whether to use TLS for ZooKeeper clients",
"Takes effect on restart of process",
NODE_TYPE, HOSTNAME);
public static final UnboundBooleanFlag ENABLE_DISK_WRITE_TEST = defineFeatureFlag(
"enable-disk-write-test", false,
"Regularly issue a small write to disk and fail the host if it is not successful",
"Takes effect on next node agent tick (but does not clear existing failure reports)",
HOSTNAME);
public static final UnboundBooleanFlag DISABLE_CM3 = defineFeatureFlag(
"disable-cm3", false,
"Whether to disable CM3.", "Takes effect on next host admin tick",
HOSTNAME);
public static final UnboundBooleanFlag USE_4443_UPSTREAM = defineFeatureFlag(
"use-4443-upstream", false,
"Use port 4443 for nginx upstream",
"Takes effect when routing container asks for new config",
APPLICATION_ID);
public static final UnboundBooleanFlag ENABLE_IN_PLACE_RESIZE = defineFeatureFlag(
"enable-in-place-resize", false,
"Whether nodes can be resized in-place when certain conditions are met",
"Takes effect on next deployment",
APPLICATION_ID);
public static final UnboundBooleanFlag USE_CONFIG_SERVER_FOR_TESTER_API_CALLS = defineFeatureFlag(
"use-config-server-for-tester-api-calls", false,
"Whether controller should send requests to tester API through config server (if false) or tester endpoint (if true)",
"Takes effect immediately",
ZONE_ID);
public static final UnboundBooleanFlag INSTALL_L4_ROUTING_SUPPORT = defineFeatureFlag(
"install-l4-routing-support", false,
"Whether routing nodes should install package supporting L4 routing",
"Takes effect immediately",
ZONE_ID, HOSTNAME);
public static final UnboundBooleanFlag GENERATE_L4_ROUTING_CONFIG = defineFeatureFlag(
"generate-l4-routing-config", false,
"Whether routing nodes should generate L4 routing config",
"Takes effect immediately",
ZONE_ID, HOSTNAME);
public static final UnboundBooleanFlag GENERATE_ROUTING_CONFIG_FOR_TESTER_APPLICATIONS = defineFeatureFlag(
"generate-routing-config-for-tester-applications", true,
"Whether config server should generate routing config (lb-services) for tester applications",
"Takes effect on the next deployment of the routing (zone) application",
ZONE_ID);
public static final UnboundBooleanFlag USE_REFRESHED_ENDPOINT_CERTIFICATE = defineFeatureFlag(
"use-refreshed-endpoint-certificate", false,
"Whether an application should start using a newer certificate/key pair if available",
"Takes effect on the next deployment of the application",
APPLICATION_ID);
public static final UnboundBooleanFlag USE_NEW_ATHENZ_FILTER = defineFeatureFlag(
"use-new-athenz-filter", false,
"Use new Athenz filter that supports access-tokens",
"Takes effect at redeployment",
APPLICATION_ID);
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundBooleanFlag::new, flagId, defaultValue, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundStringFlag::new, flagId, defaultValue, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundIntFlag::new, flagId, defaultValue, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundLongFlag::new, flagId, defaultValue, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundDoubleFlag::new, flagId, defaultValue, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass),
flagId, defaultValue, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass,
String description, String modificationEffect, FetchVector.Dimension... dimensions) {
return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec),
flagId, defaultValue, description, modificationEffect, dimensions);
}
@FunctionalInterface
private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> {
U create(FlagId id, T defaultVale, FetchVector defaultFetchVector);
}
/**
* Defines a Flag.
*
* @param factory Factory for creating unbound flag of type U
* @param flagId The globally unique FlagId.
* @param defaultValue The default value if none is present after resolution.
* @param description Description of how the flag is used.
* @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc.
* @param dimensions What dimensions will be set in the {@link FetchVector} when fetching
* the flag value in
* {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}.
* For instance, if APPLICATION is one of the dimensions here, you should make sure
* APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag
* from the FlagSource.
* @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features.
* @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag.
* @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and
* {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment
* is typically implicit.
*/
private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory,
String flagId,
T defaultValue,
String description,
String modificationEffect,
FetchVector.Dimension[] dimensions) {
FlagId id = new FlagId(flagId);
FetchVector vector = new FetchVector()
.with(HOSTNAME, Defaults.getDefaults().vespaHostname())
// Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0
// (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0.
.with(VESPA_VERSION, Vtag.currentVersion.toFullString());
U unboundFlag = factory.create(id, defaultValue, vector);
FlagDefinition definition = new FlagDefinition(unboundFlag, description, modificationEffect, dimensions);
flags.put(id, definition);
return unboundFlag;
}
public static List<FlagDefinition> getAllFlags() {
return List.copyOf(flags.values());
}
public static Optional<FlagDefinition> getFlag(FlagId flagId) {
return Optional.ofNullable(flags.get(flagId));
}
/**
* Allows the statically defined flags to be controlled in a test.
*
* <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block,
* the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from
* before the block is reinserted.
*
* <p>NOT thread-safe. Tests using this cannot run in parallel.
*/
public static Replacer clearFlagsForTesting() {
return new Replacer();
}
public static class Replacer implements AutoCloseable {
private static volatile boolean flagsCleared = false;
private final TreeMap<FlagId, FlagDefinition> savedFlags;
private Replacer() {
verifyAndSetFlagsCleared(true);
this.savedFlags = Flags.flags;
Flags.flags = new TreeMap<>();
}
@Override
public void close() {
verifyAndSetFlagsCleared(false);
Flags.flags = savedFlags;
}
/**
* Used to implement a simple verification that Replacer is not used by multiple threads.
* For instance two different tests running in parallel cannot both use Replacer.
*/
private static void verifyAndSetFlagsCleared(boolean newValue) {
if (flagsCleared == newValue) {
throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?");
}
flagsCleared = newValue;
}
}
}
|
package org.lenskit.knn.user;
import org.lenskit.inject.Shareable;
import org.lenskit.knn.MinNeighbors;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import javax.inject.Inject;
import java.io.Serializable;
import java.util.List;
/**
* Score an item using the weighted average of neighbor ratings.
*/
@Immutable
@Shareable
public class WeightedAverageUserNeighborhoodScorer implements UserNeighborhoodScorer, Serializable {
private static final long serialVersionUID = 1L;
private final int minimumNeighbors;
/**
* Construct a weighted average scorer.
* @param min The minimum neighbors.
*/
@Inject
public WeightedAverageUserNeighborhoodScorer(@MinNeighbors int min) {
minimumNeighbors = min;
}
@Override
@Nullable
public UserUserResult score(long item, List<Neighbor> neighbors) {
if (neighbors.size() < minimumNeighbors) {
return null;
}
double sum = 0;
double weight = 0;
for (Neighbor n: neighbors) {
assert n.vector.containsKey(item);
weight += Math.abs(n.similarity);
sum += n.similarity * n.vector.get(item);
}
if (weight > 0) {
return UserUserResult.newBuilder()
.setItemId(item)
.setScore(sum / weight)
.setTotalWeight(weight)
.setNeighborhoodSize(neighbors.size())
.build();
} else {
return null;
}
}
}
|
package com.yahoo.vespa.flags;
import com.yahoo.component.Vtag;
import com.yahoo.vespa.defaults.Defaults;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import java.util.TreeMap;
import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID;
import static com.yahoo.vespa.flags.FetchVector.Dimension.CONSOLE_USER_EMAIL;
import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME;
import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE;
import static com.yahoo.vespa.flags.FetchVector.Dimension.TENANT_ID;
import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION;
import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID;
/**
* Definitions of feature flags.
*
* <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag}
* or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p>
*
* <ol>
* <li>The unbound flag</li>
* <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding
* an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li>
* <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should
* declare this in the unbound flag definition in this file (referring to
* {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g.
* {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li>
* </ol>
*
* <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically
* there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p>
*
* @author hakonhall
*/
public class Flags {
private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>();
public static final UnboundBooleanFlag MAIN_CHAIN_GRAPH = defineFeatureFlag(
"main-chain-graph", true,
List.of("hakonhall"), "2022-07-06", "2022-10-05",
"Whether to run all tasks in the main task chain up to the one failing to converge (false), or " +
"run all tasks in the main task chain whose dependencies have converged (true). And when suspending, " +
"whether to run the tasks in sequence (false) or in reverse sequence (true).",
"On first tick of the main chain after (re)start of host admin.",
ZONE_ID, NODE_TYPE, HOSTNAME);
public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag(
"default-term-wise-limit", 1.0,
List.of("baldersheim"), "2020-12-02", "2023-01-01",
"Default limit for when to apply termwise query evaluation",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundStringFlag FEED_SEQUENCER_TYPE = defineStringFlag(
"feed-sequencer-type", "THROUGHPUT",
List.of("baldersheim"), "2020-12-02", "2023-01-01",
"Selects type of sequenced executor used for feeding in proton, valid values are LATENCY, ADAPTIVE, THROUGHPUT",
"Takes effect at redeployment (requires restart)",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag KEEP_STORAGE_NODE_UP = defineFeatureFlag(
"keep-storage-node-up", true,
List.of("hakonhall"), "2022-07-07", "2022-09-07",
"Whether to leave the storage node (with wanted state) UP while the node is permanently down.",
"Takes effect immediately for nodes transitioning to permanently down.",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag MAX_UNCOMMITTED_MEMORY = defineIntFlag(
"max-uncommitted-memory", 130000,
List.of("geirst, baldersheim"), "2021-10-21", "2023-01-01",
"Max amount of memory holding updates to an attribute before we do a commit.",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundStringFlag RESPONSE_SEQUENCER_TYPE = defineStringFlag(
"response-sequencer-type", "ADAPTIVE",
List.of("baldersheim"), "2020-12-02", "2023-01-01",
"Selects type of sequenced executor used for mbus responses, valid values are LATENCY, ADAPTIVE, THROUGHPUT",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag RESPONSE_NUM_THREADS = defineIntFlag(
"response-num-threads", 2,
List.of("baldersheim"), "2020-12-02", "2023-01-01",
"Number of threads used for mbus responses, default is 2, negative number = numcores/4",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag SKIP_COMMUNICATIONMANAGER_THREAD = defineFeatureFlag(
"skip-communicationmanager-thread", false,
List.of("baldersheim"), "2020-12-02", "2023-01-01",
"Should we skip the communicationmanager thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag SKIP_MBUS_REQUEST_THREAD = defineFeatureFlag(
"skip-mbus-request-thread", false,
List.of("baldersheim"), "2020-12-02", "2023-01-01",
"Should we skip the mbus request thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag SKIP_MBUS_REPLY_THREAD = defineFeatureFlag(
"skip-mbus-reply-thread", false,
List.of("baldersheim"), "2020-12-02", "2023-01-01",
"Should we skip the mbus reply thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag USE_THREE_PHASE_UPDATES = defineFeatureFlag(
"use-three-phase-updates", false,
List.of("vekterli"), "2020-12-02", "2022-08-15",
"Whether to enable the use of three-phase updates when bucket replicas are out of sync.",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag USE_ASYNC_MESSAGE_HANDLING_ON_SCHEDULE = defineFeatureFlag(
"async-message-handling-on-schedule", false,
List.of("baldersheim"), "2020-12-02", "2023-01-01",
"Optionally deliver async messages in own thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundDoubleFlag FEED_CONCURRENCY = defineDoubleFlag(
"feed-concurrency", 0.5,
List.of("baldersheim"), "2020-12-02", "2023-01-01",
"How much concurrency should be allowed for feed",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundDoubleFlag FEED_NICENESS = defineDoubleFlag(
"feed-niceness", 0.0,
List.of("baldersheim"), "2022-06-24", "2023-01-01",
"How nice feeding shall be",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag MBUS_DISPATCH_ON_ENCODE = defineFeatureFlag(
"mbus-dispatch-on-encode", true,
List.of("baldersheim"), "2022-07-01", "2023-01-01",
"Should we use mbus threadpool on encode",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag MBUS_DISPATCH_ON_DECODE = defineFeatureFlag(
"mbus-dispatch-on-decode", true,
List.of("baldersheim"), "2022-07-01", "2023-01-01",
"Should we use mbus threadpool on decode",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag MBUS_JAVA_NUM_TARGETS = defineIntFlag(
"mbus-java-num-targets", 1,
List.of("baldersheim"), "2022-07-05", "2023-01-01",
"Number of rpc targets per service",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag MBUS_CPP_NUM_TARGETS = defineIntFlag(
"mbus-cpp-num-targets", 1,
List.of("baldersheim"), "2022-07-05", "2023-01-01",
"Number of rpc targets per service",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag RPC_NUM_TARGETS = defineIntFlag(
"rpc-num-targets", 1,
List.of("baldersheim"), "2022-07-05", "2023-01-01",
"Number of rpc targets per content node",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag MBUS_JAVA_EVENTS_BEFORE_WAKEUP = defineIntFlag(
"mbus-java-events-before-wakeup", 1,
List.of("baldersheim"), "2022-07-05", "2023-01-01",
"Number write events before waking up transport thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag MBUS_CPP_EVENTS_BEFORE_WAKEUP = defineIntFlag(
"mbus-cpp-events-before-wakeup", 1,
List.of("baldersheim"), "2022-07-05", "2023-01-01",
"Number write events before waking up transport thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag RPC_EVENTS_BEFORE_WAKEUP = defineIntFlag(
"rpc-events-before-wakeup", 1,
List.of("baldersheim"), "2022-07-05", "2023-01-01",
"Number write events before waking up transport thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag MBUS_NUM_THREADS = defineIntFlag(
"mbus-num-threads", 4,
List.of("baldersheim"), "2022-07-01", "2023-01-01",
"Number of threads used for mbus threadpool",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag MBUS_NUM_NETWORK_THREADS = defineIntFlag(
"mbus-num-network-threads", 1,
List.of("baldersheim"), "2022-07-01", "2023-01-01",
"Number of threads used for mbus network",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag SHARED_STRING_REPO_NO_RECLAIM = defineFeatureFlag(
"shared-string-repo-no-reclaim", false,
List.of("baldersheim"), "2022-06-14", "2023-01-01",
"Controls whether we do track usage and reclaim unused enum values in shared string repo",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag CONTAINER_DUMP_HEAP_ON_SHUTDOWN_TIMEOUT = defineFeatureFlag(
"container-dump-heap-on-shutdown-timeout", false,
List.of("baldersheim"), "2021-09-25", "2023-01-01",
"Will trigger a heap dump during if container shutdown times out",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag LOAD_CODE_AS_HUGEPAGES = defineFeatureFlag(
"load-code-as-hugepages", false,
List.of("baldersheim"), "2022-05-13", "2023-01-01",
"Will try to map the code segment with huge (2M) pages",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundDoubleFlag CONTAINER_SHUTDOWN_TIMEOUT = defineDoubleFlag(
"container-shutdown-timeout", 50.0,
List.of("baldersheim"), "2021-09-25", "2023-05-01",
"Timeout for shutdown of a jdisc container",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundListFlag<String> ALLOWED_ATHENZ_PROXY_IDENTITIES = defineListFlag(
"allowed-athenz-proxy-identities", List.of(), String.class,
List.of("bjorncs", "tokle"), "2021-02-10", "2022-09-01",
"Allowed Athenz proxy identities",
"takes effect at redeployment");
public static final UnboundIntFlag MAX_ACTIVATION_INHIBITED_OUT_OF_SYNC_GROUPS = defineIntFlag(
"max-activation-inhibited-out-of-sync-groups", 0,
List.of("vekterli"), "2021-02-19", "2022-08-15",
"Allows replicas in up to N content groups to not be activated " +
"for query visibility if they are out of sync with a majority of other replicas",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag MAX_CONCURRENT_MERGES_PER_NODE = defineIntFlag(
"max-concurrent-merges-per-node", 16,
List.of("balder", "vekterli"), "2021-06-06", "2022-08-15",
"Specifies max concurrent merges per content node.",
"Takes effect at redeploy",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag MAX_MERGE_QUEUE_SIZE = defineIntFlag(
"max-merge-queue-size", 100,
List.of("balder", "vekterli"), "2021-06-06", "2022-08-15",
"Specifies max size of merge queue.",
"Takes effect at redeploy",
ZONE_ID, APPLICATION_ID);
public static final UnboundDoubleFlag MIN_NODE_RATIO_PER_GROUP = defineDoubleFlag(
"min-node-ratio-per-group", 0.0,
List.of("geirst", "vekterli"), "2021-07-16", "2022-09-01",
"Minimum ratio of nodes that have to be available (i.e. not Down) in any hierarchic content cluster group for the group to be Up",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag METRICSPROXY_NUM_THREADS = defineIntFlag(
"metricsproxy-num-threads", 2,
List.of("balder"), "2021-09-01", "2023-01-01",
"Number of threads for metrics proxy",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag AVAILABLE_PROCESSORS = defineIntFlag(
"available-processors", 2,
List.of("balder"), "2022-01-18", "2023-01-01",
"Number of processors the jvm sees in non-application clusters",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag ENABLED_HORIZON_DASHBOARD = defineFeatureFlag(
"enabled-horizon-dashboard", false,
List.of("olaa"), "2021-09-13", "2022-10-01",
"Enable Horizon dashboard",
"Takes effect immediately",
TENANT_ID, CONSOLE_USER_EMAIL
);
public static final UnboundBooleanFlag UNORDERED_MERGE_CHAINING = defineFeatureFlag(
"unordered-merge-chaining", true,
List.of("vekterli", "geirst"), "2021-11-15", "2022-09-01",
"Enables the use of unordered merge chains for data merge operations",
"Takes effect at redeploy",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag IGNORE_THREAD_STACK_SIZES = defineFeatureFlag(
"ignore-thread-stack-sizes", false,
List.of("arnej"), "2021-11-12", "2022-12-01",
"Whether C++ thread creation should ignore any requested stack size",
"Triggers restart, takes effect immediately",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag USE_V8_GEO_POSITIONS = defineFeatureFlag(
"use-v8-geo-positions", true,
List.of("arnej"), "2021-11-15", "2022-12-31",
"Use Vespa 8 types and formats for geographical positions",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag MAX_COMPACT_BUFFERS = defineIntFlag(
"max-compact-buffers", 1,
List.of("baldersheim", "geirst", "toregge"), "2021-12-15", "2023-01-01",
"Upper limit of buffers to compact in a data store at the same time for each reason (memory usage, address space usage)",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag ENABLE_SERVER_OCSP_STAPLING = defineFeatureFlag(
"enable-server-ocsp-stapling", false,
List.of("bjorncs"), "2021-12-17", "2022-09-01",
"Enable server OCSP stapling for jdisc containers",
"Takes effect on redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag ENABLE_DATA_HIGHWAY_IN_AWS = defineFeatureFlag(
"enable-data-highway-in-aws", false,
List.of("hmusum"), "2022-01-06", "2022-09-01",
"Enable Data Highway in AWS",
"Takes effect on restart of Docker container",
ZONE_ID, APPLICATION_ID);
public static final UnboundStringFlag MERGE_THROTTLING_POLICY = defineStringFlag(
"merge-throttling-policy", "STATIC",
List.of("vekterli"), "2022-01-25", "2022-08-15",
"Sets the policy used for merge throttling on the content nodes. " +
"Valid values: STATIC, DYNAMIC",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundDoubleFlag PERSISTENCE_THROTTLING_WS_DECREMENT_FACTOR = defineDoubleFlag(
"persistence-throttling-ws-decrement-factor", 1.2,
List.of("vekterli"), "2022-01-27", "2022-08-15",
"Sets the dynamic throttle policy window size decrement factor for persistence " +
"async throttling. Only applies if DYNAMIC policy is used.",
"Takes effect on redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundDoubleFlag PERSISTENCE_THROTTLING_WS_BACKOFF = defineDoubleFlag(
"persistence-throttling-ws-backoff", 0.95,
List.of("vekterli"), "2022-01-27", "2022-08-15",
"Sets the dynamic throttle policy window size backoff for persistence " +
"async throttling. Only applies if DYNAMIC policy is used. Valid range [0, 1]",
"Takes effect on redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag PERSISTENCE_THROTTLING_WINDOW_SIZE = defineIntFlag(
"persistence-throttling-window-size", -1,
List.of("vekterli"), "2022-02-23", "2022-09-01",
"If greater than zero, sets both min and max window size to the given number, effectively " +
"turning dynamic throttling into a static throttling policy. " +
"Only applies if DYNAMIC policy is used.",
"Takes effect on redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundDoubleFlag PERSISTENCE_THROTTLING_WS_RESIZE_RATE = defineDoubleFlag(
"persistence-throttling-ws-resize-rate", 3.0,
List.of("vekterli"), "2022-02-23", "2022-09-01",
"Sets the dynamic throttle policy resize rate. Only applies if DYNAMIC policy is used.",
"Takes effect on redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag PERSISTENCE_THROTTLING_OF_MERGE_FEED_OPS = defineFeatureFlag(
"persistence-throttling-of-merge-feed-ops", true,
List.of("vekterli"), "2022-02-24", "2022-09-01",
"If true, each put/remove contained within a merge is individually throttled as if it " +
"were a put/remove from a client. If false, merges are throttled at a persistence thread " +
"level, i.e. per ApplyBucketDiff message, regardless of how many document operations " +
"are contained within. Only applies if DYNAMIC policy is used.",
"Takes effect on redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag USE_QRSERVER_SERVICE_NAME = defineFeatureFlag(
"use-qrserver-service-name", false,
List.of("arnej"), "2022-01-18", "2022-12-31",
"Use backwards-compatible 'qrserver' service name for containers with only 'search' API",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag AVOID_RENAMING_SUMMARY_FEATURES = defineFeatureFlag(
"avoid-renaming-summary-features", true,
List.of("arnej"), "2022-01-15", "2023-12-31",
"Tell backend about the original name of summary-features that were wrapped in a rankingExpression feature",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag ENABLE_BIT_VECTORS = defineFeatureFlag(
"enable-bit-vectors", false,
List.of("baldersheim"), "2022-05-03", "2022-12-31",
"Enables bit vector by default for fast-search attributes",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundStringFlag APPLICATION_FILES_WITH_UNKNOWN_EXTENSION = defineStringFlag(
"fail-deployment-for-files-with-unknown-extension", "FAIL",
List.of("hmusum"), "2022-04-27", "2022-09-01",
"Whether to log, fail or do nothing for deployments when app has a file with unknown extension (valid values LOG, FAIL, NOOP)",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag NOTIFICATION_DISPATCH_FLAG = defineFeatureFlag(
"dispatch-notifications", false,
List.of("enygaard"), "2022-05-02", "2022-09-30",
"Whether we should send notification for a given tenant",
"Takes effect immediately",
TENANT_ID);
public static final UnboundBooleanFlag ENABLE_PROXY_PROTOCOL_MIXED_MODE = defineFeatureFlag(
"enable-proxy-protocol-mixed-mode", true,
List.of("tokle"), "2022-05-09", "2022-09-01",
"Enable or disable proxy protocol mixed mode",
"Takes effect on redeployment",
APPLICATION_ID);
public static final UnboundListFlag<String> FILE_DISTRIBUTION_ACCEPTED_COMPRESSION_TYPES = defineListFlag(
"file-distribution-accepted-compression-types", List.of("gzip", "lz4"), String.class,
List.of("hmusum"), "2022-07-05", "2022-09-05",
"´List of accepted compression types used when asking for a file reference. Valid values: gzip, lz4",
"Takes effect on restart of service",
APPLICATION_ID);
public static final UnboundListFlag<String> FILE_DISTRIBUTION_COMPRESSION_TYPES_TO_SERVE = defineListFlag(
"file-distribution-compression-types-to-use", List.of("lz4", "gzip"), String.class,
List.of("hmusum"), "2022-07-05", "2022-09-05",
"List of compression types to use (in preferred order), matched with accepted compression types when serving file references. Valid values: gzip, lz4",
"Takes effect on restart of service",
APPLICATION_ID);
public static final UnboundBooleanFlag USE_YUM_PROXY_V2 = defineFeatureFlag(
"use-yumproxy-v2", false,
List.of("tokle"), "2022-05-05", "2022-09-01",
"Use yumproxy-v2",
"Takes effect on host admin restart",
HOSTNAME);
public static final UnboundStringFlag LOG_FILE_COMPRESSION_ALGORITHM = defineStringFlag(
"log-file-compression-algorithm", "",
List.of("arnej"), "2022-06-14", "2024-12-31",
"Which algorithm to use for compressing log files. Valid values: empty string (default), gzip, zstd",
"Takes effect immediately",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag SEPARATE_METRIC_CHECK_CONFIG = defineFeatureFlag(
"separate-metric-check-config", false,
List.of("olaa"), "2022-07-04", "2022-09-01",
"Determines whether one metrics config check should be written per Vespa node",
"Takes effect on next tick",
HOSTNAME);
public static final UnboundStringFlag TLS_CAPABILITIES_ENFORCEMENT_MODE = defineStringFlag(
"tls-capabilities-enforcement-mode", "disable",
List.of("bjorncs", "vekterli"), "2022-07-21", "2024-01-01",
"Configure Vespa TLS capability enforcement mode",
"Takes effect on restart of Docker container",
APPLICATION_ID,HOSTNAME,NODE_TYPE,TENANT_ID,VESPA_VERSION
);
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundBooleanFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundStringFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundIntFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundLongFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundDoubleFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass),
flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass,
List<String> owners, String createdAt, String expiresAt,
String description, String modificationEffect, FetchVector.Dimension... dimensions) {
return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec),
flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
@FunctionalInterface
private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> {
U create(FlagId id, T defaultVale, FetchVector defaultFetchVector);
}
/**
* Defines a Flag.
*
* @param factory Factory for creating unbound flag of type U
* @param flagId The globally unique FlagId.
* @param defaultValue The default value if none is present after resolution.
* @param description Description of how the flag is used.
* @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc.
* @param dimensions What dimensions will be set in the {@link FetchVector} when fetching
* the flag value in
* {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}.
* For instance, if APPLICATION is one of the dimensions here, you should make sure
* APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag
* from the FlagSource.
* @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features.
* @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag.
* @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and
* {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment
* is typically implicit.
*/
private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory,
String flagId,
T defaultValue,
List<String> owners,
String createdAt,
String expiresAt,
String description,
String modificationEffect,
FetchVector.Dimension[] dimensions) {
FlagId id = new FlagId(flagId);
FetchVector vector = new FetchVector()
.with(HOSTNAME, Defaults.getDefaults().vespaHostname())
// Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0
// (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0.
.with(VESPA_VERSION, Vtag.currentVersion.toFullString());
U unboundFlag = factory.create(id, defaultValue, vector);
FlagDefinition definition = new FlagDefinition(
unboundFlag, owners, parseDate(createdAt), parseDate(expiresAt), description, modificationEffect, dimensions);
flags.put(id, definition);
return unboundFlag;
}
private static Instant parseDate(String rawDate) {
return DateTimeFormatter.ISO_DATE.parse(rawDate, LocalDate::from).atStartOfDay().toInstant(ZoneOffset.UTC);
}
public static List<FlagDefinition> getAllFlags() {
return List.copyOf(flags.values());
}
public static Optional<FlagDefinition> getFlag(FlagId flagId) {
return Optional.ofNullable(flags.get(flagId));
}
/**
* Allows the statically defined flags to be controlled in a test.
*
* <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block,
* the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from
* before the block is reinserted.
*
* <p>NOT thread-safe. Tests using this cannot run in parallel.
*/
public static Replacer clearFlagsForTesting(FlagId... flagsToKeep) {
return new Replacer(flagsToKeep);
}
public static class Replacer implements AutoCloseable {
private static volatile boolean flagsCleared = false;
private final TreeMap<FlagId, FlagDefinition> savedFlags;
private Replacer(FlagId... flagsToKeep) {
verifyAndSetFlagsCleared(true);
this.savedFlags = Flags.flags;
Flags.flags = new TreeMap<>();
List.of(flagsToKeep).forEach(id -> Flags.flags.put(id, savedFlags.get(id)));
}
@Override
public void close() {
verifyAndSetFlagsCleared(false);
Flags.flags = savedFlags;
}
/**
* Used to implement a simple verification that Replacer is not used by multiple threads.
* For instance two different tests running in parallel cannot both use Replacer.
*/
private static void verifyAndSetFlagsCleared(boolean newValue) {
if (flagsCleared == newValue) {
throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?");
}
flagsCleared = newValue;
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.nativelibs4java.opencl.util;
import com.nativelibs4java.opencl.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.Buffer;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.nativelibs4java.util.IOUtils;
import com.nativelibs4java.util.NIOUtils;
import com.ochafik.util.listenable.Pair;
/**
*
* @author Olivier
*/
public class ReductionUtils {
static String source;
static final String sourcePath = ReductionUtils.class.getPackage().getName().replace('.', '/') + "/" + "Reduction.c";
static synchronized String getSource() throws IOException {
InputStream in = ReductionUtils.class.getClassLoader().getResourceAsStream(sourcePath);
if (in == null)
throw new FileNotFoundException(sourcePath);
return source = IOUtils.readText(in);
}
public enum Operation {
Add,
Multiply,
Min,
Max;
}
public static Pair<String, Map<String, Object>> getReductionCodeAndMacros(Operation op, OpenCLType valueType, int channels) throws IOException {
Map<String, Object> macros = new LinkedHashMap<String, Object>();
String cType = valueType.toCType() + (channels == 1 ? "" : channels);
macros.put("OPERAND_TYPE", cType);
String operation, seed;
switch (op) {
case Add:
operation = "_add_";
seed = "0";
break;
case Multiply:
operation = "_mul_";
seed = "1";
break;
case Min:
operation = "_min_";
switch (valueType) {
case Int:
seed = Integer.MAX_VALUE + "";
break;
case Long:
seed = Long.MAX_VALUE + "LL";
break;
case Short:
seed = Short.MAX_VALUE + "";
break;
case Float:
seed = "MAXFLOAT";
break;
case Double:
seed = "MAXDOUBLE";
break;
default:
throw new IllegalArgumentException("Unhandled seed type: " + valueType);
}
break;
case Max:
operation = "_max_";
switch (valueType) {
case Int:
seed = Integer.MIN_VALUE + "";
break;
case Long:
seed = Long.MIN_VALUE + "LL";
break;
case Short:
seed = Short.MIN_VALUE + "";
break;
case Float:
seed = "-MAXFLOAT";
break;
case Double:
seed = "-MAXDOUBLE";
break;
default:
throw new IllegalArgumentException("Unhandled seed type: " + valueType);
}
break;
default:
throw new IllegalArgumentException("Unhandled operation: " + op);
}
macros.put("OPERATION", operation);
macros.put("SEED", seed);
return new Pair<String, Map<String, Object>>(getSource(), macros);
}
public interface Reductor<B extends Buffer> {
public CLEvent reduce(CLQueue queue, CLBuffer<B> input, long inputLength, B output, int maxReductionSize, CLEvent... eventsToWaitFor);
public B reduce(CLQueue queue, CLBuffer<B> input, long inputLength, int maxReductionSize, CLEvent... eventsToWaitFor);
public CLEvent reduce(CLQueue queue, CLBuffer<B> input, long inputLength, CLBuffer<B> output, int maxReductionSize, CLEvent... eventsToWaitFor);
}
/*public interface WeightedReductor<B extends Buffer, W extends Buffer> {
public CLEvent reduce(CLQueue queue, CLBuffer<B> input, CLBuffer<W> weights, long inputLength, B output, int maxReductionSize, CLEvent... eventsToWaitFor);
public CLEvent reduce(CLQueue queue, CLBuffer<B> input, CLBuffer<W> weights, long inputLength, CLBuffer<B> output, int maxReductionSize, CLEvent... eventsToWaitFor);
}*/
static int getNextPowerOfTwo(int i) {
int shifted = 0;
boolean lost = false;
for (;;) {
int next = i >> 1;
if (next == 0) {
if (lost)
return 1 << (shifted + 1);
else
return 1 << shifted;
}
lost = lost || (next << 1 != i);
shifted++;
i = next;
}
}
public static <B extends Buffer> Reductor<B> createReductor(final CLContext context, Operation op, OpenCLType valueType, final int valueChannels) throws CLBuildException {
try {
Pair<String, Map<String, Object>> codeAndMacros = getReductionCodeAndMacros(op, valueType, valueChannels);
CLProgram program = context.createProgram(codeAndMacros.getFirst());
program.defineMacros(codeAndMacros.getValue());
program.build();
CLKernel[] kernels = program.createKernels();
if (kernels.length != 1)
throw new RuntimeException("Expected 1 kernel, found : " + kernels.length);
final CLKernel kernel = kernels[0];
return new Reductor<B>() {
@SuppressWarnings("unchecked")
@Override
public CLEvent reduce(CLQueue queue, CLBuffer<B> input, long inputLength, B output, int maxReductionSize, CLEvent... eventsToWaitFor) {
Pair<CLBuffer<B>, CLEvent[]> outAndEvts = reduceHelper(queue, input, (int)inputLength, (Class<B>)output.getClass(), maxReductionSize, eventsToWaitFor);
return outAndEvts.getFirst().read(queue, 0, valueChannels, output, false, outAndEvts.getSecond());
}
@Override
public B reduce(CLQueue queue, CLBuffer<B> input, long inputLength, int maxReductionSize, CLEvent... eventsToWaitFor) {
B output = NIOUtils.directBuffer((int)inputLength, context.getByteOrder(), input.typedBufferClass());
CLEvent evt = reduce(queue, input, inputLength, output, maxReductionSize, eventsToWaitFor);
//queue.finish();
//TODO
evt.waitFor();
return output;
}
@Override
public CLEvent reduce(CLQueue queue, CLBuffer<B> input, long inputLength, CLBuffer<B> output, int maxReductionSize, CLEvent... eventsToWaitFor) {
Pair<CLBuffer<B>, CLEvent[]> outAndEvts = reduceHelper(queue, input, (int)inputLength, output.typedBufferClass(), maxReductionSize, eventsToWaitFor);
return outAndEvts.getFirst().copyTo(queue, 0, valueChannels, output, 0, outAndEvts.getSecond());
}
@SuppressWarnings("unchecked")
public Pair<CLBuffer<B>, CLEvent[]> reduceHelper(CLQueue queue, CLBuffer<B> input, int inputLength, Class<B> outputClass, int maxReductionSize, CLEvent... eventsToWaitFor) {
if (inputLength == 1) {
return new Pair<CLBuffer<B>, CLEvent[]>(input, new CLEvent[0]);
}
CLBuffer<?>[] tempBuffers = new CLBuffer<?>[2];
int depth = 0;
CLBuffer<B> currentOutput = null;
CLEvent[] eventsArr = new CLEvent[1];
int[] blockCountArr = new int[1];
int maxWIS = (int)queue.getDevice().getMaxWorkItemSizes()[0];
while (inputLength > 1) {
int blocksInCurrentDepth = inputLength / maxReductionSize;
if (inputLength > blocksInCurrentDepth * maxReductionSize)
blocksInCurrentDepth++;
int iOutput = depth & 1;
CLBuffer<? extends Buffer> currentInput = depth == 0 ? input : tempBuffers[iOutput ^ 1];
currentOutput = (CLBuffer<B>)tempBuffers[iOutput];
if (currentOutput == null)
currentOutput = (CLBuffer<B>)(tempBuffers[iOutput] = context.createBuffer(CLMem.Usage.InputOutput, blocksInCurrentDepth * valueChannels, outputClass));
synchronized (kernel) {
kernel.setArgs(currentInput, (long)blocksInCurrentDepth, (long)inputLength, (long)maxReductionSize, currentOutput);
int workgroupSize = blocksInCurrentDepth;
if (workgroupSize == 1)
workgroupSize = 2;
blockCountArr[0] = workgroupSize;
eventsArr[0] = kernel.enqueueNDRange(queue, blockCountArr, null, eventsToWaitFor);
}
eventsToWaitFor = eventsArr;
inputLength = blocksInCurrentDepth;
depth++;
}
return new Pair<CLBuffer<B>, CLEvent[]>(currentOutput, eventsToWaitFor);
}
};
} catch (IOException ex) {
Logger.getLogger(ReductionUtils.class.getName()).log(Level.SEVERE, null, ex);
throw new RuntimeException("Failed to create a " + op + " reductor for type " + valueType + valueChannels, ex);
}
}
}
|
package com.timehop.stickyheadersrecyclerview;
import android.graphics.Rect;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.timehop.stickyheadersrecyclerview.caching.HeaderProvider;
import com.timehop.stickyheadersrecyclerview.calculation.DimensionCalculator;
import com.timehop.stickyheadersrecyclerview.util.OrientationProvider;
/**
* Calculates the position and location of header views
*/
public class HeaderPositionCalculator {
private final StickyRecyclerHeadersAdapter mAdapter;
private final OrientationProvider mOrientationProvider;
private final HeaderProvider mHeaderProvider;
private final DimensionCalculator mDimensionCalculator;
/**
* The following fields are used as buffers for internal calculations. Their sole purpose is to avoid
* allocating new Rect every time we need one.
*/
private final Rect mTempRect1 = new Rect();
private final Rect mTempRect2 = new Rect();
public HeaderPositionCalculator(StickyRecyclerHeadersAdapter adapter, HeaderProvider headerProvider,
OrientationProvider orientationProvider, DimensionCalculator dimensionCalculator) {
mAdapter = adapter;
mHeaderProvider = headerProvider;
mOrientationProvider = orientationProvider;
mDimensionCalculator = dimensionCalculator;
}
/**
* Determines if a view should have a sticky header.
* The view has a sticky header if:
* 1. It is the first element in the recycler view
* 2. It has a valid ID associated to its position
*
* @param itemView given by the RecyclerView
* @param orientation of the Recyclerview
* @param position of the list item in question
* @return True if the view should have a sticky header
*/
public boolean hasStickyHeader(View itemView, int orientation, int position) {
int offset, margin;
mDimensionCalculator.initMargins(mTempRect1, itemView);
if (orientation == LinearLayout.VERTICAL) {
offset = itemView.getTop();
margin = mTempRect1.top;
} else {
offset = itemView.getLeft();
margin = mTempRect1.left;
}
return offset <= margin && mAdapter.getHeaderId(position) >= 0;
}
/**
* Determines if an item in the list should have a header that is different than the item in the
* list that immediately precedes it. Items with no headers will always return false.
*
* @param position of the list item in questions
* @param isReverseLayout TRUE if layout manager has flag isReverseLayout
* @return true if this item has a different header than the previous item in the list
*/
public boolean hasNewHeader(int position, boolean isReverseLayout) {
if (indexOutOfBounds(position)) {
return false;
}
long headerId = mAdapter.getHeaderId(position);
if (headerId < 0) {
return false;
}
long nextItemHeaderId = -1;
int nextItemPosition = position + (isReverseLayout? 1: -1);
if (!indexOutOfBounds(nextItemPosition)){
nextItemHeaderId = mAdapter.getHeaderId(nextItemPosition);
}
int firstItemPosition = isReverseLayout? mAdapter.getItemCount()-1 : 0;
return position == firstItemPosition || headerId != nextItemHeaderId;
}
private boolean indexOutOfBounds(int position) {
return position < 0 || position >= mAdapter.getItemCount();
}
public void initHeaderBounds(Rect bounds, RecyclerView recyclerView, View header, View firstView, boolean firstHeader) {
int orientation = mOrientationProvider.getOrientation(recyclerView);
initDefaultHeaderOffset(bounds, recyclerView, header, firstView, orientation);
if (firstHeader && isStickyHeaderBeingPushedOffscreen(recyclerView, header)) {
View viewAfterNextHeader = getFirstViewUnobscuredByHeader(recyclerView, header);
int firstViewUnderHeaderPosition = recyclerView.getChildAdapterPosition(viewAfterNextHeader);
View secondHeader = mHeaderProvider.getHeader(recyclerView, firstViewUnderHeaderPosition);
translateHeaderWithNextHeader(recyclerView, mOrientationProvider.getOrientation(recyclerView), bounds,
header, viewAfterNextHeader, secondHeader);
}
}
private void initDefaultHeaderOffset(Rect headerMargins, RecyclerView recyclerView, View header, View firstView, int orientation) {
int translationX, translationY;
mDimensionCalculator.initMargins(mTempRect1, header);
ViewGroup.LayoutParams layoutParams = firstView.getLayoutParams();
int leftMargin = 0;
int topMargin = 0;
if (layoutParams instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) layoutParams;
leftMargin = marginLayoutParams.leftMargin;
topMargin = marginLayoutParams.topMargin;
}
if (orientation == LinearLayoutManager.VERTICAL) {
translationX = firstView.getLeft() - leftMargin + mTempRect1.left;
translationY = Math.max(
firstView.getTop() - topMargin - header.getHeight() - mTempRect1.bottom,
getListTop(recyclerView) + mTempRect1.top);
} else {
translationY = firstView.getTop() - topMargin + mTempRect1.top;
translationX = Math.max(
firstView.getLeft() - leftMargin - header.getWidth() - mTempRect1.right,
getListLeft(recyclerView) + mTempRect1.left);
}
headerMargins.set(translationX, translationY, translationX + header.getWidth(),
translationY + header.getHeight());
}
private boolean isStickyHeaderBeingPushedOffscreen(RecyclerView recyclerView, View stickyHeader) {
View viewAfterHeader = getFirstViewUnobscuredByHeader(recyclerView, stickyHeader);
int firstViewUnderHeaderPosition = recyclerView.getChildAdapterPosition(viewAfterHeader);
if (firstViewUnderHeaderPosition == RecyclerView.NO_POSITION) {
return false;
}
boolean isReverseLayout = mOrientationProvider.isReverseLayout(recyclerView);
if (firstViewUnderHeaderPosition > 0 && hasNewHeader(firstViewUnderHeaderPosition, isReverseLayout)) {
View nextHeader = mHeaderProvider.getHeader(recyclerView, firstViewUnderHeaderPosition);
mDimensionCalculator.initMargins(mTempRect1, nextHeader);
mDimensionCalculator.initMargins(mTempRect2, stickyHeader);
if (mOrientationProvider.getOrientation(recyclerView) == LinearLayoutManager.VERTICAL) {
int topOfNextHeader = viewAfterHeader.getTop() - mTempRect1.bottom - nextHeader.getHeight() - mTempRect1.top;
int bottomOfThisHeader = recyclerView.getPaddingTop() + stickyHeader.getBottom() + mTempRect2.top + mTempRect2.bottom;
if (topOfNextHeader < bottomOfThisHeader) {
return true;
}
} else {
int leftOfNextHeader = viewAfterHeader.getLeft() - mTempRect1.right - nextHeader.getWidth() - mTempRect1.left;
int rightOfThisHeader = recyclerView.getPaddingLeft() + stickyHeader.getRight() + mTempRect2.left + mTempRect2.right;
if (leftOfNextHeader < rightOfThisHeader) {
return true;
}
}
}
return false;
}
private void translateHeaderWithNextHeader(RecyclerView recyclerView, int orientation, Rect translation,
View currentHeader, View viewAfterNextHeader, View nextHeader) {
mDimensionCalculator.initMargins(mTempRect1, nextHeader);
mDimensionCalculator.initMargins(mTempRect2, currentHeader);
if (orientation == LinearLayoutManager.VERTICAL) {
int topOfStickyHeader = getListTop(recyclerView) + mTempRect2.top + mTempRect2.bottom;
int shiftFromNextHeader = viewAfterNextHeader.getTop() - nextHeader.getHeight() - mTempRect1.bottom - mTempRect1.top - currentHeader.getHeight() - topOfStickyHeader;
if (shiftFromNextHeader < topOfStickyHeader) {
translation.top += shiftFromNextHeader;
}
} else {
int leftOfStickyHeader = getListLeft(recyclerView) + mTempRect2.left + mTempRect2.right;
int shiftFromNextHeader = viewAfterNextHeader.getLeft() - nextHeader.getWidth() - mTempRect1.right - mTempRect1.left - currentHeader.getWidth() - leftOfStickyHeader;
if (shiftFromNextHeader < leftOfStickyHeader) {
translation.left += shiftFromNextHeader;
}
}
}
/**
* Returns the first item currently in the RecyclerView that is not obscured by a header.
*
* @param parent Recyclerview containing all the list items
* @return first item that is fully beneath a header
*/
private View getFirstViewUnobscuredByHeader(RecyclerView parent, View firstHeader) {
boolean isReverseLayout = mOrientationProvider.isReverseLayout(parent);
int step = isReverseLayout? -1 : 1;
int from = isReverseLayout? parent.getChildCount()-1 : 0;
for (int i = from; i >= 0 && i <= parent.getChildCount() - 1; i += step) {
View child = parent.getChildAt(i);
if (!itemIsObscuredByHeader(parent, child, firstHeader, mOrientationProvider.getOrientation(parent))) {
return child;
}
}
return null;
}
/**
* Determines if an item is obscured by a header
*
*
* @param parent
* @param item to determine if obscured by header
* @param header that might be obscuring the item
* @param orientation of the {@link RecyclerView}
* @return true if the item view is obscured by the header view
*/
private boolean itemIsObscuredByHeader(RecyclerView parent, View item, View header, int orientation) {
RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) item.getLayoutParams();
mDimensionCalculator.initMargins(mTempRect1, header);
int adapterPosition = parent.getChildAdapterPosition(item);
if (adapterPosition == RecyclerView.NO_POSITION || mHeaderProvider.getHeader(parent, adapterPosition) != header) {
// Handles an edge case where a trailing header is smaller than the current sticky header.
return false;
}
if (orientation == LinearLayoutManager.VERTICAL) {
int itemTop = item.getTop() - layoutParams.topMargin;
int headerBottom = getListTop(parent) + header.getBottom() + mTempRect1.bottom + mTempRect1.top;
if (itemTop > headerBottom) {
return false;
}
} else {
int itemLeft = item.getLeft() - layoutParams.leftMargin;
int headerRight = getListLeft(parent) + header.getRight() + mTempRect1.right + mTempRect1.left;
if (itemLeft > headerRight) {
return false;
}
}
return true;
}
private int getListTop(RecyclerView view) {
if (view.getLayoutManager().getClipToPadding()) {
return view.getPaddingTop();
} else {
return 0;
}
}
private int getListLeft(RecyclerView view) {
if (view.getLayoutManager().getClipToPadding()) {
return view.getPaddingLeft();
} else {
return 0;
}
}
}
|
package com.timehop.stickyheadersrecyclerview;
import android.graphics.Rect;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.timehop.stickyheadersrecyclerview.caching.HeaderProvider;
import com.timehop.stickyheadersrecyclerview.calculation.DimensionCalculator;
import com.timehop.stickyheadersrecyclerview.util.OrientationProvider;
/**
* Calculates the position and location of header views
*/
public class HeaderPositionCalculator {
private final StickyRecyclerHeadersAdapter mAdapter;
private final OrientationProvider mOrientationProvider;
private final HeaderProvider mHeaderProvider;
private final DimensionCalculator mDimensionCalculator;
/**
* The following fields are used as buffers for internal calculations. Their sole purpose is to avoid
* allocating new Rect every time we need one.
*/
private final Rect mTempRect1 = new Rect();
private final Rect mTempRect2 = new Rect();
public HeaderPositionCalculator(StickyRecyclerHeadersAdapter adapter, HeaderProvider headerProvider,
OrientationProvider orientationProvider, DimensionCalculator dimensionCalculator) {
mAdapter = adapter;
mHeaderProvider = headerProvider;
mOrientationProvider = orientationProvider;
mDimensionCalculator = dimensionCalculator;
}
/**
* Determines if a view should have a sticky header.
* The view has a sticky header if:
* 1. It is the first element in the recycler view
* 2. It has a valid ID associated to its position
*
* @param itemView given by the RecyclerView
* @param orientation of the Recyclerview
* @param position of the list item in question
* @return True if the view should have a sticky header
*/
public boolean hasStickyHeader(View itemView, int orientation, int position) {
int offset, margin;
mDimensionCalculator.initMargins(mTempRect1, itemView);
if (orientation == LinearLayout.VERTICAL) {
offset = itemView.getTop();
margin = mTempRect1.top;
} else {
offset = itemView.getLeft();
margin = mTempRect1.left;
}
return offset <= margin && mAdapter.getHeaderId(position) >= 0;
}
/**
* Determines if an item in the list should have a header that is different than the item in the
* list that immediately precedes it. Items with no headers will always return false.
*
* @param position of the list item in questions
* @param isReverseLayout TRUE if layout manager has flag isReverseLayout
* @return true if this item has a different header than the previous item in the list
*/
public boolean hasNewHeader(int position, boolean isReverseLayout) {
if (indexOutOfBounds(position)) {
return false;
}
long headerId = mAdapter.getHeaderId(position);
if (headerId < 0) {
return false;
}
long nextItemHeaderId = -1;
int nextItemPosition = position + (isReverseLayout? 1: -1);
if (!indexOutOfBounds(nextItemPosition)){
nextItemHeaderId = mAdapter.getHeaderId(nextItemPosition);
}
int firstItemPosition = isReverseLayout? mAdapter.getItemCount()-1 : 0;
return position == firstItemPosition || headerId != nextItemHeaderId;
}
private boolean indexOutOfBounds(int position) {
return position < 0 || position >= mAdapter.getItemCount();
}
public void initHeaderBounds(Rect bounds, RecyclerView recyclerView, View header, View firstView, boolean firstHeader) {
int orientation = mOrientationProvider.getOrientation(recyclerView);
initDefaultHeaderOffset(bounds, recyclerView, header, firstView, orientation);
if (firstHeader && isStickyHeaderBeingPushedOffscreen(recyclerView, header)) {
View viewAfterNextHeader = getFirstViewUnobscuredByHeader(recyclerView, header);
int firstViewUnderHeaderPosition = recyclerView.getChildAdapterPosition(viewAfterNextHeader);
View secondHeader = mHeaderProvider.getHeader(recyclerView, firstViewUnderHeaderPosition);
translateHeaderWithNextHeader(recyclerView, mOrientationProvider.getOrientation(recyclerView), bounds,
header, viewAfterNextHeader, secondHeader);
}
}
private void initDefaultHeaderOffset(Rect headerMargins, RecyclerView recyclerView, View header, View firstView, int orientation) {
int translationX, translationY;
mDimensionCalculator.initMargins(mTempRect1, header);
ViewGroup.LayoutParams layoutParams = firstView.getLayoutParams();
int leftMargin = 0;
int topMargin = 0;
if (layoutParams instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) layoutParams;
leftMargin = marginLayoutParams.leftMargin;
topMargin = marginLayoutParams.topMargin;
}
if (orientation == LinearLayoutManager.VERTICAL) {
translationX = firstView.getLeft() - leftMargin + mTempRect1.left;
translationY = Math.max(
firstView.getTop() - topMargin - header.getHeight() - mTempRect1.bottom,
getListTop(recyclerView) + mTempRect1.top);
} else {
translationY = firstView.getTop() - topMargin + mTempRect1.top;
translationX = Math.max(
firstView.getLeft() - leftMargin - header.getWidth() - mTempRect1.right,
getListLeft(recyclerView) + mTempRect1.left);
}
headerMargins.set(translationX, translationY, translationX + header.getWidth(),
translationY + header.getHeight());
}
private boolean isStickyHeaderBeingPushedOffscreen(RecyclerView recyclerView, View stickyHeader) {
View viewAfterHeader = getFirstViewUnobscuredByHeader(recyclerView, stickyHeader);
int firstViewUnderHeaderPosition = recyclerView.getChildAdapterPosition(viewAfterHeader);
if (firstViewUnderHeaderPosition == RecyclerView.NO_POSITION) {
return false;
}
boolean isReverseLayout = mOrientationProvider.isReverseLayout(recyclerView);
if (firstViewUnderHeaderPosition > 0 && hasNewHeader(firstViewUnderHeaderPosition, isReverseLayout)) {
View nextHeader = mHeaderProvider.getHeader(recyclerView, firstViewUnderHeaderPosition);
mDimensionCalculator.initMargins(mTempRect1, nextHeader);
mDimensionCalculator.initMargins(mTempRect2, stickyHeader);
if (mOrientationProvider.getOrientation(recyclerView) == LinearLayoutManager.VERTICAL) {
int topOfNextHeader = viewAfterHeader.getTop() - mTempRect1.bottom - nextHeader.getHeight() - mTempRect1.top;
int bottomOfThisHeader = recyclerView.getPaddingTop() + stickyHeader.getBottom() + mTempRect2.top + mTempRect2.bottom;
if (topOfNextHeader < bottomOfThisHeader) {
return true;
}
} else {
int leftOfNextHeader = viewAfterHeader.getLeft() - mTempRect1.right - nextHeader.getWidth() - mTempRect1.left;
int rightOfThisHeader = recyclerView.getPaddingLeft() + stickyHeader.getRight() + mTempRect2.left + mTempRect2.right;
if (leftOfNextHeader < rightOfThisHeader) {
return true;
}
}
}
return false;
}
private void translateHeaderWithNextHeader(RecyclerView recyclerView, int orientation, Rect translation,
View currentHeader, View viewAfterNextHeader, View nextHeader) {
mDimensionCalculator.initMargins(mTempRect1, nextHeader);
mDimensionCalculator.initMargins(mTempRect2, currentHeader);
if (orientation == LinearLayoutManager.VERTICAL) {
int topOfStickyHeader = getListTop(recyclerView) + mTempRect2.top + mTempRect2.bottom;
int shiftFromNextHeader = viewAfterNextHeader.getTop() - nextHeader.getHeight() - mTempRect1.bottom - mTempRect1.top - currentHeader.getHeight() - topOfStickyHeader;
if (shiftFromNextHeader < topOfStickyHeader) {
translation.top += shiftFromNextHeader;
}
} else {
int leftOfStickyHeader = getListLeft(recyclerView) + mTempRect2.left + mTempRect2.right;
int shiftFromNextHeader = viewAfterNextHeader.getLeft() - nextHeader.getWidth() - mTempRect1.right - mTempRect1.left - currentHeader.getWidth() - leftOfStickyHeader;
if (shiftFromNextHeader < leftOfStickyHeader) {
translation.left += shiftFromNextHeader;
}
}
}
/**
* Returns the first item currently in the RecyclerView that is not obscured by a header.
*
* @param parent Recyclerview containing all the list items
* @return first item that is fully beneath a header
*/
private View getFirstViewUnobscuredByHeader(RecyclerView parent, View firstHeader) {
boolean isReverseLayout = mOrientationProvider.isReverseLayout(parent);
int step = isReverseLayout? -1 : 1;
int from = isReverseLayout? parent.getChildCount()-1 : 0;
for (int i = from; i >= 0 && i <= parent.getChildCount() - 1; i += step) {
View child = parent.getChildAt(i);
if (!itemIsObscuredByHeader(parent, child, firstHeader, mOrientationProvider.getOrientation(parent))) {
return child;
}
}
return null;
}
/**
* Determines if an item is obscured by a header
*
*
* @param parent
* @param item to determine if obscured by header
* @param header that might be obscuring the item
* @param orientation of the {@link RecyclerView}
* @return true if the item view is obscured by the header view
*/
private boolean itemIsObscuredByHeader(RecyclerView parent, View item, View header, int orientation) {
RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) item.getLayoutParams();
mDimensionCalculator.initMargins(mTempRect1, header);
int adapterPosition = parent.getChildAdapterPosition(item);
if (adapterPosition == RecyclerView.NO_POSITION || mHeaderProvider.getHeader(parent, adapterPosition) != header) {
// Handles an edge case where a trailing header is smaller than the current sticky header.
return false;
}
if (orientation == LinearLayoutManager.VERTICAL) {
int itemTop = item.getTop() - layoutParams.topMargin;
int headerBottom = getListTop(parent) + header.getBottom() + mTempRect1.bottom + mTempRect1.top;
if (itemTop >= headerBottom) {
return false;
}
} else {
int itemLeft = item.getLeft() - layoutParams.leftMargin;
int headerRight = getListLeft(parent) + header.getRight() + mTempRect1.right + mTempRect1.left;
if (itemLeft >= headerRight) {
return false;
}
}
return true;
}
private int getListTop(RecyclerView view) {
if (view.getLayoutManager().getClipToPadding()) {
return view.getPaddingTop();
} else {
return 0;
}
}
private int getListLeft(RecyclerView view) {
if (view.getLayoutManager().getClipToPadding()) {
return view.getPaddingLeft();
} else {
return 0;
}
}
}
|
package org.libreplan.web.common.entrypoints;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
public class MatrixParameters {
private MatrixParameters() {
}
private static Pattern matrixParamPattern = Pattern
.compile(";([^/=;]+)=?([^/;]+)?");
public static Map<String, String> extract(HttpServletRequest request) {
return extract(request.getRequestURI());
}
/**
* Extracts matrix parameters but skipping "jsessionid"
*/
public static Map<String, String> extract(String string) {
Map<String, String> result = new HashMap<String, String>();
Matcher matcher = matrixParamPattern.matcher(string);
while (matcher.find()) {
if (!matcher.group(1).equals("jsessionid")) {
result.put(matcher.group(1), matcher.group(2));
}
}
return result;
}
}
|
package com.excelian.mache.integrations.eventing;
import com.codeaffine.test.ConditionalIgnoreRule;
import com.excelian.mache.core.NoRunningKafkaForTests;
import com.excelian.mache.events.MQFactory;
import com.excelian.mache.events.integration.DefaultKafkaMqConfig;
import com.excelian.mache.events.integration.KafkaMQFactory;
import org.junit.Rule;
import com.excelian.mache.core.NotRunningInExcelian;
import javax.jms.JMSException;
import java.io.IOException;
import static com.codeaffine.test.ConditionalIgnoreRule.IgnoreIf;
@IgnoreIf(condition = NotRunningInExcelian.class)
public class KafkaEventingTest extends TestEventingBase {
@Rule
public final ConditionalIgnoreRule rule = new ConditionalIgnoreRule();
@SuppressWarnings("rawtypes")
@Override
protected MQFactory buildMQFactory() throws JMSException, IOException {
return new KafkaMQFactory(new NoRunningKafkaForTests().HostName(), new DefaultKafkaMqConfig());
}
}
|
package org.mobicents.protocols.ss7.map.api.errors;
import java.io.Serializable;
/**
* Base class of MAP ReturnError messages
*
* @author sergey vetyutnev
*
*/
public interface MAPErrorMessage extends Serializable {
public Long getErrorCode();
public boolean isEmParameterless();
public boolean isEmExtensionContainer();
public boolean isEmFacilityNotSup();
public boolean isEmSMDeliveryFailure();
public boolean isEmSystemFailure();
public boolean isEmUnknownSubscriber();
public boolean isEmAbsentSubscriberSM();
public boolean isEmAbsentSubscriber();
public boolean isEmSubscriberBusyForMtSms();
public boolean isEmCallBarred();
public boolean isEmUnauthorizedLCSClient();
public boolean isEmPositionMethodFailure();
public MAPErrorMessageParameterless getEmParameterless();
public MAPErrorMessageExtensionContainer getEmExtensionContainer();
public MAPErrorMessageFacilityNotSup getEmFacilityNotSup();
public MAPErrorMessageSMDeliveryFailure getEmSMDeliveryFailure();
public MAPErrorMessageSystemFailure getEmSystemFailure();
public MAPErrorMessageUnknownSubscriber getEmUnknownSubscriber();
public MAPErrorMessageAbsentSubscriberSM getEmAbsentSubscriberSM();
public MAPErrorMessageAbsentSubscriber getEmAbsentSubscriber();
public MAPErrorMessageSubscriberBusyForMtSms getEmSubscriberBusyForMtSms();
public MAPErrorMessageCallBarred getEmCallBarred();
public MAPErrorMessageUnauthorizedLCSClient getEmUnauthorizedLCSClient();
public MAPErrorMessagePositionMethodFailure getEmPositionMethodFailure();
}
|
package org.apache.geronimo.xml.deployment;
import java.io.File;
import java.io.FileReader;
import junit.framework.TestCase;
import org.apache.geronimo.deployment.model.geronimo.appclient.ApplicationClient;
import org.apache.geronimo.deployment.model.geronimo.j2ee.EjbRef;
import org.apache.geronimo.deployment.model.geronimo.j2ee.ServiceRef;
import org.apache.geronimo.deployment.model.geronimo.j2ee.ResourceRef;
import org.apache.geronimo.deployment.model.geronimo.j2ee.ResourceEnvRef;
import org.apache.geronimo.deployment.model.geronimo.j2ee.MessageDestinationRef;
import org.apache.geronimo.deployment.model.j2ee.EnvEntry;
import org.apache.geronimo.deployment.model.geronimo.j2ee.MessageDestination;
import org.w3c.dom.Document;
public class GeronimoAppClientLoaderTest extends TestCase {
private File docDir;
private GeronimoAppClientLoader loader;
public void testLoad() throws Exception {
File f = new File(docDir, "geronimo-app-client.xml");
Document doc = LoaderUtil.parseXML(new FileReader(f));
ApplicationClient client = loader.load(doc);
EnvEntry[] envEntries = client.getEnvEntry();
assertEquals(1, envEntries.length);
EnvEntry envEntry = envEntries[0];
assertEquals("hello", envEntry.getEnvEntryName());
assertEquals("java.lang.String", envEntry.getEnvEntryType());
assertEquals("Hello World", envEntry.getEnvEntryValue());
EjbRef[] ejbRefs = client.getGeronimoEJBRef();
assertEquals(1, ejbRefs.length);
EjbRef ejbRef = ejbRefs[0];
assertEquals("ejb/MyEJB", ejbRef.getEJBRefName());
assertEquals("Session", ejbRef.getEJBRefType());
assertEquals("my.EJB.Home", ejbRef.getHome());
assertEquals("my.EJB.Remote", ejbRef.getRemote());
assertNull(ejbRef.getEJBLink());
assertEquals("TestEJB", ejbRef.getJndiName());
ServiceRef[] serviceRefs = client.getGeronimoServiceRef();
assertEquals(1, serviceRefs.length);
ServiceRef serviceRef = serviceRefs[0];
assertEquals("service/MyService", serviceRef.getServiceRefName());
assertEquals("javax.xml.rpc.Service", serviceRef.getServiceInterface());
ResourceRef[] resourceRefs = client.getGeronimoResourceRef();
assertEquals(1, resourceRefs.length);
ResourceRef resourceRef = resourceRefs[0];
assertEquals("jdbc/MyDS", resourceRef.getResRefName());
assertEquals("javax.sql.DataSource", resourceRef.getResType());
assertEquals("Container", resourceRef.getResAuth());
assertEquals("Shareable", resourceRef.getResSharingScope());
assertEquals("TestDS", resourceRef.getJndiName());
ResourceEnvRef[] resEnvRefs = client.getGeronimoResourceEnvRef();
assertEquals(1, resEnvRefs.length);
ResourceEnvRef resEnvRef = resEnvRefs[0];
assertEquals("jms/MyOldQueue", resEnvRef.getResourceEnvRefName());
assertEquals("javax.jms.Queue", resEnvRef.getResourceEnvRefType());
assertEquals("TestQueue", resEnvRef.getJndiName());
MessageDestinationRef[] msgDestRefs = client.getGeronimoMessageDestinationRef();
assertEquals(1, msgDestRefs.length);
MessageDestinationRef msgDestRef = msgDestRefs[0];
assertEquals("jms/MyQueue", msgDestRef.getMessageDestinationRefName());
assertEquals("javax.jms.Queue", msgDestRef.getMessageDestinationType());
assertEquals("TestQueue", msgDestRef.getJndiName());
assertEquals(client.getCallbackHandler(), "my.callback.handler");
MessageDestination[] msgDests = client.getGeronimoMessageDestination();
assertEquals(1, msgDests.length);
MessageDestination msgDest = msgDests[0];
assertEquals("jms/MyOwnQueue", msgDest.getMessageDestinationName());
assertEquals("TestQueue", msgDest.getJndiName());
}
protected void setUp() throws Exception {
docDir = new File("src/test-data/xml/deployment");
loader = new GeronimoAppClientLoader();
}
}
|
package org.motechproject.server.svc.impl;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.motechproject.server.messaging.MessageDefDate;
import org.motechproject.server.messaging.MessageNotFoundException;
import org.motechproject.server.model.*;
import org.motechproject.server.model.MessageStatus;
import org.motechproject.server.omod.*;
import org.motechproject.server.omod.builder.PatientBuilder;
import org.motechproject.server.omod.factory.DistrictFactory;
import org.motechproject.server.omod.impl.MessageProgramServiceImpl;
import org.motechproject.server.omod.web.model.WebStaff;
import org.motechproject.server.svc.BirthOutcomeChild;
import org.motechproject.server.svc.OpenmrsBean;
import org.motechproject.server.svc.RCTService;
import org.motechproject.server.svc.RegistrarBean;
import org.motechproject.server.util.GenderTypeConverter;
import org.motechproject.server.util.MotechConstants;
import org.motechproject.server.util.Password;
import org.motechproject.server.ws.WebServiceModelConverterImpl;
import org.motechproject.ws.*;
import org.motechproject.ws.mobile.MessageService;
import org.openmrs.*;
import org.openmrs.Patient;
import org.openmrs.api.*;
import org.openmrs.scheduler.SchedulerService;
import org.openmrs.scheduler.TaskDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;
import static org.motechproject.server.omod.PatientIdentifierTypeEnum.PATIENT_IDENTIFIER_MOTECH_ID;
/**
* An implementation of the RegistrarBean interface, implemented using a mix of
* OpenMRS and module defined services.
*/
public class RegistrarBeanImpl implements RegistrarBean, OpenmrsBean {
private static Log log = LogFactory.getLog(RegistrarBeanImpl.class);
private ContextService contextService;
private MessageService mobileService;
private PatientService patientService;
private PersonService personService;
private RelationshipService relationshipService;
private UserService userService;
private AuthenticationService authenticationService;
private ConceptService conceptService;
private LocationService locationService;
private ObsService obsService;
private EncounterService encounterService;
private SchedulerService schedulerService;
private AdministrationService administrationService;
private RCTService rctService;
private MessageProgramServiceImpl messageProgramService;
@Autowired
private IdentifierGenerator identifierGenerator;
private List<String> staffTypes;
@Autowired
private MotechUserRepository motechUserRepository;
private final DistrictFactory DISTRICT_FACTORY = new DistrictFactory();
public void setContextService(ContextService contextService) {
this.contextService = contextService;
}
public void setMobileService(MessageService mobileService) {
this.mobileService = mobileService;
}
public User registerStaff(String firstName, String lastName, String phone,
String staffType, String staffId) {
User staff = null;
if (staffId != null) {
staff = motechUserRepository.updateUser(getStaffBySystemId(staffId), new WebStaff(firstName, lastName, phone, staffType));
} else {
staff = motechUserRepository.newUser(new WebStaff(firstName, lastName, phone, staffType));
}
return userService.saveUser(staff, generatePassword(8));
}
private String generatePassword(int length) {
return new Password(length).create();
}
@Transactional
public Patient registerPatient(RegistrationMode registrationMode,
Integer motechId, RegistrantType registrantType, String firstName,
String middleName, String lastName, String preferredName,
Date dateOfBirth, Boolean estimatedBirthDate, Gender sex,
Boolean insured, String nhis, Date nhisExpires, Patient mother,
Community community, Facility facility, String address, String phoneNumber,
Date expDeliveryDate, Boolean deliveryDateConfirmed,
Boolean enroll, Boolean consent, ContactNumberType ownership,
MediaType format, String language, DayOfWeek dayOfWeek,
Date timeOfDay, InterestReason reason, HowLearned howLearned,
Integer messagesStartWeek) {
User staff = authenticationService.getAuthenticatedUser();
Date date = new Date();
return registerPatient(staff, facility, date, registrationMode,
motechId, registrantType, firstName, middleName, lastName,
preferredName, dateOfBirth, estimatedBirthDate, sex, insured,
nhis, nhisExpires, mother, community, address, phoneNumber,
expDeliveryDate, deliveryDateConfirmed, enroll, consent,
ownership, format, language, dayOfWeek, timeOfDay, reason,
howLearned, messagesStartWeek);
}
@Transactional
public Patient registerPatient(User staff, Facility facility, Date date,
RegistrationMode registrationMode, Integer motechId,
RegistrantType registrantType, String firstName, String middleName,
String lastName, String preferredName, Date dateOfBirth,
Boolean estimatedBirthDate, Gender sex, Boolean insured,
String nhis, Date nhisExpires, Patient mother, Community community,
String address, String phoneNumber, Date expDeliveryDate,
Boolean deliveryDateConfirmed, Boolean enroll, Boolean consent,
ContactNumberType ownership, MediaType format, String language,
DayOfWeek dayOfWeek, Date timeOfDay, InterestReason reason,
HowLearned howLearned, Integer messagesStartWeek) {
Patient patient = createPatient(staff, motechId, firstName, middleName,
lastName, preferredName, dateOfBirth, estimatedBirthDate, sex,
insured, nhis, nhisExpires, address, phoneNumber, ownership,
format, language, dayOfWeek, timeOfDay, howLearned, reason, registrantType, mother);
patient = patientService.savePatient(patient);
if (isChildWithMother(registrantType, mother)) {
childRegistrationPostProcessing(staff, patient, mother, facility, community, enroll, consent, messagesStartWeek, date);
} else if (registrantType == RegistrantType.PREGNANT_MOTHER) {
motherRegistrationPostProcessing(staff, patient, facility, community, enroll, consent, messagesStartWeek, date, expDeliveryDate, deliveryDateConfirmed);
} else {
patientRegistrationPostProcessing(staff, patient, facility, community, enroll, consent, messagesStartWeek, null, date);
}
return patient;
}
private boolean isChildWithMother(RegistrantType registrantType, Patient mother) {
return registrantType == RegistrantType.CHILD_UNDER_FIVE && mother != null;
}
private void childRegistrationPostProcessing(User staff, Patient child, Patient mother, Facility facility, Community community,
Boolean enroll, Boolean consent, Integer messagesStartWeek,
Date date) {
if (community == null) {
community = getCommunityByPatient(mother);
}
if (enroll == null && consent == null) {
List<MessageProgramEnrollment> enrollments = motechService().getActiveMessageProgramEnrollments(mother.getPatientId(), null, null, null, null);
if (enrollments != null && !enrollments.isEmpty()) {
enroll = true;
consent = true;
}
}
if (mother != null) {
relationshipService.createMotherChildRelationship(mother, child);
}
patientRegistrationPostProcessing(staff, child, facility, community, enroll, consent, messagesStartWeek, null, date);
}
private void motherRegistrationPostProcessing(User staff, Patient mother, Facility facility, Community community,
Boolean enroll, Boolean consent, Integer messagesStartWeek, Date date, Date expDeliveryDate,
Boolean deliveryDateConfirmed) {
Integer pregnancyDueDateObsId = registerPregnancy(staff, facility.getLocation(), date, mother, expDeliveryDate, deliveryDateConfirmed);
patientRegistrationPostProcessing(staff, mother, facility, community, enroll, consent, messagesStartWeek, pregnancyDueDateObsId, date);
}
private void patientRegistrationPostProcessing(User staff, Patient patient, Facility facility, Community community,
Boolean enroll, Boolean consent, Integer messagesStartWeek, Integer pregnancyDueDateObsId,
Date date) {
if (community != null) {
community.getResidents().add(patient);
}
facility.addPatient(patient);
enrollPatient(patient, enroll, consent, messagesStartWeek, pregnancyDueDateObsId);
recordPatientRegistration(staff, facility.getLocation(), date, patient);
}
private void enrollPatientWithAttributes(Patient patient,
Boolean enroll, Boolean consent,
ContactNumberType ownership, String phoneNumber, MediaType format,
String language, DayOfWeek dayOfWeek, Date timeOfDay,
InterestReason reason, HowLearned howLearned,
Integer messagesStartWeek, Integer pregnancyDueDateObsId) {
setPatientAttributes(patient, phoneNumber, ownership, format, language,
dayOfWeek, timeOfDay, howLearned, reason, null, null, null);
patientService.savePatient(patient);
enrollPatient(patient, enroll, consent, messagesStartWeek,
pregnancyDueDateObsId);
}
private void enrollPatient(Patient patient,
Boolean enroll, Boolean consent, Integer messagesStartWeek,
Integer pregnancyDueDateObsId) {
boolean enrollPatient = Boolean.TRUE.equals(enroll)
&& Boolean.TRUE.equals(consent);
Integer referenceDateObsId = null;
String infoMessageProgramName = null;
if (pregnancyDueDateObsId != null) {
infoMessageProgramName = "Weekly Pregnancy Message Program";
referenceDateObsId = pregnancyDueDateObsId;
} else if (messagesStartWeek != null) {
infoMessageProgramName = "Weekly Info Pregnancy Message Program";
if (enrollPatient) {
referenceDateObsId = storeMessagesWeekObs(patient,
messagesStartWeek);
}
} else if (patient.getAge() != null && patient.getAge() < 5) {
infoMessageProgramName = "Weekly Info Child Message Program";
// TODO: If mother specified, Remove mother's pregnancy message
// enrollment
}
if (enrollPatient) {
if (infoMessageProgramName != null) {
addMessageProgramEnrollment(patient.getPatientId(),
infoMessageProgramName, referenceDateObsId);
}
addMessageProgramEnrollment(patient.getPatientId(), "Expected Care Message Program", null);
}
}
private Integer storeMessagesWeekObs(Patient patient,
Integer messagesStartWeek) {
Location ghanaLocation = getGhanaLocation();
Date currentDate = new Date();
Calendar calendar = Calendar.getInstance();
// Convert weeks to days, plus one day
calendar.add(Calendar.DATE, (messagesStartWeek * -7) + 1);
Date referenceDate = calendar.getTime();
Obs refDateObs = createDateValueObs(currentDate,
concept(ConceptEnum.CONCEPT_ENROLLMENT_REFERENCE_DATE), patient, ghanaLocation,
referenceDate, null, null);
refDateObs = obsService.saveObs(refDateObs, null);
return refDateObs.getObsId();
}
@Transactional
public void demoRegisterPatient(RegistrationMode registrationMode,
Integer motechId, String firstName, String middleName,
String lastName, String preferredName, Date dateOfBirth,
Boolean estimatedBirthDate, Gender sex, Boolean insured,
String nhis, Date nhisExpires, Community community, String address,
String phoneNumber, Boolean enroll, Boolean consent,
ContactNumberType ownership, MediaType format, String language,
DayOfWeek dayOfWeek, Date timeOfDay, InterestReason reason,
HowLearned howLearned) {
User staff = contextService.getAuthenticatedUser();
Patient patient = createPatient(staff, motechId, firstName, middleName,
lastName, preferredName, dateOfBirth, estimatedBirthDate, sex,
insured, nhis, nhisExpires, address, phoneNumber, ownership,
format, language, dayOfWeek, timeOfDay, howLearned, reason, RegistrantType.OTHER, null);
patient = patientService.savePatient(patient);
if (Boolean.TRUE.equals(enroll) && Boolean.TRUE.equals(consent)) {
addMessageProgramEnrollment(patient.getPatientId(),
"Demo Minute Message Program", null);
}
}
@Transactional
public void demoEnrollPatient(Patient patient) {
addMessageProgramEnrollment(patient.getPersonId(),
"Input Demo Message Program", null);
}
@Transactional
private Patient createPatient(User staff, Integer motechId,
String firstName, String middleName, String lastName,
String prefName, Date birthDate, Boolean birthDateEst, Gender sex,
Boolean insured, String nhis, Date nhisExpDate, String address,
String phoneNumber, ContactNumberType phoneType,
MediaType mediaType, String language, DayOfWeek dayOfWeek,
Date timeOfDay, HowLearned howLearned, InterestReason interestReason, RegistrantType registrantType, Patient mother) {
PatientBuilder patientBuilder = new PatientBuilder(personService, motechService(), identifierGenerator, registrantType, patientService, locationService);
SimpleDateFormat timeFormatter = new SimpleDateFormat(MotechConstants.TIME_FORMAT_DELIVERY_TIME);
SimpleDateFormat dateFormatter = new SimpleDateFormat(MotechConstants.DATE_FORMAT);
patientBuilder.setMotechId(motechId).setName(firstName, middleName, lastName)
.setPreferredName(prefName).setGender(sex).setBirthDate(birthDate)
.setBirthDateEstimated(birthDateEst).setAddress1(address).setParent(mother);
try {
patientBuilder.addAttribute(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_PHONE_NUMBER, phoneNumber, "toString");
patientBuilder.addAttribute(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_PHONE_TYPE, phoneType, "name");
patientBuilder.addAttribute(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_MEDIA_TYPE, mediaType, "name");
patientBuilder.addAttribute(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_LANGUAGE, language, "toString");
patientBuilder.addAttribute(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_DELIVERY_DAY, dayOfWeek, "name");
patientBuilder.addAttribute(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_DELIVERY_TIME, timeOfDay, timeFormatter, "format");
patientBuilder.addAttribute(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_HOW_LEARNED, howLearned, "name");
patientBuilder.addAttribute(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_INTEREST_REASON, interestReason, "name");
patientBuilder.addAttribute(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_INSURED, insured, "toString");
patientBuilder.addAttribute(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_NHIS_NUMBER, nhis, "toString");
patientBuilder.addAttribute(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_NHIS_EXP_DATE, nhisExpDate, dateFormatter, "format");
} catch (NoSuchMethodException e) {
log.error("Value Method not found on the invocation target");
} catch (InvocationTargetException e) {
log.error("Invalid invocation target set for the value method");
} catch (IllegalAccessException e) {
log.error("Value method is not accessible on the invocation target");
}
return patientBuilder.build();
}
private void recordPatientRegistration(User staff, Location facility,
Date date, Patient patient) {
Encounter encounter = new Encounter();
encounter.setEncounterType(getEncounterType(EncounterTypeEnum.ENCOUNTER_TYPE_PATIENTREGVISIT));
encounter.setEncounterDatetime(date);
encounter.setPatient(patient);
encounter.setLocation(facility);
encounter.setProvider(staff);
encounterService.saveEncounter(encounter);
}
private void setPatientAttributes(Patient patient, String phoneNumber,
ContactNumberType phoneType, MediaType mediaType, String language,
DayOfWeek dayOfWeek, Date timeOfDay, HowLearned howLearned,
InterestReason interestReason, Boolean insured, String nhis,
Date nhisExpDate) {
List<PersonAttribute> attrs = new ArrayList<PersonAttribute>();
if (phoneNumber != null) {
attrs.add(new PersonAttribute(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_PHONE_NUMBER.getAttributeType(personService),
phoneNumber));
}
if (phoneType != null) {
attrs.add(new PersonAttribute(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_PHONE_TYPE.getAttributeType(personService),
phoneType.name()));
}
if (mediaType != null) {
attrs.add(new PersonAttribute(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_MEDIA_TYPE.getAttributeType(personService),
mediaType.name()));
}
if (language != null) {
attrs
.add(new PersonAttribute(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_LANGUAGE.getAttributeType(personService),
language));
}
if (dayOfWeek != null) {
attrs.add(new PersonAttribute(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_DELIVERY_DAY.getAttributeType(personService),
dayOfWeek.name()));
}
if (timeOfDay != null) {
SimpleDateFormat formatter = new SimpleDateFormat(
MotechConstants.TIME_FORMAT_DELIVERY_TIME);
attrs.add(new PersonAttribute(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_DELIVERY_TIME.getAttributeType(personService),
formatter.format(timeOfDay)));
}
if (howLearned != null) {
attrs.add(new PersonAttribute(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_HOW_LEARNED.getAttributeType(personService),
howLearned.name()));
}
if (interestReason != null) {
attrs.add(new PersonAttribute(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_INTEREST_REASON.getAttributeType(personService),
interestReason.name()));
}
if (insured != null) {
attrs.add(new PersonAttribute(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_INSURED.getAttributeType(personService), insured
.toString()));
}
if (nhis != null) {
attrs.add(new PersonAttribute(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_NHIS_NUMBER.getAttributeType(personService), nhis));
}
if (nhisExpDate != null) {
SimpleDateFormat formatter = new SimpleDateFormat(
MotechConstants.DATE_FORMAT);
attrs.add(new PersonAttribute(PersonAttributeTypeEnum.PERSON_ATTRIBUTE_NHIS_EXP_DATE.getAttributeType(personService),
formatter.format(nhisExpDate)));
}
for (PersonAttribute attr : attrs)
patient.addAttribute(attr);
}
@Transactional
public void editPatient(User staff, Date date, Patient patient, Patient mother,
String phoneNumber, ContactNumberType phoneOwnership, String nhis,
Date nhisExpires, Date expectedDeliveryDate, Boolean stopEnrollment) {
if (expectedDeliveryDate != null) {
Obs pregnancy = getActivePregnancy(patient.getPatientId());
Obs dueDateObs = getActivePregnancyDueDateObs(patient
.getPatientId(), pregnancy);
if (dueDateObs != null) {
if (!expectedDeliveryDate.equals(dueDateObs.getValueDatetime())) {
updatePregnancyDueDateObs(pregnancy,
dueDateObs, expectedDeliveryDate, dueDateObs
.getEncounter());
}
}
}
setPatientAttributes(patient, phoneNumber, phoneOwnership, null, null,
null, null, null, null, null, nhis, nhisExpires);
patientService.savePatient(patient);
relationshipService.saveOrUpdateMotherRelationship(mother, patient, false);
if (Boolean.TRUE.equals(stopEnrollment)) {
stopEnrollmentFor(patient.getPatientId());
}
}
@Transactional
public void stopEnrollmentFor(Integer patientId) {
removeAllMessageProgramEnrollments(patientId);
}
@Transactional
public void editPatient(Patient patient, String firstName,
String middleName, String lastName, String preferredName,
Date dateOfBirth, Boolean estimatedBirthDate, Gender sex,
Boolean insured, String nhis, Date nhisExpires, Patient mother,
Community community, String address, String phoneNumber,
Date expDeliveryDate, Boolean enroll, Boolean consent,
ContactNumberType ownership, MediaType format, String language,
DayOfWeek dayOfWeek, Date timeOfDay, Facility facility) {
patient.setBirthdate(dateOfBirth);
patient.setBirthdateEstimated(estimatedBirthDate);
patient.setGender(GenderTypeConverter.toOpenMRSString(sex));
Set<PersonName> patientNames = patient.getNames();
if (patientNames.isEmpty()) {
patient.addName(new PersonName(firstName, middleName, lastName));
if (preferredName != null) {
PersonName preferredPersonName = new PersonName(preferredName,
middleName, lastName);
preferredPersonName.setPreferred(true);
patient.addName(preferredPersonName);
}
} else {
for (PersonName name : patient.getNames()) {
if (name.isPreferred()) {
if (preferredName != null) {
name.setGivenName(preferredName);
name.setFamilyName(lastName);
name.setMiddleName(middleName);
} else {
patient.removeName(name);
}
} else {
name.setGivenName(firstName);
name.setMiddleName(middleName);
name.setFamilyName(lastName);
}
}
}
PersonAddress patientAddress = patient.getPersonAddress();
if (patientAddress == null) {
patientAddress = new PersonAddress();
patientAddress.setAddress1(address);
patient.addAddress(patientAddress);
} else {
patientAddress.setAddress1(address);
}
relationshipService.saveOrUpdateMotherRelationship(mother, patient, true);
PatientEditor editor = new PatientEditor(patient);
Facility currentFacility = getFacilityByPatient(patient);
if (!currentFacility.equals(facility)) {
patient = editor.removeFrom(currentFacility).addTo(facility).done();
}
Community currentCommunity = getCommunityByPatient(patient);
boolean bothCommunitiesExistAndAreSame = community != null && currentCommunity != null && currentCommunity.equals(community);
if (!bothCommunitiesExistAndAreSame) {
patient = editor.removeFrom(currentCommunity).addTo(community).done();
}
setPatientAttributes(patient, phoneNumber, ownership, format, language,
dayOfWeek, timeOfDay, null, null, insured, nhis, nhisExpires);
patientService.savePatient(patient);
Integer dueDateObsId = null;
if (expDeliveryDate != null) {
Obs pregnancy = getActivePregnancy(patient.getPatientId());
Obs dueDateObs = getActivePregnancyDueDateObs(patient
.getPatientId(), pregnancy);
if (dueDateObs != null) {
dueDateObsId = dueDateObs.getObsId();
if (!expDeliveryDate.equals(dueDateObs.getValueDatetime())) {
dueDateObsId = updatePregnancyDueDateObs(pregnancy,
dueDateObs, expDeliveryDate, dueDateObs
.getEncounter());
}
}
}
if (Boolean.FALSE.equals(enroll)) {
removeAllMessageProgramEnrollments(patient.getPatientId());
} else {
enrollPatient(patient, enroll, consent, null,
dueDateObsId);
}
}
@Transactional
public void registerPregnancy(Patient patient, Date expDeliveryDate,
Boolean deliveryDateConfirmed, Boolean enroll, Boolean consent,
String phoneNumber, ContactNumberType ownership, MediaType format,
String language, DayOfWeek dayOfWeek, Date timeOfDay,
InterestReason reason, HowLearned howLearned) {
Integer pregnancyDueDateObsId = checkExistingPregnancy(patient);
Location facility = getGhanaLocation();
User staff = authenticationService.getAuthenticatedUser();
Date date = new Date();
if (pregnancyDueDateObsId == null) {
pregnancyDueDateObsId = registerPregnancy(staff, facility, date,
patient, expDeliveryDate, deliveryDateConfirmed);
}
enrollPatientWithAttributes(patient, enroll, consent, ownership,
phoneNumber, format, language, dayOfWeek, timeOfDay, reason,
howLearned, null, pregnancyDueDateObsId);
}
private Integer registerPregnancy(User staff, Location facility, Date date,
Patient patient, Date dueDate, Boolean dueDateConfirmed) {
Encounter encounter = new Encounter();
encounter
.setEncounterType(getEncounterType(EncounterTypeEnum.ENCOUNTER_TYPE_PREGREGVISIT));
encounter.setEncounterDatetime(date);
encounter.setPatient(patient);
encounter.setLocation(facility);
encounter.setProvider(staff);
encounter = encounterService.saveEncounter(encounter);
Obs pregnancyObs = createObs(date, concept(ConceptEnum.CONCEPT_PREGNANCY), patient,
facility, encounter, null);
Obs pregnancyStatusObs = createBooleanValueObs(date,
concept(ConceptEnum.CONCEPT_PREGNANCY_STATUS), patient, facility, Boolean.TRUE,
encounter, null);
pregnancyObs.addGroupMember(pregnancyStatusObs);
Obs dueDateObs = null;
if (dueDate != null) {
dueDateObs = createDateValueObs(date, concept(ConceptEnum.CONCEPT_ESTIMATED_DATE_OF_CONFINEMENT),
patient, facility, dueDate, encounter, null);
pregnancyObs.addGroupMember(dueDateObs);
}
if (dueDateConfirmed != null) {
Obs dueDateConfirmedObs = createBooleanValueObs(date,
concept(ConceptEnum.CONCEPT_DATE_OF_CONFINEMENT_CONFIRMED), patient, facility,
dueDateConfirmed, encounter, null);
pregnancyObs.addGroupMember(dueDateConfirmedObs);
}
obsService.saveObs(pregnancyObs, null);
if (dueDateObs != null) {
return dueDateObs.getObsId();
}
return null;
}
@Transactional
public void registerPregnancy(User staff, Location facility, Date date,
Patient patient, Date estDeliveryDate, Boolean enroll,
Boolean consent, ContactNumberType ownership, String phoneNumber,
MediaType format, String language, DayOfWeek dayOfWeek,
Date timeOfDay, HowLearned howLearned) {
Integer pregnancyDueDateObsId = checkExistingPregnancy(patient);
if (pregnancyDueDateObsId == null) {
pregnancyDueDateObsId = registerPregnancy(staff, facility, date,
patient, estDeliveryDate, null);
}
enrollPatientWithAttributes(patient, enroll, consent, ownership,
phoneNumber, format, language, dayOfWeek, timeOfDay, null,
howLearned, null, pregnancyDueDateObsId);
}
private Integer checkExistingPregnancy(Patient patient) {
Obs pregnancyObs = getActivePregnancy(patient.getPatientId());
Integer pregnancyDueDateObsId = null;
if (pregnancyObs != null) {
log.warn("Entering Pregnancy for patient with active pregnancy, "
+ "patient id=" + patient.getPatientId());
Obs pregnancyDueDateObs = getActivePregnancyDueDateObs(patient
.getPatientId(), pregnancyObs);
if (pregnancyDueDateObs != null) {
pregnancyDueDateObsId = pregnancyDueDateObs.getObsId();
} else {
log.warn("No due date found for active pregnancy, patient id="
+ patient.getPatientId());
}
}
return pregnancyDueDateObsId;
}
public void recordPatientHistory(User staff, Location facility, Date date,
Patient patient, Integer lastIPT, Date lastIPTDate, Integer lastTT,
Date lastTTDate, Date bcgDate, Integer lastOPV, Date lastOPVDate,
Integer lastPenta, Date lastPentaDate, Date measlesDate,
Date yellowFeverDate, Integer lastIPTI, Date lastIPTIDate,
Date lastVitaminADate, Integer whyNoHistory) {
// Not associating historical data with any facility
Location ghanaLocation = getGhanaLocation();
Encounter historyEncounter = new Encounter();
historyEncounter.setEncounterType(getEncounterType(EncounterTypeEnum.ENCOUNTER_TYPE_PATIENTHISTORY));
historyEncounter.setEncounterDatetime(date);
historyEncounter.setPatient(patient);
historyEncounter.setLocation(ghanaLocation);
historyEncounter.setProvider(staff);
if (lastIPT != null && lastIPTDate != null) {
Obs iptDoseObs = createNumericValueObs(lastIPTDate,
concept(ConceptEnum.CONCEPT_INTERMITTENT_PREVENTATIVE_TREATMENT_DOSE), patient, ghanaLocation, lastIPT,
historyEncounter, null);
historyEncounter.addObs(iptDoseObs);
}
if (lastTT != null && lastTTDate != null) {
Obs ttDoseObs = createNumericValueObs(lastTTDate,
concept(ConceptEnum.CONCEPT_TETANUS_TOXOID_DOSE), patient, ghanaLocation, lastTT,
historyEncounter, null);
historyEncounter.addObs(ttDoseObs);
}
if (bcgDate != null) {
Obs bcgObs = createConceptValueObs(bcgDate,
concept(ConceptEnum.CONCEPT_IMMUNIZATIONS_ORDERED), patient, ghanaLocation,
concept(ConceptEnum.CONCEPT_BCG_VACCINATION), historyEncounter, null);
historyEncounter.addObs(bcgObs);
}
if (lastOPV != null && lastOPVDate != null) {
Obs opvDoseObs = createNumericValueObs(lastOPVDate,
concept(ConceptEnum.CONCEPT_ORAL_POLIO_VACCINATION_DOSE),
patient, ghanaLocation, lastOPV,
historyEncounter, null);
historyEncounter.addObs(opvDoseObs);
}
if (lastPenta != null && lastPentaDate != null) {
Obs pentaDoseObs = createNumericValueObs(lastPentaDate,
concept(ConceptEnum.CONCEPT_PENTA_VACCINATION_DOSE), patient, ghanaLocation, lastPenta,
historyEncounter, null);
historyEncounter.addObs(pentaDoseObs);
}
if (measlesDate != null) {
Obs measlesObs = createConceptValueObs(measlesDate,
concept(ConceptEnum.CONCEPT_IMMUNIZATIONS_ORDERED), patient, ghanaLocation,
concept(ConceptEnum.CONCEPT_MEASLES_VACCINATION), historyEncounter, null);
historyEncounter.addObs(measlesObs);
}
if (yellowFeverDate != null) {
Obs yellowFeverObs = createConceptValueObs(yellowFeverDate,
concept(ConceptEnum.CONCEPT_IMMUNIZATIONS_ORDERED), patient, ghanaLocation,
concept(ConceptEnum.CONCEPT_YELLOW_FEVER_VACCINATION), historyEncounter, null);
historyEncounter.addObs(yellowFeverObs);
}
if (lastIPTI != null && lastIPTIDate != null) {
Obs iptiObs = createNumericValueObs(lastIPTIDate,
concept(ConceptEnum.CONCEPT_INTERMITTENT_PREVENTATIVE_TREATMENT_INFANTS_DOSE),
patient, ghanaLocation, lastIPTI,
historyEncounter, null);
historyEncounter.addObs(iptiObs);
}
if (lastVitaminADate != null) {
Obs vitaminAObs = createConceptValueObs(lastVitaminADate,
concept(ConceptEnum.CONCEPT_IMMUNIZATIONS_ORDERED), patient, ghanaLocation,
concept(ConceptEnum.CONCEPT_VITAMIN_A), historyEncounter, null);
historyEncounter.addObs(vitaminAObs);
}
if (whyNoHistory != null) {
Obs whyNoHistoryObs = createNumericValueObs(date,
concept(ConceptEnum.CONCEPT_WHY_NO_HISTORY), patient, ghanaLocation, whyNoHistory,
historyEncounter, null);
historyEncounter.addObs(whyNoHistoryObs);
}
if (!historyEncounter.getAllObs().isEmpty()) {
encounterService.saveEncounter(historyEncounter);
}
}
@Transactional
public void registerANCMother(User staff, Location facility, Date date,
Patient patient, String ancRegNumber, Date estDeliveryDate,
Double height, Integer gravida, Integer parity, Boolean enroll,
Boolean consent, ContactNumberType ownership, String phoneNumber,
MediaType format, String language, DayOfWeek dayOfWeek,
Date timeOfDay, HowLearned howLearned) {
Encounter encounter = new Encounter();
encounter.setEncounterType(getEncounterType(EncounterTypeEnum.ENCOUNTER_TYPE_ANCREGVISIT));
encounter.setEncounterDatetime(date);
encounter.setPatient(patient);
encounter.setLocation(facility);
encounter.setProvider(staff);
if (ancRegNumber != null) {
Obs ancRegNumObs = createTextValueObs(date,
concept(ConceptEnum.CONCEPT_ANC_REG_NUMBER), patient, facility,
ancRegNumber, encounter, null);
encounter.addObs(ancRegNumObs);
}
if (gravida != null) {
Obs gravidaObs = createNumericValueObs(date, concept(ConceptEnum.CONCEPT_GRAVIDA),
patient, facility, gravida, encounter, null);
encounter.addObs(gravidaObs);
}
if (parity != null) {
Obs parityObs = createNumericValueObs(date, concept(ConceptEnum.CONCEPT_PARITY),
patient, facility, parity, encounter, null);
encounter.addObs(parityObs);
}
if (height != null) {
Obs heightObs = createNumericValueObs(date, concept(ConceptEnum.CONCEPT_HEIGHT),
patient, facility, height, encounter, null);
encounter.addObs(heightObs);
}
encounterService.saveEncounter(encounter);
Integer pregnancyDueDateObsId = null;
Obs pregnancyObs = getActivePregnancy(patient.getPatientId());
if (pregnancyObs == null) {
pregnancyDueDateObsId = registerPregnancy(staff, facility, date,
patient, estDeliveryDate, null);
} else {
Obs pregnancyDueDateObs = getActivePregnancyDueDateObs(patient
.getPatientId(), pregnancyObs);
if (pregnancyDueDateObs != null) {
pregnancyDueDateObsId = pregnancyDueDateObs.getObsId();
if (estDeliveryDate != null) {
pregnancyDueDateObsId = updatePregnancyDueDateObs(
pregnancyObs, pregnancyDueDateObs, estDeliveryDate,
encounter);
}
} else if (estDeliveryDate != null) {
log.warn("Cannot update pregnancy due date, "
+ "no active pregnancy due date found, patient id="
+ patient.getPatientId());
}
}
enrollPatientWithAttributes(patient, enroll, consent, ownership,
phoneNumber, format, language, dayOfWeek, timeOfDay, null,
howLearned, null, pregnancyDueDateObsId);
}
@Transactional
public void registerCWCChild(User staff, Location facility, Date date,
Patient patient, String cwcRegNumber, Boolean enroll,
Boolean consent, ContactNumberType ownership, String phoneNumber,
MediaType format, String language, DayOfWeek dayOfWeek,
Date timeOfDay, HowLearned howLearned) {
enrollPatientWithAttributes(patient, enroll, consent, ownership,
phoneNumber, format, language, dayOfWeek, timeOfDay, null,
howLearned, null, null);
Encounter encounter = new Encounter();
encounter.setEncounterType(getEncounterType(EncounterTypeEnum.ENCOUNTER_TYPE_CWCREGVISIT));
encounter.setEncounterDatetime(date);
encounter.setPatient(patient);
encounter.setLocation(facility);
encounter.setProvider(staff);
if (cwcRegNumber != null) {
Obs cwcRegNumObs = createTextValueObs(date,
concept(ConceptEnum.CONCEPT_CWC_REG_NUMBER), patient, facility,
cwcRegNumber, encounter, null);
encounter.addObs(cwcRegNumObs);
}
encounterService.saveEncounter(encounter);
}
@Transactional
public void recordMotherANCVisit(User staff, Location facility, Date date,
Patient patient, Integer visitNumber, Integer ancLocation,
String house, String community, Date estDeliveryDate,
Integer bpSystolic, Integer bpDiastolic, Double weight,
Integer ttDose, Integer iptDose, Boolean iptReactive,
Boolean itnUse, Double fht, Integer fhr, Integer urineTestProtein,
Integer urineTestGlucose, Double hemoglobin, Boolean vdrlReactive,
Boolean vdrlTreatment, Boolean dewormer, Boolean maleInvolved,
Boolean pmtct, Boolean preTestCounseled, HIVResult hivTestResult,
Boolean postTestCounseled, Boolean pmtctTreatment,
Boolean referred, Date nextANCDate, String comments) {
Encounter encounter = new Encounter();
encounter.setEncounterType(getEncounterType(EncounterTypeEnum.ENCOUNTER_TYPE_ANCVISIT));
encounter.setEncounterDatetime(date);
encounter.setPatient(patient);
encounter.setLocation(facility);
encounter.setProvider(staff);
Obs pregnancyObs = getActivePregnancy(patient.getPatientId());
if (pregnancyObs == null) {
log.warn("Entered ANC visit for patient without active pregnancy, "
+ "patient id=" + patient.getPatientId());
}
if (visitNumber != null) {
Obs visitNumberObs = createNumericValueObs(date,
concept(ConceptEnum.CONCEPT_VISIT_NUMBER), patient, facility, visitNumber,
encounter, null);
encounter.addObs(visitNumberObs);
}
if (ancLocation != null) {
Obs ancLocationObs = createNumericValueObs(date,
concept(ConceptEnum.CONCEPT_ANC_PNC_LOCATION), patient, facility, ancLocation,
encounter, null);
encounter.addObs(ancLocationObs);
}
if (house != null) {
Obs houseObs = createTextValueObs(date, concept(ConceptEnum.CONCEPT_HOUSE),
patient, facility, house, encounter, null);
encounter.addObs(houseObs);
}
if (community != null) {
Obs communityObs = createTextValueObs(date,
concept(ConceptEnum.CONCEPT_COMMUNITY), patient, facility, community,
encounter, null);
encounter.addObs(communityObs);
}
if (bpSystolic != null) {
Obs bpSystolicObs = createNumericValueObs(date,
concept(ConceptEnum.CONCEPT_SYSTOLIC_BLOOD_PRESSURE), patient, facility,
bpSystolic, encounter, null);
encounter.addObs(bpSystolicObs);
}
if (bpDiastolic != null) {
Obs bpDiastolicObs = createNumericValueObs(date,
concept(ConceptEnum.CONCEPT_DIASTOLIC_BLOOD_PRESSURE), patient, facility,
bpDiastolic, encounter, null);
encounter.addObs(bpDiastolicObs);
}
if (weight != null) {
Obs weightObs = createNumericValueObs(date, concept(ConceptEnum.CONCEPT_WEIGHT),
patient, facility, weight, encounter, null);
encounter.addObs(weightObs);
}
if (ttDose != null) {
Obs ttDoseObs = createNumericValueObs(date,
concept(ConceptEnum.CONCEPT_TETANUS_TOXOID_DOSE), patient, facility, ttDose,
encounter, null);
encounter.addObs(ttDoseObs);
}
if (iptDose != null) {
Obs iptDoseObs = createNumericValueObs(date, concept(ConceptEnum.CONCEPT_INTERMITTENT_PREVENTATIVE_TREATMENT_DOSE),
patient, facility, iptDose, encounter, null);
encounter.addObs(iptDoseObs);
}
if (iptReactive != null) {
Concept iptReactionValueConcept = null;
if (Boolean.TRUE.equals(iptReactive)) {
iptReactionValueConcept = concept(ConceptEnum.CONCEPT_REACTIVE);
} else {
iptReactionValueConcept = concept(ConceptEnum.CONCEPT_NON_REACTIVE);
}
Obs iptReactiveObs = createConceptValueObs(date,
concept(ConceptEnum.CONCEPT_IPT_REACTION), patient, facility,
iptReactionValueConcept, encounter, null);
encounter.addObs(iptReactiveObs);
}
if (itnUse != null) {
Obs itnUseObs = createBooleanValueObs(date, concept(ConceptEnum.CONCEPT_INSECTICIDE_TREATED_NET_USAGE),
patient, facility, itnUse, encounter, null);
encounter.addObs(itnUseObs);
}
if (fht != null) {
Obs fhtObs = createNumericValueObs(date, concept(ConceptEnum.CONCEPT_FUNDAL_HEIGHT),
patient, facility, fht, encounter, null);
encounter.addObs(fhtObs);
}
if (fhr != null) {
Obs fhrObs = createNumericValueObs(date,
concept(ConceptEnum.CONCEPT_FETAL_HEART_RATE), patient, facility, fhr,
encounter, null);
encounter.addObs(fhrObs);
}
if (urineTestProtein != null) {
Concept urineProteinTestValueConcept = null;
switch (urineTestProtein) {
case 0:
urineProteinTestValueConcept = concept(ConceptEnum.CONCEPT_NEGATIVE);
break;
case 1:
urineProteinTestValueConcept = concept(ConceptEnum.CONCEPT_POSITIVE);
break;
case 2:
urineProteinTestValueConcept = concept(ConceptEnum.CONCEPT_TRACE);
break;
}
if (urineProteinTestValueConcept != null) {
Obs urineTestProteinPositiveObs = createConceptValueObs(date,
concept(ConceptEnum.CONCEPT_URINE_PROTEIN_TEST), patient, facility,
urineProteinTestValueConcept, encounter, null);
encounter.addObs(urineTestProteinPositiveObs);
}
}
if (urineTestGlucose != null) {
Concept urineGlucoseTestValueConcept = null;
switch (urineTestGlucose) {
case 0:
urineGlucoseTestValueConcept = concept(ConceptEnum.CONCEPT_NEGATIVE);
break;
case 1:
urineGlucoseTestValueConcept = concept(ConceptEnum.CONCEPT_POSITIVE);
break;
case 2:
urineGlucoseTestValueConcept = concept(ConceptEnum.CONCEPT_TRACE);
break;
}
if (urineGlucoseTestValueConcept != null) {
Obs urineTestProteinPositiveObs = createConceptValueObs(date,
concept(ConceptEnum.CONCEPT_URINE_GLUCOSE_TEST), patient, facility,
urineGlucoseTestValueConcept, encounter, null);
encounter.addObs(urineTestProteinPositiveObs);
}
}
if (hemoglobin != null) {
Obs hemoglobinObs = createNumericValueObs(date,
concept(ConceptEnum.CONCEPT_HEMOGLOBIN), patient, facility, hemoglobin,
encounter, null);
encounter.addObs(hemoglobinObs);
}
if (vdrlReactive != null) {
Concept vdrlValueConcept;
if (Boolean.TRUE.equals(vdrlReactive)) {
vdrlValueConcept = concept(ConceptEnum.CONCEPT_REACTIVE);
} else {
vdrlValueConcept = concept(ConceptEnum.CONCEPT_NON_REACTIVE);
}
Obs vdrlReactiveObs = createConceptValueObs(date, concept(ConceptEnum.CONCEPT_VDRL),
patient, facility, vdrlValueConcept, encounter, null);
encounter.addObs(vdrlReactiveObs);
}
if (vdrlTreatment != null) {
Obs vdrlTreatmentObs = createBooleanValueObs(date,
concept(ConceptEnum.CONCEPT_VDRL_TREATMENT), patient, facility,
vdrlTreatment, encounter, null);
encounter.addObs(vdrlTreatmentObs);
}
if (dewormer != null) {
Obs dewormerObs = createBooleanValueObs(date, concept(ConceptEnum.CONCEPT_DEWORMER),
patient, facility, dewormer, encounter, null);
encounter.addObs(dewormerObs);
}
if (maleInvolved != null) {
Obs maleInvolvedObs = createBooleanValueObs(date,
concept(ConceptEnum.CONCEPT_MALE_INVOLVEMENT), patient, facility,
maleInvolved, encounter, null);
encounter.addObs(maleInvolvedObs);
}
if (pmtct != null) {
Obs pmtctObs = createBooleanValueObs(date, concept(ConceptEnum.CONCEPT_PMTCT),
patient, facility, pmtct, encounter, null);
encounter.addObs(pmtctObs);
}
if (preTestCounseled != null) {
Obs preTestCounseledObs = createBooleanValueObs(date,
concept(ConceptEnum.CONCEPT_HIV_PRE_TEST_COUNSELING), patient, facility,
preTestCounseled, encounter, null);
encounter.addObs(preTestCounseledObs);
}
if (hivTestResult != null) {
Obs hivResultObs = createTextValueObs(date,
concept(ConceptEnum.CONCEPT_HIV_TEST_RESULT), patient, facility, hivTestResult
.name(), encounter, null);
encounter.addObs(hivResultObs);
}
if (postTestCounseled != null) {
Obs postTestCounseledObs = createBooleanValueObs(date,
concept(ConceptEnum.CONCEPT_HIV_POST_TEST_COUNSELING), patient, facility,
postTestCounseled, encounter, null);
encounter.addObs(postTestCounseledObs);
}
if (pmtctTreatment != null) {
Obs pmtctTreatmentObs = createBooleanValueObs(date,
concept(ConceptEnum.CONCEPT_PMTCT_TREATMENT), patient, facility,
pmtctTreatment, encounter, null);
encounter.addObs(pmtctTreatmentObs);
}
if (referred != null) {
Obs referredObs = createBooleanValueObs(date, concept(ConceptEnum.CONCEPT_REFERRED),
patient, facility, referred, encounter, null);
encounter.addObs(referredObs);
}
if (nextANCDate != null) {
Obs nextANCDateObs = createDateValueObs(date,
concept(ConceptEnum.CONCEPT_NEXT_ANC_DATE), patient, facility, nextANCDate,
encounter, null);
encounter.addObs(nextANCDateObs);
}
if (comments != null) {
Obs commentsObs = createTextValueObs(date, concept(ConceptEnum.CONCEPT_COMMENTS),
patient, facility, comments, encounter, null);
encounter.addObs(commentsObs);
}
encounter = encounterService.saveEncounter(encounter);
if (estDeliveryDate != null) {
Obs pregnancyDueDateObs = getActivePregnancyDueDateObs(patient
.getPatientId(), pregnancyObs);
if (pregnancyDueDateObs != null) {
updatePregnancyDueDateObs(pregnancyObs, pregnancyDueDateObs,
estDeliveryDate, encounter);
} else {
log.warn("Cannot update pregnancy due date, "
+ "no active pregnancy due date found, patient id="
+ patient.getPatientId());
}
}
}
@Transactional
public void recordPregnancyTermination(User staff, Location facility,
Date date, Patient patient, Integer terminationType,
Integer procedure, Integer[] complications, Boolean maternalDeath,
Boolean referred, Boolean postAbortionFPCounseled,
Boolean postAbortionFPAccepted, String comments) {
Encounter encounter = new Encounter();
encounter.setEncounterType(getEncounterType(EncounterTypeEnum.ENCOUNTER_TYPE_PREGTERMVISIT));
encounter.setEncounterDatetime(date);
encounter.setPatient(patient);
encounter.setLocation(facility);
encounter.setProvider(staff);
Obs pregnancyObs = getActivePregnancy(patient.getPatientId());
if (pregnancyObs == null) {
log.warn("Entered Pregnancy termination "
+ "for patient without active pregnancy, patient id="
+ patient.getPatientId());
}
if (terminationType != null) {
Obs terminationTypeObs = createNumericValueObs(date,
concept(ConceptEnum.CONCEPT_TERMINATION_TYPE), patient, facility,
terminationType, encounter, null);
encounter.addObs(terminationTypeObs);
}
if (procedure != null) {
Obs procedureObs = createNumericValueObs(date,
concept(ConceptEnum.CONCEPT_TERMINATION_PROCEDURE), patient, facility,
procedure, encounter, null);
encounter.addObs(procedureObs);
}
if (complications != null) {
for (Integer complication : complications) {
Obs complicationObs = createNumericValueObs(date,
concept(ConceptEnum.CONCEPT_TERMINATION_COMPLICATION), patient, facility,
complication, encounter, null);
encounter.addObs(complicationObs);
}
}
if (maternalDeath != null) {
Obs maternalDeathObs = createBooleanValueObs(date,
concept(ConceptEnum.CONCEPT_MATERNAL_DEATH), patient, facility,
maternalDeath, encounter, null);
encounter.addObs(maternalDeathObs);
}
if (referred != null) {
Obs referredObs = createBooleanValueObs(date, concept(ConceptEnum.CONCEPT_REFERRED),
patient, facility, referred, encounter, null);
encounter.addObs(referredObs);
}
if (postAbortionFPCounseled != null) {
Obs postCounseledObs = createBooleanValueObs(date,
concept(ConceptEnum.CONCEPT_POST_ABORTION_FP_COUNSELING), patient, facility,
postAbortionFPCounseled, encounter, null);
encounter.addObs(postCounseledObs);
}
if (postAbortionFPAccepted != null) {
Obs postAcceptedObs = createBooleanValueObs(date,
concept(ConceptEnum.CONCEPT_POST_ABORTION_FP_ACCEPTED), patient, facility,
postAbortionFPAccepted, encounter, null);
encounter.addObs(postAcceptedObs);
}
if (comments != null) {
Obs commentsObs = createTextValueObs(date, concept(ConceptEnum.CONCEPT_COMMENTS),
patient, facility, comments, encounter, null);
encounter.addObs(commentsObs);
}
Obs pregnancyStatusObs = createBooleanValueObs(date,
concept(ConceptEnum.CONCEPT_PREGNANCY_STATUS), patient, facility, Boolean.FALSE,
encounter, null);
pregnancyStatusObs.setObsGroup(pregnancyObs);
encounter.addObs(pregnancyStatusObs);
encounterService.saveEncounter(encounter);
if (Boolean.TRUE.equals(maternalDeath)) {
processPatientDeath(patient, date);
}
}
@Transactional
public List<Patient> recordPregnancyDelivery(User staff, Facility facility,
Date datetime, Patient patient, Integer mode, Integer outcome,
Integer deliveryLocation, Integer deliveredBy,
Boolean maleInvolved, Integer[] complications, Integer vvf,
Boolean maternalDeath, String comments,
List<BirthOutcomeChild> outcomes) {
Encounter encounter = new Encounter();
Location location = facility.getLocation();
encounter.setEncounterType(getEncounterType(EncounterTypeEnum.ENCOUNTER_TYPE_PREGDELVISIT));
encounter.setEncounterDatetime(datetime);
encounter.setPatient(patient);
encounter.setLocation(location);
encounter.setProvider(staff);
Obs pregnancyObs = getActivePregnancy(patient.getPatientId());
if (pregnancyObs == null) {
log.warn("Entered Pregnancy delivery "
+ "for patient without active pregnancy, patient id="
+ patient.getPatientId());
}
if (mode != null) {
Obs modeObs = createNumericValueObs(datetime,
concept(ConceptEnum.CONCEPT_DELIVERY_MODE), patient, location, mode,
encounter, null);
encounter.addObs(modeObs);
}
if (outcome != null) {
Obs outcomeObs = createNumericValueObs(datetime,
concept(ConceptEnum.CONCEPT_DELIVERY_OUTCOME), patient, location, outcome,
encounter, null);
encounter.addObs(outcomeObs);
}
if (deliveryLocation != null) {
Obs locationObs = createNumericValueObs(datetime,
concept(ConceptEnum.CONCEPT_DELIVERY_LOCATION), patient, location,
deliveryLocation, encounter, null);
encounter.addObs(locationObs);
}
if (deliveredBy != null) {
Obs deliveredByObs = createNumericValueObs(datetime,
concept(ConceptEnum.CONCEPT_DELIVERED_BY), patient, location, deliveredBy,
encounter, null);
encounter.addObs(deliveredByObs);
}
if (maleInvolved != null) {
Obs maleInvolvedObs = createBooleanValueObs(datetime,
concept(ConceptEnum.CONCEPT_MALE_INVOLVEMENT), patient, location,
maleInvolved, encounter, null);
encounter.addObs(maleInvolvedObs);
}
if (complications != null) {
for (Integer complication : complications) {
Obs complicationObs = createNumericValueObs(datetime,
concept(ConceptEnum.CONCEPT_DELIVERY_COMPLICATION), patient, location,
complication, encounter, null);
encounter.addObs(complicationObs);
}
}
if (vvf != null) {
Obs vvfObs = createNumericValueObs(datetime, concept(ConceptEnum.CONCEPT_VVF_REPAIR),
patient, location, vvf, encounter, null);
encounter.addObs(vvfObs);
}
if (maternalDeath != null) {
Obs maternalDeathObs = createBooleanValueObs(datetime,
concept(ConceptEnum.CONCEPT_MATERNAL_DEATH), patient, location,
maternalDeath, encounter, null);
encounter.addObs(maternalDeathObs);
}
if (comments != null) {
Obs commentsObs = createTextValueObs(datetime,
concept(ConceptEnum.CONCEPT_COMMENTS), patient, location, comments,
encounter, null);
encounter.addObs(commentsObs);
}
Obs pregnancyStatusObs = createBooleanValueObs(datetime,
concept(ConceptEnum.CONCEPT_PREGNANCY_STATUS), patient, location, Boolean.FALSE,
encounter, null);
pregnancyStatusObs.setObsGroup(pregnancyObs);
encounter.addObs(pregnancyStatusObs);
List<Patient> childPatients = new ArrayList<Patient>();
for (BirthOutcomeChild childOutcome : outcomes) {
if (childOutcome.getOutcome() == null) {
// Skip child outcomes missing required outcome
continue;
}
Obs childOutcomeObs = createTextValueObs(datetime,
concept(ConceptEnum.CONCEPT_BIRTH_OUTCOME), patient, location, childOutcome
.getOutcome().name(), encounter, null);
encounter.addObs(childOutcomeObs);
if (BirthOutcome.A == childOutcome.getOutcome()) {
Patient child = registerPatient(staff, facility, datetime,
childOutcome.getIdMode(), childOutcome.getMotechId(),
RegistrantType.CHILD_UNDER_FIVE, childOutcome
.getFirstName(), null, null, null, datetime,
false, childOutcome.getSex(), null, null, null,
patient, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null);
if (childOutcome.getWeight() != null) {
recordBirthData(staff, location, child, datetime,
childOutcome.getWeight());
}
childPatients.add(child);
}
}
encounterService.saveEncounter(encounter);
if (Boolean.TRUE.equals(maternalDeath)) {
processPatientDeath(patient, datetime);
}
return childPatients;
}
private void recordBirthData(User staff, Location facility, Patient child,
Date datetime, Double weight) {
Encounter encounter = new Encounter();
encounter.setEncounterType(getEncounterType(EncounterTypeEnum.ENCOUNTER_TYPE_BIRTHVISIT));
encounter.setEncounterDatetime(datetime);
encounter.setPatient(child);
encounter.setLocation(facility);
encounter.setProvider(staff);
if (weight != null) {
Obs weightObs = createNumericValueObs(datetime, concept(ConceptEnum.CONCEPT_WEIGHT),
child, facility, weight, encounter, null);
encounter.addObs(weightObs);
}
encounterService.saveEncounter(encounter);
}
@Transactional
public void recordPregnancyDeliveryNotification(User staff,
Location facility, Date date, Patient patient) {
Encounter encounter = new Encounter();
encounter
.setEncounterType(getEncounterType(EncounterTypeEnum.ENCOUNTER_TYPE_PREGDELNOTIFYVISIT));
encounter.setEncounterDatetime(date);
encounter.setPatient(patient);
encounter.setLocation(facility);
encounter.setProvider(staff);
Obs pregnancyObs = getActivePregnancy(patient.getPatientId());
if (pregnancyObs == null) {
log
.warn("Entered Pregnancy delivery notification for patient without active pregnancy, "
+ "patient id=" + patient.getPatientId());
}
Obs pregnancyStatusObs = createBooleanValueObs(date,
concept(ConceptEnum.CONCEPT_PREGNANCY_STATUS), patient, facility, Boolean.FALSE,
encounter, null);
pregnancyStatusObs.setObsGroup(pregnancyObs);
encounter.addObs(pregnancyStatusObs);
encounterService.saveEncounter(encounter);
// Send message only if closing active pregnancy
if (pregnancyObs != null) {
sendDeliveryNotification(patient);
}
}
private void sendDeliveryNotification(Patient patient) {
// Send message to phone number of facility serving patient's community
Facility facility = getFacilityByPatient(patient);
if (isNotNull(facility)) {
String phoneNumber = facility.getPhoneNumber();
if (phoneNumber != null) {
MessageDefinition messageDef = getMessageDefinition("pregnancy.notification");
if (messageDef == null) {
log.error("Pregnancy delivery notification message "
+ "does not exist");
return;
}
String messageId = null;
NameValuePair[] nameValues = new NameValuePair[0];
MediaType mediaType = MediaType.TEXT;
String languageCode = "en";
// Send immediately if not during blackout,
// otherwise adjust time to after the blackout period
Date currentDate = new Date();
Date messageStartDate = adjustDateForBlackout(currentDate);
if (currentDate.equals(messageStartDate)) {
messageStartDate = null;
}
WebServiceModelConverterImpl wsModelConverter = new WebServiceModelConverterImpl();
wsModelConverter.setRegistrarBean(this);
org.motechproject.ws.Patient wsPatient = wsModelConverter
.patientToWebService(patient, true);
org.motechproject.ws.Patient[] wsPatients = new org.motechproject.ws.Patient[]{wsPatient};
sendStaffMessage(messageId, nameValues, phoneNumber,
languageCode, mediaType, messageDef.getPublicId(),
messageStartDate, null, wsPatients);
}
}
}
@Transactional
public void recordMotherPNCVisit(User staff, Location facility,
Date datetime, Patient patient, Integer visitNumber,
Integer pncLocation, String house, String community,
Boolean referred, Boolean maleInvolved, Boolean vitaminA,
Integer ttDose, Integer lochiaColour, Boolean lochiaAmountExcess,
Boolean lochiaOdourFoul, Double temperature, Double fht,
String comments) {
Encounter encounter = new Encounter();
encounter.setEncounterType(getEncounterType(EncounterTypeEnum.ENCOUNTER_TYPE_PNCMOTHERVISIT));
encounter.setEncounterDatetime(datetime);
encounter.setPatient(patient);
encounter.setLocation(facility);
encounter.setProvider(staff);
if (visitNumber != null) {
Obs visitNumberObs = createNumericValueObs(datetime,
concept(ConceptEnum.CONCEPT_VISIT_NUMBER), patient, facility, visitNumber,
encounter, null);
encounter.addObs(visitNumberObs);
}
if (pncLocation != null) {
Obs pncLocationObs = createNumericValueObs(datetime,
concept(ConceptEnum.CONCEPT_ANC_PNC_LOCATION), patient, facility, pncLocation,
encounter, null);
encounter.addObs(pncLocationObs);
}
if (house != null) {
Obs houseObs = createTextValueObs(datetime, concept(ConceptEnum.CONCEPT_HOUSE),
patient, facility, house, encounter, null);
encounter.addObs(houseObs);
}
if (community != null) {
Obs communityObs = createTextValueObs(datetime,
concept(ConceptEnum.CONCEPT_COMMUNITY), patient, facility, community,
encounter, null);
encounter.addObs(communityObs);
}
if (referred != null) {
Obs referredObs = createBooleanValueObs(datetime,
concept(ConceptEnum.CONCEPT_REFERRED), patient, facility, referred,
encounter, null);
encounter.addObs(referredObs);
}
if (maleInvolved != null) {
Obs maleInvolvedObs = createBooleanValueObs(datetime,
concept(ConceptEnum.CONCEPT_MALE_INVOLVEMENT), patient, facility,
maleInvolved, encounter, null);
encounter.addObs(maleInvolvedObs);
}
if (Boolean.TRUE.equals(vitaminA)) {
Obs vitaminAObs = createConceptValueObs(datetime,
concept(ConceptEnum.CONCEPT_IMMUNIZATIONS_ORDERED), patient, facility,
concept(ConceptEnum.CONCEPT_VITAMIN_A), encounter, null);
encounter.addObs(vitaminAObs);
}
if (ttDose != null) {
Obs ttDoseObs = createNumericValueObs(datetime,
concept(ConceptEnum.CONCEPT_TETANUS_TOXOID_DOSE), patient, facility, ttDose,
encounter, null);
encounter.addObs(ttDoseObs);
}
if (lochiaColour != null) {
Obs lochiaColourObs = createNumericValueObs(datetime,
concept(ConceptEnum.CONCEPT_LOCHIA_COLOUR), patient, facility, lochiaColour,
encounter, null);
encounter.addObs(lochiaColourObs);
}
if (lochiaOdourFoul != null) {
Obs lochiaOdourObs = createBooleanValueObs(datetime,
concept(ConceptEnum.CONCEPT_LOCHIA_FOUL_ODOUR), patient, facility, lochiaOdourFoul,
encounter, null);
encounter.addObs(lochiaOdourObs);
}
if (lochiaAmountExcess != null) {
Obs lochiaAmountObs = createBooleanValueObs(datetime,
concept(ConceptEnum.CONCEPT_LOCHIA_EXCESS_AMOUNT), patient, facility,
lochiaAmountExcess, encounter, null);
encounter.addObs(lochiaAmountObs);
}
if (temperature != null) {
Obs temperatureObs = createNumericValueObs(datetime,
concept(ConceptEnum.CONCEPT_TEMPERATURE), patient, facility, temperature,
encounter, null);
encounter.addObs(temperatureObs);
}
if (fht != null) {
Obs fhtObs = createNumericValueObs(datetime,
concept(ConceptEnum.CONCEPT_FUNDAL_HEIGHT), patient, facility, fht,
encounter, null);
encounter.addObs(fhtObs);
}
if (comments != null) {
Obs commentsObs = createTextValueObs(datetime,
concept(ConceptEnum.CONCEPT_COMMENTS), patient, facility, comments,
encounter, null);
encounter.addObs(commentsObs);
}
encounterService.saveEncounter(encounter);
}
@Transactional
public void recordChildPNCVisit(User staff, Location facility,
Date datetime, Patient patient, Integer visitNumber,
Integer pncLocation, String house, String community,
Boolean referred, Boolean maleInvolved, Double weight,
Double temperature, Boolean bcg, Boolean opv0, Integer respiration,
Boolean cordConditionNormal, Boolean babyConditionGood,
String comments) {
Encounter encounter = new Encounter();
encounter.setEncounterType(getEncounterType(EncounterTypeEnum.ENCOUNTER_TYPE_PNCCHILDVISIT));
encounter.setEncounterDatetime(datetime);
encounter.setPatient(patient);
encounter.setLocation(facility);
encounter.setProvider(staff);
if (visitNumber != null) {
Obs visitNumberObs = createNumericValueObs(datetime,
concept(ConceptEnum.CONCEPT_VISIT_NUMBER), patient, facility, visitNumber,
encounter, null);
encounter.addObs(visitNumberObs);
}
if (pncLocation != null) {
Obs pncLocationObs = createNumericValueObs(datetime,
concept(ConceptEnum.CONCEPT_ANC_PNC_LOCATION), patient, facility, pncLocation,
encounter, null);
encounter.addObs(pncLocationObs);
}
if (house != null) {
Obs houseObs = createTextValueObs(datetime, concept(ConceptEnum.CONCEPT_HOUSE),
patient, facility, house, encounter, null);
encounter.addObs(houseObs);
}
if (community != null) {
Obs communityObs = createTextValueObs(datetime,
concept(ConceptEnum.CONCEPT_COMMUNITY), patient, facility, community,
encounter, null);
encounter.addObs(communityObs);
}
if (referred != null) {
Obs referredObs = createBooleanValueObs(datetime,
concept(ConceptEnum.CONCEPT_REFERRED), patient, facility, referred,
encounter, null);
encounter.addObs(referredObs);
}
if (maleInvolved != null) {
Obs maleInvolvedObs = createBooleanValueObs(datetime,
concept(ConceptEnum.CONCEPT_MALE_INVOLVEMENT), patient, facility,
maleInvolved, encounter, null);
encounter.addObs(maleInvolvedObs);
}
if (weight != null) {
Obs weightObs = createNumericValueObs(datetime, concept(ConceptEnum.CONCEPT_WEIGHT),
patient, facility, weight, encounter, null);
encounter.addObs(weightObs);
}
if (temperature != null) {
Obs temperatureObs = createNumericValueObs(datetime,
concept(ConceptEnum.CONCEPT_TEMPERATURE), patient, facility, temperature,
encounter, null);
encounter.addObs(temperatureObs);
}
if (Boolean.TRUE.equals(bcg)) {
Obs bcgObs = createConceptValueObs(datetime,
concept(ConceptEnum.CONCEPT_IMMUNIZATIONS_ORDERED), patient, facility,
concept(ConceptEnum.CONCEPT_BCG_VACCINATION), encounter, null);
encounter.addObs(bcgObs);
}
if (Boolean.TRUE.equals(opv0)) {
Integer opvDose = 0;
Obs opvDoseObs = createNumericValueObs(datetime,
concept(ConceptEnum.CONCEPT_ORAL_POLIO_VACCINATION_DOSE),
patient, facility, opvDose, encounter,
null);
encounter.addObs(opvDoseObs);
}
if (respiration != null) {
Obs respirationObs = createNumericValueObs(datetime,
concept(ConceptEnum.CONCEPT_RESPIRATORY_RATE), patient, facility,
respiration, encounter, null);
encounter.addObs(respirationObs);
}
if (cordConditionNormal != null) {
Obs cordConditionObs = createBooleanValueObs(datetime,
concept(ConceptEnum.CONCEPT_CORD_CONDITION), patient, facility,
cordConditionNormal, encounter, null);
encounter.addObs(cordConditionObs);
}
if (babyConditionGood != null) {
Obs babyConditionObs = createBooleanValueObs(datetime,
concept(ConceptEnum.CONCEPT_CONDITION_OF_BABY), patient, facility,
babyConditionGood, encounter, null);
encounter.addObs(babyConditionObs);
}
if (comments != null) {
Obs commentsObs = createTextValueObs(datetime,
concept(ConceptEnum.CONCEPT_COMMENTS), patient, facility, comments,
encounter, null);
encounter.addObs(commentsObs);
}
encounterService.saveEncounter(encounter);
}
@Transactional
public void recordTTVisit(User staff, Location facility, Date date,
Patient patient, Integer ttDose) {
Encounter encounter = new Encounter();
encounter.setEncounterType(getEncounterType(EncounterTypeEnum.ENCOUNTER_TYPE_TTVISIT));
encounter.setEncounterDatetime(date);
encounter.setPatient(patient);
encounter.setLocation(facility);
encounter.setProvider(staff);
if (ttDose != null) {
Obs ttDoseObs = createNumericValueObs(date,
concept(ConceptEnum.CONCEPT_TETANUS_TOXOID_DOSE), patient, facility, ttDose,
encounter, null);
encounter.addObs(ttDoseObs);
}
encounterService.saveEncounter(encounter);
}
@Transactional
public void recordDeath(User staff, Location facility, Date date,
Patient patient) {
processPatientDeath(patient, date);
}
private void processPatientDeath(Patient patient, Date date) {
// Stop all messages and remove all message program enrollments
removeAllMessageProgramEnrollments(patient.getPatientId());
patient.setDead(true);
patient.setDeathDate(date);
patient = patientService.savePatient(patient);
personService.voidPerson(patient, "Deceased");
}
@Transactional
public void recordChildCWCVisit(User staff, Location facility, Date date,
Patient patient, Integer cwcLocation, String house,
String community, Boolean bcg, Integer opvDose, Integer pentaDose,
Boolean measles, Boolean yellowFever, Boolean csm,
Integer iptiDose, Boolean vitaminA, Boolean dewormer,
Double weight, Double muac, Double height, Boolean maleInvolved,
String comments) {
Encounter encounter = new Encounter();
encounter.setEncounterType(getEncounterType(EncounterTypeEnum.ENCOUNTER_TYPE_CWCVISIT));
encounter.setEncounterDatetime(date);
encounter.setPatient(patient);
encounter.setLocation(facility);
encounter.setProvider(staff);
if (cwcLocation != null) {
Obs cwcLocationObs = createNumericValueObs(date,
concept(ConceptEnum.CONCEPT_CWC_LOCATION), patient, facility, cwcLocation,
encounter, null);
encounter.addObs(cwcLocationObs);
}
if (house != null) {
Obs houseObs = createTextValueObs(date, concept(ConceptEnum.CONCEPT_HOUSE), patient,
facility, house, encounter, null);
encounter.addObs(houseObs);
}
if (community != null) {
Obs communityObs = createTextValueObs(date, concept(ConceptEnum.CONCEPT_COMMUNITY),
patient, facility, community, encounter, null);
encounter.addObs(communityObs);
}
if (Boolean.TRUE.equals(bcg)) {
Obs bcgObs = createConceptValueObs(date,
concept(ConceptEnum.CONCEPT_IMMUNIZATIONS_ORDERED), patient, facility,
concept(ConceptEnum.CONCEPT_BCG_VACCINATION), encounter, null);
encounter.addObs(bcgObs);
}
if (opvDose != null) {
Obs opvDoseObs = createNumericValueObs(date, concept(ConceptEnum.CONCEPT_ORAL_POLIO_VACCINATION_DOSE),
patient, facility, opvDose, encounter, null);
encounter.addObs(opvDoseObs);
}
if (pentaDose != null) {
Obs pentaDoseObs = createNumericValueObs(date,
concept(ConceptEnum.CONCEPT_PENTA_VACCINATION_DOSE), patient, facility, pentaDose,
encounter, null);
encounter.addObs(pentaDoseObs);
}
if (Boolean.TRUE.equals(yellowFever)) {
Obs yellowFeverObs = createConceptValueObs(date,
concept(ConceptEnum.CONCEPT_IMMUNIZATIONS_ORDERED), patient, facility,
concept(ConceptEnum.CONCEPT_YELLOW_FEVER_VACCINATION), encounter, null);
encounter.addObs(yellowFeverObs);
}
if (Boolean.TRUE.equals(csm)) {
Obs csmObs = createConceptValueObs(date,
concept(ConceptEnum.CONCEPT_IMMUNIZATIONS_ORDERED), patient, facility,
concept(ConceptEnum.CONCEPT_CEREBRO_SPINAL_MENINGITIS_VACCINATION),
encounter, null);
encounter.addObs(csmObs);
}
if (Boolean.TRUE.equals(measles)) {
Obs measlesObs = createConceptValueObs(date,
concept(ConceptEnum.CONCEPT_IMMUNIZATIONS_ORDERED), patient, facility,
concept(ConceptEnum.CONCEPT_MEASLES_VACCINATION), encounter, null);
encounter.addObs(measlesObs);
}
if (iptiDose != null) {
Obs iptiObs = createNumericValueObs(date,
concept(ConceptEnum.CONCEPT_INTERMITTENT_PREVENTATIVE_TREATMENT_INFANTS_DOSE),
patient, facility, iptiDose, encounter, null);
encounter.addObs(iptiObs);
}
if (Boolean.TRUE.equals(vitaminA)) {
Obs vitaminAObs = createConceptValueObs(date,
concept(ConceptEnum.CONCEPT_IMMUNIZATIONS_ORDERED), patient, facility,
concept(ConceptEnum.CONCEPT_VITAMIN_A), encounter, null);
encounter.addObs(vitaminAObs);
}
if (dewormer != null) {
Obs dewormerObs = createBooleanValueObs(date, concept(ConceptEnum.CONCEPT_DEWORMER),
patient, facility, dewormer, encounter, null);
encounter.addObs(dewormerObs);
}
if (weight != null) {
Obs weightObs = createNumericValueObs(date, concept(ConceptEnum.CONCEPT_WEIGHT),
patient, facility, weight, encounter, null);
encounter.addObs(weightObs);
}
if (muac != null) {
Obs muacObs = createNumericValueObs(date, concept(ConceptEnum.CONCEPT_MIDDLE_UPPER_ARM_CIRCUMFERENCE),
patient, facility, muac, encounter, null);
encounter.addObs(muacObs);
}
if (height != null) {
Obs heightObs = createNumericValueObs(date, concept(ConceptEnum.CONCEPT_HEIGHT),
patient, facility, height, encounter, null);
encounter.addObs(heightObs);
}
if (maleInvolved != null) {
Obs maleInvolvedObs = createBooleanValueObs(date,
concept(ConceptEnum.CONCEPT_MALE_INVOLVEMENT), patient, facility,
maleInvolved, encounter, null);
encounter.addObs(maleInvolvedObs);
}
if (comments != null) {
Obs commentsObs = createTextValueObs(date, concept(ConceptEnum.CONCEPT_COMMENTS),
patient, facility, comments, encounter, null);
encounter.addObs(commentsObs);
}
encounterService.saveEncounter(encounter);
}
@Transactional
public void recordGeneralOutpatientVisit(Integer staffId,
Integer facilityId, Date date, String serialNumber, Gender sex,
Date dateOfBirth, Boolean insured, Integer diagnosis,
Integer secondDiagnosis, Boolean rdtGiven, Boolean rdtPositive,
Boolean actTreated, Boolean newCase, Boolean newPatient, Boolean referred,
String comments) {
GeneralOutpatientEncounter encounter = new GeneralOutpatientEncounter(
date, staffId, facilityId, serialNumber, sex, dateOfBirth,
insured, newCase, newPatient, diagnosis, secondDiagnosis, referred,
rdtGiven, rdtPositive, actTreated, comments);
if (log.isDebugEnabled()) {
log.debug(encounter.toString());
}
motechService().saveGeneralOutpatientEncounter(encounter);
}
@Transactional
public void recordOutpatientVisit(User staff, Location facility, Date date,
Patient patient, String serialNumber, Boolean insured,
Integer diagnosis, Integer secondDiagnosis, Boolean rdtGiven,
Boolean rdtPositive, Boolean actTreated, Boolean newCase,
Boolean newPatient, Boolean referred, String comments) {
Encounter encounter = new Encounter();
encounter.setEncounterType(getEncounterType(EncounterTypeEnum.ENCOUNTER_TYPE_OUTPATIENTVISIT));
encounter.setEncounterDatetime(date);
encounter.setPatient(patient);
encounter.setLocation(facility);
encounter.setProvider(staff);
if (serialNumber != null) {
Obs serialNumberObs = createTextValueObs(date,
concept(ConceptEnum.CONCEPT_SERIAL_NUMBER), patient, facility, serialNumber,
encounter, null);
encounter.addObs(serialNumberObs);
}
if (insured != null) {
Obs insuredObs = createBooleanValueObs(date, concept(ConceptEnum.CONCEPT_INSURED),
patient, facility, insured, encounter, null);
encounter.addObs(insuredObs);
}
if (newCase != null) {
Obs newCaseObs = createBooleanValueObs(date, concept(ConceptEnum.CONCEPT_NEW_CASE),
patient, facility, newCase, encounter, null);
encounter.addObs(newCaseObs);
}
if (newPatient != null) {
Obs newPatientObs = createBooleanValueObs(date, concept(ConceptEnum.PATIENT_NEW_CASE),
patient, facility, newPatient, encounter, null);
encounter.addObs(newPatientObs);
}
if (diagnosis != null) {
Obs diagnosisObs = createNumericValueObs(date,
concept(ConceptEnum.CONCEPT_PRIMARY_DIAGNOSIS), patient, facility, diagnosis,
encounter, null);
encounter.addObs(diagnosisObs);
}
if (secondDiagnosis != null) {
Obs secondDiagnosisObs = createNumericValueObs(date,
concept(ConceptEnum.CONCEPT_SECONDARY_DIAGNOSIS), patient, facility,
secondDiagnosis, encounter, null);
encounter.addObs(secondDiagnosisObs);
}
if (referred != null) {
Obs referredObs = createBooleanValueObs(date, concept(ConceptEnum.CONCEPT_REFERRED),
patient, facility, referred, encounter, null);
encounter.addObs(referredObs);
}
if (Boolean.TRUE.equals(rdtGiven)) {
Concept rdtTestValueConcept;
if (Boolean.TRUE.equals(rdtPositive)) {
rdtTestValueConcept = concept(ConceptEnum.CONCEPT_POSITIVE);
} else {
rdtTestValueConcept = concept(ConceptEnum.CONCEPT_NEGATIVE);
}
Obs rdtTestObs = createConceptValueObs(date,
concept(ConceptEnum.CONCEPT_MALARIA_RAPID_TEST), patient, facility,
rdtTestValueConcept, encounter, null);
encounter.addObs(rdtTestObs);
}
if (actTreated != null) {
Obs actTreatedObs = createBooleanValueObs(date,
concept(ConceptEnum.CONCEPT_ACT_TREATMENT), patient, facility, actTreated,
encounter, null);
encounter.addObs(actTreatedObs);
}
if (comments != null) {
Obs commentsObs = createTextValueObs(date, concept(ConceptEnum.CONCEPT_COMMENTS),
patient, facility, comments, encounter, null);
encounter.addObs(commentsObs);
}
encounterService.saveEncounter(encounter);
}
@Transactional
public void setMessageStatus(String messageId, Boolean success) {
log.debug("setMessageStatus WS: messageId: " + messageId
+ ", success: " + success);
Message message = motechService().getMessage(messageId);
if (message == null) {
throw new MessageNotFoundException();
}
if (success) {
message.setAttemptStatus(MessageStatus.DELIVERED);
} else {
message.setAttemptStatus(MessageStatus.ATTEMPT_FAIL);
}
motechService().saveMessage(message);
}
public User getUserByPhoneNumber(String phoneNumber) {
PersonAttributeType phoneAttributeType = PersonAttributeTypeEnum.PERSON_ATTRIBUTE_PHONE_NUMBER.getAttributeType(personService);
List<Integer> matchingUsers = motechService()
.getUserIdsByPersonAttribute(phoneAttributeType, phoneNumber);
if (matchingUsers.size() > 0) {
if (matchingUsers.size() > 1) {
log.warn("Multiple staff found for phone number: "
+ phoneNumber);
}
// If more than one user matches phone number, first user in list is
// returned
Integer userId = matchingUsers.get(0);
return userService.getUser(userId);
}
log.warn("No staff found for phone number: " + phoneNumber);
return null;
}
/* MotechService methods end */
/* Controller methods start */
public List<Location> getAllLocations() {
return locationService.getAllLocations();
}
public List<User> getAllStaff() {
return userService.getAllUsers();
}
public List<Patient> getAllPatients() {
List<PatientIdentifierType> motechPatientIdType = new ArrayList<PatientIdentifierType>();
motechPatientIdType.add(getPatientIdentifierTypeForMotechId());
return patientService.getPatients(null, null, motechPatientIdType,
false);
}
public List<Patient> getPatients(String firstName, String lastName,
String preferredName, Date birthDate, Integer facilityId,
String phoneNumber, String nhisNumber, String motechId) {
PersonAttributeType phoneNumberAttrType = PersonAttributeTypeEnum.PERSON_ATTRIBUTE_PHONE_NUMBER.getAttributeType(personService);
PersonAttributeType nhisAttrType = PersonAttributeTypeEnum.PERSON_ATTRIBUTE_NHIS_NUMBER.getAttributeType(personService);
PatientIdentifierType motechIdType = getPatientIdentifierTypeForMotechId();
Integer maxResults = getMaxQueryResults();
return motechService().getPatients(firstName, lastName, preferredName,
birthDate, facilityId, phoneNumber, phoneNumberAttrType,
nhisNumber, nhisAttrType, motechId, motechIdType, maxResults);
}
public List<Patient> getDuplicatePatients(String firstName,
String lastName, String preferredName, Date birthDate,
Integer facilityId, String phoneNumber, String nhisNumber,
String motechId) {
PersonAttributeType phoneNumberAttrType = PersonAttributeTypeEnum.PERSON_ATTRIBUTE_PHONE_NUMBER.getAttributeType(personService);
PersonAttributeType nhisAttrType = PersonAttributeTypeEnum.PERSON_ATTRIBUTE_NHIS_NUMBER.getAttributeType(personService);
PatientIdentifierType motechIdType = getPatientIdentifierTypeForMotechId();
Integer maxResults = getMaxQueryResults();
return motechService().getDuplicatePatients(firstName, lastName,
preferredName, birthDate, facilityId, phoneNumber,
phoneNumberAttrType, nhisNumber, nhisAttrType, motechId,
motechIdType, maxResults);
}
public List<Obs> getAllPregnancies() {
List<Concept> pregnancyConcept = new ArrayList<Concept>();
pregnancyConcept.add(concept(ConceptEnum.CONCEPT_PREGNANCY));
return obsService.getObservations(null, null, pregnancyConcept, null,
null, null, null, null, null, null, null, false);
}
public List<ExpectedEncounter> getUpcomingExpectedEncounters(Patient patient) {
Calendar calendar = Calendar.getInstance();
Date currentDate = calendar.getTime();
calendar.add(Calendar.DATE, 7);
Date oneWeekLaterDate = calendar.getTime();
Integer maxResults = getMaxQueryResults();
return motechService().getExpectedEncounter(patient, null, null, null,
oneWeekLaterDate, null, currentDate, maxResults);
}
public List<ExpectedObs> getUpcomingExpectedObs(Patient patient) {
Calendar calendar = Calendar.getInstance();
Date currentDate = calendar.getTime();
calendar.add(Calendar.DATE, 7);
Date oneWeekLaterDate = calendar.getTime();
Integer maxResults = getMaxQueryResults();
return motechService().getExpectedObs(patient, null, null, null,
oneWeekLaterDate, null, currentDate, maxResults);
}
public List<ExpectedEncounter> getDefaultedExpectedEncounters(
Facility facility, String[] groups) {
Date currentDate = new Date();
Integer maxResults = getMaxQueryResults();
return motechService().getExpectedEncounter(null, facility, groups, null,
null, currentDate, currentDate, maxResults);
}
public List<ExpectedObs> getDefaultedExpectedObs(Facility facility,
String[] groups) {
Date currentDate = new Date();
Integer maxResults = getMaxQueryResults();
return motechService().getExpectedObs(null, facility, groups, null, null,
currentDate, currentDate, maxResults);
}
private List<ExpectedEncounter> getUpcomingExpectedEncounters(
Facility facility, String[] groups, Date fromDate, Date toDate) {
Integer maxResults = getMaxQueryResults();
return motechService().getExpectedEncounter(null, facility, groups, null,
toDate, null, fromDate, maxResults);
}
private List<ExpectedObs> getUpcomingExpectedObs(Facility facility,
String[] groups, Date fromDate, Date toDate) {
Integer maxResults = getMaxQueryResults();
return motechService().getExpectedObs(null, facility, groups, null,
toDate, null, fromDate, maxResults);
}
private List<ExpectedEncounter> getDefaultedExpectedEncounters(
Facility facility, String[] groups, Date forDate) {
Integer maxResults = getMaxQueryResults();
return motechService().getExpectedEncounter(null, facility, groups, null,
null, forDate, forDate, maxResults);
}
private List<ExpectedObs> getDefaultedExpectedObs(Facility facility,
String[] groups, Date forDate) {
Integer maxResults = getMaxQueryResults();
return motechService().getExpectedObs(null, facility, groups, null, null,
forDate, forDate, maxResults);
}
public List<ExpectedEncounter> getExpectedEncounters(Patient patient) {
Date currentDate = new Date();
return motechService().getExpectedEncounter(patient, null, null, null,
null, null, currentDate, null);
}
public List<ExpectedObs> getExpectedObs(Patient patient) {
Date currentDate = new Date();
return motechService().getExpectedObs(patient, null, null, null, null,
null, currentDate, null);
}
public List<ExpectedEncounter> getExpectedEncounters(Patient patient,
String group) {
return motechService().getExpectedEncounter(patient, null,
new String[]{group}, null, null, null, null, null);
}
public List<ExpectedObs> getExpectedObs(Patient patient, String group) {
return motechService().getExpectedObs(patient, null,
new String[]{group}, null, null, null, null, null);
}
public List<Encounter> getRecentDeliveries(Facility facility) {
EncounterType deliveryEncounterType = getEncounterType(EncounterTypeEnum.ENCOUNTER_TYPE_PREGDELVISIT);
Calendar calendar = Calendar.getInstance();
Date currentDate = calendar.getTime();
calendar.add(Calendar.DATE, 2 * -7);
Date twoWeeksPriorDate = calendar.getTime();
Integer maxResults = getMaxQueryResults();
return motechService().getEncounters(facility, deliveryEncounterType,
twoWeeksPriorDate, currentDate, maxResults);
}
public Date getCurrentDeliveryDate(Patient patient) {
List<EncounterType> deliveryEncounterType = new ArrayList<EncounterType>();
deliveryEncounterType.add(getEncounterType(EncounterTypeEnum.ENCOUNTER_TYPE_PREGDELVISIT));
List<Encounter> deliveries = encounterService.getEncounters(patient,
null, null, null, null, deliveryEncounterType, null, false);
if (!deliveries.isEmpty()) {
// List is ascending by date, get last match to get most recent
return deliveries.get(deliveries.size() - 1).getEncounterDatetime();
}
return null;
}
public List<Obs> getUpcomingPregnanciesDueDate(Facility facility) {
Calendar calendar = Calendar.getInstance();
Date currentDate = calendar.getTime();
calendar.add(Calendar.DATE, 2 * 7);
Date twoWeeksLaterDate = calendar.getTime();
return getActivePregnanciesDueDateObs(facility, currentDate,
twoWeeksLaterDate);
}
public List<Obs> getOverduePregnanciesDueDate(Facility facility) {
Date currentDate = new Date();
return getActivePregnanciesDueDateObs(facility, null, currentDate);
}
private List<Obs> getActivePregnanciesDueDateObs(Facility facility,
Date fromDueDate, Date toDueDate) {
Concept pregnancyDueDateConcept = concept(ConceptEnum.CONCEPT_ESTIMATED_DATE_OF_CONFINEMENT);
Concept pregnancyConcept = concept(ConceptEnum.CONCEPT_PREGNANCY);
Concept pregnancyStatusConcept = concept(ConceptEnum.CONCEPT_PREGNANCY_STATUS);
Integer maxResults = getMaxQueryResults();
return motechService().getActivePregnanciesDueDateObs(facility,
fromDueDate, toDueDate, pregnancyDueDateConcept,
pregnancyConcept, pregnancyStatusConcept, maxResults);
}
private Integer updatePregnancyDueDateObs(Obs pregnancyObs, Obs dueDateObs,
Date newDueDate, Encounter encounter) {
Integer existingDueDateObsId = dueDateObs.getObsId();
Obs newDueDateObs = createDateValueObs(
encounter.getEncounterDatetime(),
concept(ConceptEnum.CONCEPT_ESTIMATED_DATE_OF_CONFINEMENT),
encounter.getPatient(), encounter.getLocation(), newDueDate,
encounter, null);
newDueDateObs.setObsGroup(pregnancyObs);
newDueDateObs = obsService.saveObs(newDueDateObs, null);
obsService.voidObs(dueDateObs, "Replaced by new EDD value Obs: "
+ newDueDateObs.getObsId());
// Update enrollments using duedate Obs to reference new duedate Obs
List<MessageProgramEnrollment> enrollments = motechService()
.getActiveMessageProgramEnrollments(null, null,
existingDueDateObsId, null, null);
for (MessageProgramEnrollment enrollment : enrollments) {
enrollment.setObsId(newDueDateObs.getObsId());
motechService().saveMessageProgramEnrollment(enrollment);
}
return newDueDateObs.getObsId();
}
public Patient getPatientById(Integer patientId) {
return patientService.getPatient(patientId);
}
public Obs getActivePregnancy(Integer patientId) {
List<Obs> pregnancies = motechService().getActivePregnancies(patientId,
concept(ConceptEnum.CONCEPT_PREGNANCY), concept(ConceptEnum.CONCEPT_PREGNANCY_STATUS));
if (pregnancies.isEmpty()) {
return null;
} else if (pregnancies.size() > 1) {
log.warn("More than 1 active pregnancy found for patient: "
+ patientId);
}
return pregnancies.get(0);
}
public List<ScheduledMessage> getAllScheduledMessages() {
return motechService().getAllScheduledMessages();
}
public List<ScheduledMessage> getScheduledMessages(
MessageProgramEnrollment enrollment) {
return motechService().getScheduledMessages(null, null, enrollment, null);
}
/* Controller methods end */
public List<Obs> getObs(Patient patient, String conceptName,
String valueConceptName, Date minDate) {
Concept concept = conceptService.getConcept(conceptName);
Concept value = conceptService.getConcept(valueConceptName);
List<Concept> questions = new ArrayList<Concept>();
questions.add(concept);
List<Concept> answers = null;
if (value != null) {
answers = new ArrayList<Concept>();
answers.add(value);
}
List<Person> whom = new ArrayList<Person>();
whom.add(patient);
return obsService.getObservations(whom, null, questions, answers, null,
null, null, null, null, minDate, null, false);
}
public ExpectedObs createExpectedObs(Patient patient, String conceptName,
String valueConceptName, Integer value, Date minDate, Date dueDate,
Date lateDate, Date maxDate, String name, String group) {
Concept concept = conceptService.getConcept(conceptName);
Concept valueConcept = conceptService.getConcept(valueConceptName);
ExpectedObs expectedObs = new ExpectedObs();
expectedObs.setPatient(patient);
expectedObs.setConcept(concept);
expectedObs.setValueCoded(valueConcept);
if (value != null) {
expectedObs.setValueNumeric((double) value);
}
expectedObs.setMinObsDatetime(minDate);
expectedObs.setDueObsDatetime(dueDate);
expectedObs.setLateObsDatetime(lateDate);
expectedObs.setMaxObsDatetime(maxDate);
expectedObs.setName(name);
expectedObs.setGroup(group);
return saveExpectedObs(expectedObs);
}
public ExpectedObs saveExpectedObs(ExpectedObs expectedObs) {
if (log.isDebugEnabled()) {
log.debug("Saving schedule update: " + expectedObs.toString());
}
if (expectedObs.getDueObsDatetime() != null
&& expectedObs.getLateObsDatetime() != null) {
return motechService().saveExpectedObs(expectedObs);
} else {
log
.error("Attempt to store ExpectedObs with null due or late date");
return null;
}
}
public List<Encounter> getEncounters(Patient patient,
String encounterTypeName, Date minDate) {
EncounterType encounterType = encounterService
.getEncounterType(encounterTypeName);
List<EncounterType> encounterTypes = new ArrayList<EncounterType>();
encounterTypes.add(encounterType);
return encounterService.getEncounters(patient, null, minDate, null,
null, encounterTypes, null, false);
}
public ExpectedEncounter createExpectedEncounter(Patient patient,
String encounterTypeName, Date minDate, Date dueDate,
Date lateDate, Date maxDate, String name, String group) {
EncounterType encounterType = encounterService
.getEncounterType(encounterTypeName);
ExpectedEncounter expectedEncounter = new ExpectedEncounter();
expectedEncounter.setPatient(patient);
expectedEncounter.setEncounterType(encounterType);
expectedEncounter.setMinEncounterDatetime(minDate);
expectedEncounter.setDueEncounterDatetime(dueDate);
expectedEncounter.setLateEncounterDatetime(lateDate);
expectedEncounter.setMaxEncounterDatetime(maxDate);
expectedEncounter.setName(name);
expectedEncounter.setGroup(group);
return saveExpectedEncounter(expectedEncounter);
}
public ExpectedEncounter saveExpectedEncounter(
ExpectedEncounter expectedEncounter) {
if (log.isDebugEnabled()) {
log
.debug("Saving schedule update: "
+ expectedEncounter.toString());
}
if (expectedEncounter.getDueEncounterDatetime() != null
&& expectedEncounter.getLateEncounterDatetime() != null) {
return motechService().saveExpectedEncounter(expectedEncounter);
} else {
log
.error("Attempt to store ExpectedEncounter with null due or late date");
return null;
}
}
/* PatientObsService methods start */
public Date getPatientBirthDate(Integer patientId) {
Patient patient = patientService.getPatient(patientId);
return patient.getBirthdate();
}
private List<Obs> getMatchingObs(Person person, Concept question,
Concept answer, Integer obsGroupId, Date from, Date to) {
List<Concept> questions = null;
if (question != null) {
questions = new ArrayList<Concept>();
questions.add(question);
}
List<Concept> answers = null;
if (answer != null) {
answers = new ArrayList<Concept>();
answers.add(answer);
}
List<Person> whom = new ArrayList<Person>();
whom.add(person);
// patients, encounters, questions, answers, persontype, locations,
// sort, max returned, group id, from date, to date, include voided
List<Obs> obsList = obsService.getObservations(whom, null, questions,
answers, null, null, null, null, obsGroupId, from, to, false);
return obsList;
}
public int getNumberOfObs(Integer personId, String conceptName,
String conceptValue) {
return getNumberOfObs(personService.getPerson(personId), conceptService
.getConcept(conceptName), conceptService
.getConcept(conceptValue));
}
public Date getLastObsCreationDate(Integer personId, String conceptName,
String conceptValue) {
return getLastObsCreationDate(personService.getPerson(personId),
conceptService.getConcept(conceptName), conceptService
.getConcept(conceptValue));
}
public Date getLastObsDate(Integer personId, String conceptName,
String conceptValue) {
return getLastObsDate(personService.getPerson(personId), conceptService
.getConcept(conceptName), conceptService
.getConcept(conceptValue));
}
public Date getLastDoseObsDate(Integer personId, String conceptName,
Integer doseNumber) {
List<Obs> matchingObs = obsService.getObservationsByPersonAndConcept(
personService.getPerson(personId), conceptService
.getConcept(conceptName));
for (Obs obs : matchingObs) {
Double value = obs.getValueNumeric();
if (value != null && doseNumber == value.intValue()) {
return obs.getObsDatetime();
}
}
return null;
}
public Date getLastDoseObsDateInActivePregnancy(Integer patientId,
String conceptName, Integer doseNumber) {
Obs pregnancy = getActivePregnancy(patientId);
if (pregnancy != null) {
Integer pregnancyObsId = pregnancy.getObsId();
List<Obs> matchingObs = getMatchingObs(personService
.getPerson(patientId), conceptService
.getConcept(conceptName), null, pregnancyObsId, null, null);
for (Obs obs : matchingObs) {
Double value = obs.getValueNumeric();
if (value != null && doseNumber == value.intValue()) {
return obs.getObsDatetime();
}
}
}
return null;
}
public Obs getActivePregnancyDueDateObs(Integer patientId, Obs pregnancy) {
if (pregnancy != null) {
Integer pregnancyObsId = pregnancy.getObsId();
List<Obs> dueDateObsList = getMatchingObs(personService
.getPerson(patientId), concept(ConceptEnum.CONCEPT_ESTIMATED_DATE_OF_CONFINEMENT), null,
pregnancyObsId, null, null);
if (dueDateObsList.size() > 0) {
return dueDateObsList.get(0);
}
}
return null;
}
public Date getActivePregnancyDueDate(Integer patientId) {
Obs pregnancy = getActivePregnancy(patientId);
Obs dueDateObs = getActivePregnancyDueDateObs(patientId, pregnancy);
if (dueDateObs != null) {
return dueDateObs.getValueDatetime();
}
return null;
}
public Date getLastPregnancyEndDate(Integer patientId) {
List<Obs> pregnancyStatusObsList = getMatchingObs(personService
.getPerson(patientId), concept(ConceptEnum.CONCEPT_PREGNANCY_STATUS), null, null,
null, null);
for (Obs pregnancyStatusObs : pregnancyStatusObsList) {
Boolean status = pregnancyStatusObs.getValueAsBoolean();
if (Boolean.FALSE.equals(status)) {
return pregnancyStatusObs.getObsDatetime();
}
}
return null;
}
public Date getLastObsValue(Integer personId, String conceptName) {
return getLastObsValue(personService.getPerson(personId),
conceptService.getConcept(conceptName));
}
public int getNumberOfObs(Person person, Concept concept, Concept value) {
List<Obs> obsList = getMatchingObs(person, concept, value, null, null,
null);
return obsList.size();
}
public Date getLastObsCreationDate(Person person, Concept concept,
Concept value) {
Date latestObsDate = null;
// List default sorted by Obs datetime
List<Obs> obsList = getMatchingObs(person, concept, value, null, null,
null);
if (obsList.size() > 0) {
latestObsDate = obsList.get(obsList.size() - 1).getDateCreated();
} else if (log.isDebugEnabled()) {
log.debug("No matching Obs: person id: " + person.getPersonId()
+ ", concept: " + concept.getConceptId() + ", value: "
+ (value != null ? value.getConceptId() : "null"));
}
return latestObsDate;
}
public Date getLastObsDate(Person person, Concept concept, Concept value) {
Date latestObsDate = null;
// List default sorted by Obs datetime
List<Obs> obsList = getMatchingObs(person, concept, value, null, null,
null);
if (obsList.size() > 0) {
latestObsDate = obsList.get(0).getObsDatetime();
} else if (log.isDebugEnabled()) {
log.debug("No matching Obs: person id: " + person.getPersonId()
+ ", concept: " + concept.getConceptId() + ", value: "
+ (value != null ? value.getConceptId() : "null"));
}
return latestObsDate;
}
public Date getLastObsValue(Person person, Concept concept) {
Date lastestObsValue = null;
List<Obs> obsList = getMatchingObs(person, concept, null, null, null,
null);
if (obsList.size() > 0) {
lastestObsValue = obsList.get(0).getValueDatetime();
} else if (log.isDebugEnabled()) {
log.debug("No matching Obs: person id: " + person.getPersonId()
+ ", concept: " + concept.getConceptId());
}
return lastestObsValue;
}
public Date getObsValue(Integer obsId) {
Date result = null;
if (obsId != null) {
Obs obs = obsService.getObs(obsId);
if (obs != null) {
result = obs.getValueDatetime();
}
}
return result;
}
/* MessageSchedulerImpl methods start */
public void scheduleInfoMessages(String messageKey, String messageKeyA,
String messageKeyB, String messageKeyC,
MessageProgramEnrollment enrollment, Date messageDate,
boolean userPreferenceBased, Date currentDate) {
// TODO: Assumes recipient is person in enrollment
Integer messageRecipientId = enrollment.getPersonId();
Person recipient = personService.getPerson(messageRecipientId);
MediaType mediaType = getPersonMediaType(recipient);
// Schedule multiple messages if media type preference is text, or no
// preference exists, using A/B/C message keys
if (mediaType == MediaType.TEXT) {
scheduleMultipleInfoMessages(messageKeyA, messageKeyB, messageKeyC,
enrollment, messageDate, currentDate);
} else {
scheduleSingleInfoMessage(messageKey, enrollment, messageDate,
currentDate);
}
}
void scheduleMultipleInfoMessages(String messageKeyA, String messageKeyB,
String messageKeyC, MessageProgramEnrollment enrollment,
Date messageDate, Date currentDate) {
// Return existing message definitions
MessageDefinition messageDefinitionA = this
.getMessageDefinition(messageKeyA);
MessageDefinition messageDefinitionB = this
.getMessageDefinition(messageKeyB);
MessageDefinition messageDefinitionC = this
.getMessageDefinition(messageKeyC);
// TODO: Assumes recipient is person in enrollment
Integer messageRecipientId = enrollment.getPersonId();
// Expecting message date to already be preference adjusted
// Determine dates for second and third messages
Calendar calendar = getCalendarWithDate(messageDate);
calendar.add(Calendar.DATE, 2);
Date messageDateB = calendar.getTime();
calendar.add(Calendar.DATE, 2);
Date messageDateC = calendar.getTime();
MessageDefDate messageA = new MessageDefDate(messageDefinitionA,
messageDate);
MessageDefDate messageB = new MessageDefDate(messageDefinitionB,
messageDateB);
MessageDefDate messageC = new MessageDefDate(messageDefinitionC,
messageDateC);
MessageDefDate[] messageDefDates = {messageA, messageB, messageC};
// Cancel any unsent messages for the same enrollment and not matching
// the messages to schedule
this.removeUnsentMessages(messageRecipientId, enrollment,
messageDefDates);
// Create new scheduled message (with pending attempt) for all 3
// messages, for this enrollment, if no matching message already exist
this.createScheduledMessage(messageRecipientId, messageDefinitionA,
enrollment, messageDate, currentDate);
this.createScheduledMessage(messageRecipientId, messageDefinitionB,
enrollment, messageDateB, currentDate);
this.createScheduledMessage(messageRecipientId, messageDefinitionC,
enrollment, messageDateC, currentDate);
}
void scheduleSingleInfoMessage(String messageKey,
MessageProgramEnrollment enrollment, Date messageDate,
Date currentDate) {
// Return existing message definition
MessageDefinition messageDefinition = this
.getMessageDefinition(messageKey);
// TODO: Assumes recipient is person in enrollment
Integer messageRecipientId = enrollment.getPersonId();
// Expecting message date to already be preference adjusted
// Cancel any unsent messages for the same enrollment and not matching
// the message to schedule
this.removeUnsentMessages(messageRecipientId, enrollment,
messageDefinition, messageDate);
// Create new scheduled message (with pending attempt) for enrollment
// if none matching already exist
this.createScheduledMessage(messageRecipientId, messageDefinition,
enrollment, messageDate, currentDate);
}
public ScheduledMessage scheduleCareMessage(String messageKey,
MessageProgramEnrollment enrollment, Date messageDate,
boolean userPreferenceBased, String care, Date currentDate) {
// Return existing message definition
MessageDefinition messageDefinition = this
.getMessageDefinition(messageKey);
// TODO: Assumes recipient is person in enrollment
Integer messageRecipientId = enrollment.getPersonId();
// Create new scheduled message (with pending attempt) for enrollment
// Does not check if one already exists
return this.createCareScheduledMessage(messageRecipientId,
messageDefinition, enrollment, messageDate, care,
userPreferenceBased, currentDate);
}
private MessageDefinition getMessageDefinition(String messageKey) {
MessageDefinition messageDefinition = motechService()
.getMessageDefinition(messageKey);
if (messageDefinition == null) {
log.error("Invalid message key for message definition: "
+ messageKey);
}
return messageDefinition;
}
protected void removeUnsentMessages(Integer recipientId,
MessageProgramEnrollment enrollment,
MessageDefDate[] messageDefDates) {
// Get Messages matching the recipient, enrollment, and status, but
// not matching the list of message definitions and message dates
List<Message> unsentMessages = motechService().getMessages(recipientId,
enrollment, messageDefDates, MessageStatus.SHOULD_ATTEMPT);
log.debug("Unsent messages found during scheduling: "
+ unsentMessages.size());
for (Message unsentMessage : unsentMessages) {
unsentMessage.setAttemptStatus(MessageStatus.CANCELLED);
motechService().saveMessage(unsentMessage);
log.debug("Message cancelled to schedule new: Id: "
+ unsentMessage.getId());
}
}
protected void removeUnsentMessages(Integer recipientId,
MessageProgramEnrollment enrollment,
MessageDefinition messageDefinition, Date messageDate) {
// Get Messages matching the recipient, enrollment, and status, but
// not matching the message definition and message date
List<Message> unsentMessages = motechService().getMessages(recipientId,
enrollment, messageDefinition, messageDate,
MessageStatus.SHOULD_ATTEMPT);
log.debug("Unsent messages found during scheduling: "
+ unsentMessages.size());
for (Message unsentMessage : unsentMessages) {
unsentMessage.setAttemptStatus(MessageStatus.CANCELLED);
motechService().saveMessage(unsentMessage);
log.debug("Message cancelled to schedule new: Id: "
+ unsentMessage.getId());
}
}
public void removeUnsentMessages(List<ScheduledMessage> scheduledMessages) {
for (ScheduledMessage scheduledMessage : scheduledMessages) {
for (Message unsentMessage : scheduledMessage.getMessageAttempts()) {
if (MessageStatus.SHOULD_ATTEMPT == unsentMessage
.getAttemptStatus()) {
unsentMessage.setAttemptStatus(MessageStatus.CANCELLED);
motechService().saveMessage(unsentMessage);
log
.debug("Message cancelled: Id: "
+ unsentMessage.getId());
}
}
}
}
public void addMessageAttempt(ScheduledMessage scheduledMessage,
Date attemptDate, Date maxAttemptDate, boolean userPreferenceBased,
Date currentDate) {
MessageDefinition messageDefinition = scheduledMessage.getMessage();
Person recipient = personService.getPerson(scheduledMessage
.getRecipientId());
Date adjustedMessageDate = adjustCareMessageDate(recipient,
attemptDate, userPreferenceBased, currentDate);
// Prevent scheduling reminders too far in future
// Only schedule one reminder ahead
if (!adjustedMessageDate.after(maxAttemptDate)) {
Message message = messageDefinition.createMessage(scheduledMessage);
message.setAttemptDate(attemptDate);
scheduledMessage.getMessageAttempts().add(message);
if (log.isDebugEnabled()) {
log.debug("Added ScheduledMessage Attempt: recipient: "
+ scheduledMessage.getRecipientId() + ", message key: "
+ messageDefinition.getMessageKey() + ", date: "
+ adjustedMessageDate);
}
motechService().saveScheduledMessage(scheduledMessage);
}
}
public void verifyMessageAttemptDate(ScheduledMessage scheduledMessage,
boolean userPreferenceBased, Date currentDate) {
Person recipient = personService.getPerson(scheduledMessage
.getRecipientId());
List<Message> messages = scheduledMessage.getMessageAttempts();
if (!messages.isEmpty()) {
Message recentMessage = messages.get(0);
if (recentMessage.getAttemptStatus() == MessageStatus.SHOULD_ATTEMPT) {
Date attemptDate = recentMessage.getAttemptDate();
// Check if current message date is valid for user
// preferences or blackout in case these have changed
if (userPreferenceBased) {
attemptDate = findPreferredMessageDate(recipient,
attemptDate, currentDate, true);
} else {
attemptDate = adjustDateForBlackout(attemptDate);
}
if (!attemptDate.equals(recentMessage.getAttemptDate())) {
// Recompute from original scheduled message date
// Allows possibly adjusting to an earlier week or day
Date adjustedMessageDate = adjustCareMessageDate(recipient,
scheduledMessage.getScheduledFor(),
userPreferenceBased, currentDate);
if (log.isDebugEnabled()) {
log.debug("Updating message id="
+ recentMessage.getId() + " date from="
+ recentMessage.getAttemptDate() + " to="
+ adjustedMessageDate);
}
recentMessage.setAttemptDate(adjustedMessageDate);
scheduledMessage.getMessageAttempts().set(0, recentMessage);
motechService().saveScheduledMessage(scheduledMessage);
}
}
}
}
public void removeAllUnsentMessages(MessageProgramEnrollment enrollment) {
List<Message> unsentMessages = motechService().getMessages(enrollment,
MessageStatus.SHOULD_ATTEMPT);
log.debug("Unsent messages found to cancel: " + unsentMessages.size()
+ ", for enrollment: " + enrollment.getId());
for (Message unsentMessage : unsentMessages) {
unsentMessage.setAttemptStatus(MessageStatus.CANCELLED);
motechService().saveMessage(unsentMessage);
log.debug("Message cancelled: Id: " + unsentMessage.getId());
}
}
public Date determineUserPreferredMessageDate(Integer recipientId,
Date messageDate) {
Person recipient = personService.getPerson(recipientId);
return findPreferredMessageDate(recipient, messageDate, null,
false);
}
private void createScheduledMessage(Integer recipientId,
MessageDefinition messageDefinition,
MessageProgramEnrollment enrollment, Date messageDate,
Date currentDate) {
List<ScheduledMessage> scheduledMessages = motechService()
.getScheduledMessages(recipientId, messageDefinition,
enrollment, messageDate);
// Add scheduled message and message attempt is none matching exists
if (scheduledMessages.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Creating ScheduledMessage: recipient: "
+ recipientId + ", enrollment: " + enrollment.getId()
+ ", message key: " + messageDefinition.getMessageKey()
+ ", date: " + messageDate);
}
ScheduledMessage scheduledMessage = new ScheduledMessage(messageDate, recipientId, messageDefinition, enrollment);
Message message = messageDefinition.createMessage(scheduledMessage);
message.setAttemptDate(messageDate);
scheduledMessage.getMessageAttempts().add(message);
motechService().saveScheduledMessage(scheduledMessage);
} else {
if (scheduledMessages.size() > 1 && log.isWarnEnabled()) {
log.warn("Multiple matching scheduled messages: recipient: "
+ recipientId + ", enrollment: " + enrollment.getId()
+ ", message key: " + messageDefinition.getMessageKey()
+ ", date: " + messageDate);
}
// Add message attempt to existing scheduled message if not exist
boolean matchFound = false;
ScheduledMessage scheduledMessage = scheduledMessages.get(0);
for (Message message : scheduledMessage.getMessageAttempts()) {
if ((MessageStatus.SHOULD_ATTEMPT == message.getAttemptStatus()
|| MessageStatus.ATTEMPT_PENDING == message
.getAttemptStatus()
|| MessageStatus.DELIVERED == message
.getAttemptStatus() || MessageStatus.REJECTED == message
.getAttemptStatus())
&& messageDate.equals(message.getAttemptDate())) {
matchFound = true;
break;
}
}
if (!matchFound && !currentDate.after(messageDate)) {
if (log.isDebugEnabled()) {
log.debug("Creating Message: recipient: " + recipientId
+ ", enrollment: " + enrollment.getId()
+ ", message key: "
+ messageDefinition.getMessageKey() + ", date: "
+ messageDate);
}
Message message = messageDefinition
.createMessage(scheduledMessage);
message.setAttemptDate(messageDate);
scheduledMessage.getMessageAttempts().add(message);
motechService().saveScheduledMessage(scheduledMessage);
}
}
}
private ScheduledMessage createCareScheduledMessage(Integer recipientId,
MessageDefinition messageDefinition,
MessageProgramEnrollment enrollment, Date messageDate, String care,
boolean userPreferenceBased, Date currentDate) {
ScheduledMessage scheduledMessage = new ScheduledMessage(messageDate, recipientId, messageDefinition, enrollment);
// Set care field on scheduled message (not set on informational
// messages)
scheduledMessage.setCare(care);
Person recipient = personService.getPerson(recipientId);
Date adjustedMessageDate = adjustCareMessageDate(recipient,
messageDate, userPreferenceBased, currentDate);
Message message = messageDefinition.createMessage(scheduledMessage);
message.setAttemptDate(adjustedMessageDate);
scheduledMessage.getMessageAttempts().add(message);
if (log.isDebugEnabled()) {
log.debug("Creating ScheduledMessage: recipient: " + recipientId
+ ", enrollment: " + enrollment.getId() + ", message key: "
+ messageDefinition.getMessageKey() + ", date: "
+ adjustedMessageDate);
}
return motechService().saveScheduledMessage(scheduledMessage);
}
Date adjustCareMessageDate(Person person, Date messageDate,
boolean userPreferenceBased, Date currentDate) {
Date adjustedDate = verifyFutureDate(messageDate);
if (userPreferenceBased) {
adjustedDate = findPreferredMessageDate(person, adjustedDate,
currentDate, true);
} else {
adjustedDate = adjustDateForBlackout(adjustedDate);
}
return adjustedDate;
}
Date verifyFutureDate(Date messageDate) {
Calendar calendar = Calendar.getInstance();
if (calendar.getTime().after(messageDate)) {
// If date in past, return date 10 minutes in future
calendar.add(Calendar.MINUTE, 10);
return calendar.getTime();
}
return messageDate;
}
public TaskDefinition updateAllMessageProgramsState(Integer batchSize,
Long batchPreviousId) {
List<MessageProgramEnrollment> activeEnrollments = motechService()
.getActiveMessageProgramEnrollments(null, null, null,
batchPreviousId, batchSize);
Date currentDate = new Date();
for (MessageProgramEnrollment enrollment : activeEnrollments) {
MessageProgram program = messageProgramService.program(enrollment.getProgram());
log.debug("MessageProgram Update - Update State: enrollment: "
+ enrollment.getId());
program.determineState(enrollment, currentDate);
batchPreviousId = enrollment.getId();
}
if (activeEnrollments.size() < batchSize) {
batchPreviousId = null;
log.info("Completed updating all enrollments");
}
// Update task properties
TaskDefinition task = schedulerService
.getTaskByName(MotechConstants.TASK_MESSAGEPROGRAM_UPDATE);
if (task != null) {
Map<String, String> properties = task.getProperties();
if (batchPreviousId != null) {
properties.put(MotechConstants.TASK_PROPERTY_BATCH_PREVIOUS_ID,
batchPreviousId.toString());
} else {
properties
.remove(MotechConstants.TASK_PROPERTY_BATCH_PREVIOUS_ID);
}
schedulerService.saveTask(task);
}
return task;
}
public void updateAllCareSchedules() {
List<Patient> patients = patientService.getAllPatients();
log
.info("Updating care schedules for " + patients.size()
+ " patients");
for (Patient patient : patients) {
// Adds patient to transaction synchronization using advice
patientService.savePatient(patient);
}
}
public void sendStaffCareMessages(Date startDate, Date endDate,
Date deliveryDate, Date deliveryTime,
String[] careGroups,
boolean sendUpcoming,
boolean blackoutEnabled) {
final boolean shouldBlackOut = blackoutEnabled && isMessageTimeWithinBlackoutPeriod(deliveryDate);
if (shouldBlackOut) {
log.debug("Cancelling nurse messages during blackout");
return;
}
List<Facility> facilities = motechService().getAllFacilities();
deliveryDate = adjustTime(deliveryDate, deliveryTime);
for (Facility facility : facilities) {
if (facilityPhoneNumberOrLocationAvailable(facility)) {
continue;
}
sendDefaulterMessages(startDate, deliveryDate, careGroups, facility);
if (sendUpcoming) {
sendUpcomingMessages(startDate, endDate, deliveryDate, careGroups, facility);
}
}
}
private boolean facilityPhoneNumberOrLocationAvailable(Facility facility) {
return (facility.getPhoneNumber() == null) || (facility.getLocation() == null);
}
private void sendUpcomingMessages(Date startDate, Date endDate, Date deliveryDate, String[] careGroups, Facility facility) {
WebServiceModelConverterImpl modelConverter = new WebServiceModelConverterImpl();
modelConverter.setRegistrarBean(this);
List<ExpectedEncounter> upcomingEncounters = filterRCTEncounters(getUpcomingExpectedEncounters(facility, careGroups, startDate, endDate));
List<ExpectedObs> upcomingObs = filterRCTObs(getUpcomingExpectedObs(facility, careGroups, startDate, endDate));
final String facilityPhoneNumber = facility.getPhoneNumber();
final boolean upcomingEventsPresent = !(upcomingEncounters.isEmpty() && upcomingObs.isEmpty());
if (upcomingEventsPresent) {
Care[] upcomingCares = modelConverter.upcomingToWebServiceCares(upcomingEncounters, upcomingObs, true);
log.info("Sending upcoming care message to " + facility.name() + " at " + facilityPhoneNumber);
sendStaffUpcomingCareMessage(facilityPhoneNumber, deliveryDate, upcomingCares, getCareMessageGroupingStrategy(facility.getLocation()));
} else {
sendNoUpcomingCareMessage(facility, facilityPhoneNumber);
}
}
private void sendDefaulterMessages(Date startDate, Date deliveryDate, String[] careGroups, Facility facility) {
WebServiceModelConverterImpl modelConverter = new WebServiceModelConverterImpl();
modelConverter.setRegistrarBean(this);
List<ExpectedEncounter> defaultedEncounters = filterRCTEncounters(new ArrayList<ExpectedEncounter>(getDefaultedExpectedEncounters(facility, careGroups, startDate)));
List<ExpectedObs> defaultedObs = filterRCTObs(new ArrayList<ExpectedObs>(getDefaultedExpectedObs(facility, careGroups, startDate)));
final String facilityPhoneNumber = facility.getPhoneNumber();
//TODO: Replace the above code when RCT filtering rules are finalized and implemented.
final boolean defaultersPresent = !(defaultedEncounters.isEmpty() && defaultedObs.isEmpty());
if (defaultersPresent) {
Care[] defaultedCares = modelConverter.defaultedToWebServiceCares(defaultedEncounters, defaultedObs);
log.info("Sending defaulter message to " + facility.name() + " at " + facilityPhoneNumber);
sendStaffDefaultedCareMessage(facilityPhoneNumber, deliveryDate, defaultedCares, getCareMessageGroupingStrategy(facility.getLocation()));
} else {
sendNoDefaultersMessage(facility, facilityPhoneNumber);
}
}
private void sendNoUpcomingCareMessage(Facility facility, String phoneNumber) {
log.info("Sending 'no upcoming care' message to " + facility.name() + " at " + phoneNumber);
try {
org.motechproject.ws.MessageStatus messageStatus = mobileService.sendMessage(facility.name() + " has no upcoming care for this week", phoneNumber);
if (messageStatus == org.motechproject.ws.MessageStatus.FAILED) {
log.error("Unable to message " + phoneNumber + " that they have no upcoming care");
}
} catch (Exception e) {
log.error("Unable to message " + phoneNumber + " that they have no upcoming care", e);
}
}
private void sendNoDefaultersMessage(Facility facility, String phoneNumber) {
log.info("Sending 'no defaulters' message to " + facility.name() + " at " + phoneNumber);
try {
org.motechproject.ws.MessageStatus messageStatus = mobileService.sendMessage(facility.name() + " has no defaulters for this week", phoneNumber);
if (messageStatus == org.motechproject.ws.MessageStatus.FAILED) {
log.error("Unable to message " + phoneNumber + " that they have no defaulters");
}
} catch (Exception e) {
log.error("Unable to message " + phoneNumber + " that they have no defaulters", e);
}
}
private CareMessageGroupingStrategy getCareMessageGroupingStrategy(Location facilityLocation) {
return DISTRICT_FACTORY.getDistrictWithName(facilityLocation.getCountyDistrict()).getCareMessageGroupingStrategy();
}
public List<ExpectedEncounter> filterRCTEncounters(List<ExpectedEncounter> allDefaulters) {
List<ExpectedEncounter> toBeRemoved = new ArrayList<ExpectedEncounter>();
for (ExpectedEncounter allDefaulter : allDefaulters) {
ExpectedEncounter expectedEncounter = allDefaulter;
if (meetsFilteringCriteria(expectedEncounter.getPatient())) {
toBeRemoved.add(expectedEncounter);
}
}
allDefaulters.removeAll(toBeRemoved);
return allDefaulters;
}
private boolean meetsFilteringCriteria(Patient patient) {
if (patient == null) return true;
if(rctService.isPatientRegisteredAndInTreatmentGroup(patient)) return false ;
return isFromUpperEast(patient) && (patient.getId()) > 5717 ;
}
private Boolean isFromUpperEast(Patient patient) {
Facility facility = getFacilityByPatient(patient);
return facility != null && facility.isInRegion("Upper East");
}
public List<ExpectedObs> filterRCTObs(List<ExpectedObs> allDefaulters) {
List<ExpectedObs> toBeRemoved = new ArrayList<ExpectedObs>();
for (ExpectedObs allDefaulter : allDefaulters) {
ExpectedObs expectedObs = allDefaulter;
if (meetsFilteringCriteria(expectedObs.getPatient())) {
toBeRemoved.add(expectedObs);
}
}
allDefaulters.removeAll(toBeRemoved);
return allDefaulters;
}
/* NotificationTask methods start */
public void sendMessages(Date startDate, Date endDate, boolean sendImmediate) {
try {
List<Message> shouldAttemptMessages = motechService().getMessages(
startDate, endDate, MessageStatus.SHOULD_ATTEMPT);
if (log.isDebugEnabled()) {
log
.debug("Notification Task executed, Should Attempt Messages found: "
+ shouldAttemptMessages.size());
}
if (!shouldAttemptMessages.isEmpty()) {
PatientMessage[] messages = constructPatientMessages(
shouldAttemptMessages, sendImmediate);
if (messages.length > 0) {
mobileService.sendPatientMessages(messages);
}
}
} catch (Exception e) {
log.error("Failure to send patient messages", e);
}
}
private PatientMessage[] constructPatientMessages(List<Message> messages,
boolean sendImmediate) {
List<PatientMessage> patientMessages = new ArrayList<PatientMessage>();
for (Message message : messages) {
PatientMessage patientMessage = constructPatientMessage(message);
if (patientMessage != null) {
if (sendImmediate) {
patientMessage.setStartDate(null);
patientMessage.setEndDate(null);
}
patientMessages.add(patientMessage);
message.setAttemptStatus(MessageStatus.ATTEMPT_PENDING);
} else {
message.setAttemptStatus(MessageStatus.REJECTED);
}
motechService().saveMessage(message);
}
return patientMessages.toArray(new PatientMessage[patientMessages
.size()]);
}
private PatientMessage constructPatientMessage(Message message) {
try {
Long notificationType = message.getSchedule().getMessage()
.getPublicId();
Integer recipientId = message.getSchedule().getRecipientId();
Person person = personService.getPerson(recipientId);
String phoneNumber = getPersonPhoneNumber(person);
// Cancel message if phone number is considered troubled
if (isPhoneTroubled(phoneNumber)) {
if (log.isDebugEnabled()) {
log.debug("Attempt to send to Troubled Phone, Phone: "
+ phoneNumber + ", Notification: "
+ notificationType);
}
} else {
if (log.isDebugEnabled()) {
log.debug("Scheduled Message, Phone: " + phoneNumber
+ ", Notification: " + notificationType);
}
String messageId = message.getPublicId();
MediaType mediaType = getPersonMediaType(person);
String languageCode = getPersonLanguageCode(person);
NameValuePair[] personalInfo = new NameValuePair[0];
Date messageStartDate = message.getAttemptDate();
Date messageEndDate = null;
Patient patient = patientService.getPatient(recipientId);
if (rctService.isPatientRegisteredAndInTreatmentGroup(patient)) {
String motechId = new MotechPatient(patient).getMotechId();
log.info("Not creating message because the recipient falls in the RCT Control group. " +
"Patient MoTeCH id: " + motechId + " Message ID:" + message.getPublicId());
return null;
}
if (patient != null) {
ContactNumberType contactNumberType = getPersonPhoneType(person);
String motechId = patient.getPatientIdentifier(
MotechConstants.PATIENT_IDENTIFIER_MOTECH_ID)
.getIdentifier();
PatientMessage patientMessage = new PatientMessage();
patientMessage.setMessageId(messageId);
patientMessage.setPersonalInfo(personalInfo);
patientMessage.setPatientNumber(phoneNumber);
patientMessage.setPatientNumberType(contactNumberType);
patientMessage.setLangCode(languageCode);
patientMessage.setMediaType(mediaType);
patientMessage.setNotificationType(notificationType);
patientMessage.setStartDate(messageStartDate);
patientMessage.setEndDate(messageEndDate);
patientMessage.setRecipientId(motechId);
return patientMessage;
} else {
log
.error("Attempt to send message to non-existent Patient: "
+ recipientId);
}
}
} catch (Exception e) {
log.error("Error creating patient message", e);
}
return null;
}
private boolean sendStaffMessage(String messageId,
NameValuePair[] personalInfo, String phoneNumber,
String languageCode, MediaType mediaType, Long notificationType,
Date messageStartDate, Date messageEndDate,
org.motechproject.ws.Patient[] patients) {
try {
org.motechproject.ws.MessageStatus messageStatus = mobileService
.sendCHPSMessage(messageId, personalInfo, phoneNumber,
patients, languageCode, mediaType,
notificationType, messageStartDate, messageEndDate);
return messageStatus != org.motechproject.ws.MessageStatus.FAILED;
} catch (Exception e) {
log.error("Mobile WS staff message failure", e);
return false;
}
}
private boolean sendStaffDefaultedCareMessage(String phoneNumber,
Date messageStartDate,
Care[] cares, CareMessageGroupingStrategy groupingStrategy) {
try {
org.motechproject.ws.MessageStatus messageStatus;
messageStatus = mobileService.sendDefaulterMessage(null, phoneNumber, cares, groupingStrategy,
MediaType.TEXT, messageStartDate, null);
return messageStatus != org.motechproject.ws.MessageStatus.FAILED;
} catch (Exception e) {
log.error("Mobile WS staff defaulted care message failure", e);
return false;
}
}
private boolean sendStaffUpcomingCareMessage(String phoneNumber,
Date messageStartDate,
Care[] cares, CareMessageGroupingStrategy groupingStrategy) {
try {
org.motechproject.ws.MessageStatus messageStatus;
messageStatus = mobileService.sendBulkCaresMessage(null, phoneNumber, cares, groupingStrategy,
MediaType.TEXT, messageStartDate, null);
return messageStatus != org.motechproject.ws.MessageStatus.FAILED;
} catch (Exception e) {
log.error("Mobile WS staff upcoming care message failure", e);
return false;
}
}
/* NotificationTask methods end */
/* Factored out methods start */
public String[] getActiveMessageProgramEnrollmentNames(Patient patient) {
List<MessageProgramEnrollment> enrollments = motechService()
.getActiveMessageProgramEnrollments(patient.getPatientId(),
null, null, null, null);
List<String> enrollmentNames = new ArrayList<String>();
for (MessageProgramEnrollment enrollment : enrollments) {
enrollmentNames.add(enrollment.getProgram());
}
return enrollmentNames.toArray(new String[enrollmentNames.size()]);
}
public void addMessageProgramEnrollment(Integer personId, String program,
Integer obsId) {
List<MessageProgramEnrollment> enrollments = motechService()
.getActiveMessageProgramEnrollments(personId, program, obsId,
null, null);
if (enrollments.size() == 0) {
MessageProgramEnrollment enrollment = new MessageProgramEnrollment();
enrollment.setPersonId(personId);
enrollment.setProgram(program);
enrollment.setStartDate(new Date());
enrollment.setObsId(obsId);
motechService().saveMessageProgramEnrollment(enrollment);
}
}
public void removeMessageProgramEnrollment(
MessageProgramEnrollment enrollment) {
removeAllUnsentMessages(enrollment);
if (enrollment.getEndDate() == null) {
enrollment.setEndDate(new Date());
motechService().saveMessageProgramEnrollment(enrollment);
}
}
private void removeAllMessageProgramEnrollments(Integer personId) {
List<MessageProgramEnrollment> enrollments = motechService()
.getActiveMessageProgramEnrollments(personId, null, null, null,
null);
for (MessageProgramEnrollment enrollment : enrollments) {
removeMessageProgramEnrollment(enrollment);
}
}
private Obs createNumericValueObs(Date date, Concept concept, Person person,
Location location, Integer value, Encounter encounter, User creator) {
return createNumericValueObs(date, concept, person, location,
(double) value, encounter, creator);
}
private Obs createNumericValueObs(Date date, Concept concept, Person person,
Location location, Double value, Encounter encounter, User creator) {
Obs obs = createObs(date, concept, person, location, encounter, creator);
obs.setValueNumeric(value);
return obs;
}
private Obs createBooleanValueObs(Date date, Concept concept, Person person,
Location location, Boolean value, Encounter encounter, User creator) {
Double doubleValue;
// Boolean currently stored as Numeric 1 or 0
if (Boolean.TRUE.equals(value)) {
doubleValue = 1.0;
} else {
doubleValue = 0.0;
}
return createNumericValueObs(date, concept, person, location,
doubleValue, encounter, creator);
}
private Obs createDateValueObs(Date date, Concept concept, Person person,
Location location, Date value, Encounter encounter, User creator) {
Obs obs = createObs(date, concept, person, location, encounter, creator);
obs.setValueDatetime(value);
return obs;
}
private Obs createConceptValueObs(Date date, Concept concept, Person person,
Location location, Concept value, Encounter encounter, User creator) {
Obs obs = createObs(date, concept, person, location, encounter, creator);
obs.setValueCoded(value);
return obs;
}
private Obs createTextValueObs(Date date, Concept concept, Person person,
Location location, String value, Encounter encounter, User creator) {
Obs obs = createObs(date, concept, person, location, encounter, creator);
obs.setValueText(value);
return obs;
}
private Obs createObs(Date date, Concept concept, Person person,
Location location, Encounter encounter, User creator) {
Obs obs = new Obs();
obs.setObsDatetime(date);
obs.setConcept(concept);
obs.setPerson(person);
obs.setLocation(location);
if (encounter != null) {
obs.setEncounter(encounter);
}
if (creator != null) {
obs.setCreator(creator);
}
return obs;
}
public Patient getPatientByMotechId(String motechId) {
PatientIdentifierType motechIdType = getPatientIdentifierTypeForMotechId();
List<PatientIdentifierType> idTypes = new ArrayList<PatientIdentifierType>();
idTypes.add(motechIdType);
// Parameters are Name, Id, Id type, match exactly boolean
List<Patient> patients = patientService.getPatients(null, motechId,
idTypes, true);
if (patients.size() > 0) {
if (patients.size() > 1) {
log.warn("Multiple Patients found for Motech ID: " + motechId);
}
return patients.get(0);
}
return null;
}
public User getStaffBySystemId(String systemId) {
return userService.getUserByUsername(systemId);
}
public String getPersonPhoneNumber(Person person) {
PersonAttribute phoneNumberAttr = person
.getAttribute(MotechConstants.PERSON_ATTRIBUTE_PHONE_NUMBER);
if (phoneNumberAttr != null
&& StringUtils.isNotEmpty(phoneNumberAttr.getValue())) {
return phoneNumberAttr.getValue();
}
log
.warn("No phone number found for Person id: "
+ person.getPersonId());
return null;
}
private String getPersonLanguageCode(Person person) {
PersonAttribute languageAttr = person
.getAttribute(MotechConstants.PERSON_ATTRIBUTE_LANGUAGE);
if (languageAttr != null
&& StringUtils.isNotEmpty(languageAttr.getValue())) {
return languageAttr.getValue();
}
log.debug("No language found for Person id: " + person.getPersonId());
return null;
}
private ContactNumberType getPersonPhoneType(Person person) {
PersonAttribute phoneTypeAttr = person
.getAttribute(MotechConstants.PERSON_ATTRIBUTE_PHONE_TYPE);
if (phoneTypeAttr != null
&& StringUtils.isNotEmpty(phoneTypeAttr.getValue())) {
try {
return ContactNumberType.valueOf(phoneTypeAttr.getValue());
} catch (Exception e) {
log.error("Unable to parse phone type: "
+ phoneTypeAttr.getValue() + ", for Person ID:"
+ person.getPersonId(), e);
}
}
log.debug("No contact number type found for Person id: "
+ person.getPersonId());
return null;
}
private MediaType getPersonMediaType(Person person) {
PersonAttribute mediaTypeAttr = person
.getAttribute(MotechConstants.PERSON_ATTRIBUTE_MEDIA_TYPE);
if (mediaTypeAttr != null
&& StringUtils.isNotEmpty(mediaTypeAttr.getValue())) {
try {
return MediaType.valueOf(mediaTypeAttr.getValue());
} catch (Exception e) {
log.error("Unable to parse media type: "
+ mediaTypeAttr.getValue() + ", for Person ID:"
+ person.getPersonId(), e);
}
}
log.debug("No media type found for Person id: " + person.getPersonId());
return null;
}
private boolean isPhoneTroubled(String phoneNumber) {
TroubledPhone troubledPhone = contextService.getMotechService()
.getTroubledPhone(phoneNumber);
Integer maxFailures = getMaxPhoneNumberFailures();
return maxFailures != null && troubledPhone != null && troubledPhone.getSendFailures() >= maxFailures;
}
private Integer getMaxPhoneNumberFailures() {
String troubledPhoneProperty = getTroubledPhoneProperty();
if (troubledPhoneProperty != null) {
return Integer.parseInt(troubledPhoneProperty);
}
log.error("Troubled Phone Property not found");
return null;
}
public Integer getMaxPatientCareReminders() {
String careRemindersProperty = getPatientCareRemindersProperty();
if (careRemindersProperty != null) {
return Integer.parseInt(careRemindersProperty);
}
log.error("Patient Care Reminders Property not found");
return null;
}
private DayOfWeek getMessageDayOfWeek(Person person) {
PersonAttribute messageDeliveryDayChosen = person.getAttribute(MotechConstants.PERSON_ATTRIBUTE_DELIVERY_DAY);
DayOfWeek day = null;
if (messageDeliveryDayChosen != null && StringUtils.isNotEmpty(messageDeliveryDayChosen.getValue())) {
try {
day = DayOfWeek.valueOf(messageDeliveryDayChosen.getValue());
} catch (Exception e) {
log.error("Unable to parse day of week: " + messageDeliveryDayChosen.getValue()
+ ", for Person ID:" + person.getPersonId(), e);
}
} else {
log.debug("No day of week found for Person id: "
+ person.getPersonId());
}
return day;
}
private Date getPersonMessageTimeOfDay(Person person) {
PersonAttribute timeAttr = person.getAttribute(MotechConstants.PERSON_ATTRIBUTE_DELIVERY_TIME);
Date time = null;
if (timeAttr != null && StringUtils.isNotEmpty(timeAttr.getValue())) {
SimpleDateFormat timeFormat = new SimpleDateFormat(
MotechConstants.TIME_FORMAT_DELIVERY_TIME);
try {
time = timeFormat.parse(timeAttr.getValue());
} catch (Exception e) {
log.error("Unable to parse time of day: " + timeAttr.getValue()
+ ", for Person ID:" + person.getPersonId(), e);
}
} else {
log.debug("No time of day found for Person id: "
+ person.getPersonId());
}
return time;
}
private DayOfWeek getDefaultPatientDayOfWeek() {
String dayProperty = getPatientDayOfWeekProperty();
DayOfWeek day = null;
try {
day = DayOfWeek.valueOf(dayProperty);
} catch (Exception e) {
log
.error("Invalid Patient Day of Week Property: "
+ dayProperty, e);
}
return day;
}
private Date getDefaultPatientTimeOfDay() {
String timeProperty = getPatientTimeOfDayProperty();
SimpleDateFormat timeFormat = new SimpleDateFormat(
MotechConstants.TIME_FORMAT_DELIVERY_TIME);
Date time = null;
try {
time = timeFormat.parse(timeProperty);
} catch (Exception e) {
log.error("Invalid Patient Time of Day Property: " + timeProperty,
e);
}
return time;
}
private Integer getMaxQueryResults() {
String maxResultsProperty = contextService.getAdministrationService().getGlobalProperty(
MotechConstants.GLOBAL_PROPERTY_MAX_QUERY_RESULTS);
if (maxResultsProperty != null) {
return Integer.parseInt(maxResultsProperty);
}
log.error("Max Query Results Property not found");
return null;
}
public Date findPreferredMessageDate(Person person, Date messageDate, Date currentDate, boolean checkInFuture) {
Calendar calendar = getCalendarWithDate(messageDate);
setTimeOfDay(person, calendar);
setDayOfTheWeek(person, currentDate, checkInFuture, calendar);
return calendar.getTime();
}
private void setDayOfTheWeek(Person person, Date currentDate, boolean checkInFuture, Calendar calendar) {
DayOfWeek day = getMessageDayOfWeek(person);
if (day == null) {
day = getDefaultPatientDayOfWeek();
}
if (day != null) {
calendar.set(Calendar.DAY_OF_WEEK, day.getCalendarValue());
if (checkInFuture && calendar.getTime().before(currentDate)) {
// Add a week if date in past after setting the day of week
calendar.add(Calendar.DATE, 7);
}
}
}
private void setTimeOfDay(Person person, Calendar calendar) {
Date time = getPersonMessageTimeOfDay(person);
if (time == null) {
time = getDefaultPatientTimeOfDay();
}
if (time != null) {
Calendar timeCalendar = getCalendarWithDate(time);
calendar.set(Calendar.HOUR_OF_DAY, timeCalendar.get(Calendar.HOUR_OF_DAY));
calendar.set(Calendar.MINUTE, timeCalendar.get(Calendar.MINUTE));
}
calendar.set(Calendar.SECOND, 0);
}
private Calendar getCalendarWithDate(Date messageDate) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(messageDate);
return calendar;
}
Date adjustTime(Date date, Date time) {
if (date == null || time == null) {
return date;
}
Calendar calendar = getCalendarWithDate(date);
Calendar timeCalendar = getCalendarWithDate(time);
calendar.set(Calendar.HOUR_OF_DAY, timeCalendar.get(Calendar.HOUR_OF_DAY));
calendar.set(Calendar.MINUTE, timeCalendar.get(Calendar.MINUTE));
calendar.set(Calendar.SECOND, 0);
if (calendar.getTime().before(date)) {
// Add a day if before original date
// after setting the time of day
calendar.add(Calendar.DATE, 1);
}
return calendar.getTime();
}
Date adjustDateForBlackout(Date date) {
if (date == null) {
return date;
}
Blackout blackout = motechService().getBlackoutSettings();
if (blackout == null) {
return date;
}
Calendar blackoutCalendar = getCalendarWithDate(date);
adjustForBlackoutStartDate(date, blackout, blackoutCalendar);
Date blackoutStart = blackoutCalendar.getTime();
setBlackOutTime(blackout.getEndTime(), blackoutCalendar);
if (blackoutCalendar.getTime().before(blackoutStart)) {
// Add a day if blackout end date before start date after setting time
blackoutCalendar.add(Calendar.DATE, 1);
}
Date blackoutEnd = blackoutCalendar.getTime();
if (date.after(blackoutStart) && date.before(blackoutEnd)) {
return blackoutEnd;
}
return date;
}
private void adjustForBlackoutStartDate(Date date, Blackout blackout, Calendar blackoutCalendar) {
setBlackOutTime(blackout.getStartTime(), blackoutCalendar);
if (date.before(blackoutCalendar.getTime())) {
// Remove a day if blackout start date before the message date
blackoutCalendar.add(Calendar.DATE, -1);
}
}
private void setBlackOutTime(Date blackoutTime, Calendar blackoutCalendar) {
Calendar timeCalendar = getCalendarWithDate(blackoutTime);
blackoutCalendar.set(Calendar.HOUR_OF_DAY, timeCalendar.get(Calendar.HOUR_OF_DAY));
blackoutCalendar.set(Calendar.MINUTE, timeCalendar.get(Calendar.MINUTE));
blackoutCalendar.set(Calendar.SECOND, timeCalendar.get(Calendar.SECOND));
}
boolean isMessageTimeWithinBlackoutPeriod(Date deliveryDate) {
Date checkForDate = (deliveryDate != null ? deliveryDate : new Date());
Blackout blackout = motechService().getBlackoutSettings();
if (blackout == null) {
return false;
}
Calendar blackoutCalendar = getCalendarWithDate(checkForDate);
adjustForBlackoutStartDate(checkForDate, blackout, blackoutCalendar);
Date blackoutStart = blackoutCalendar.getTime();
setBlackOutTime(blackout.getEndTime(), blackoutCalendar);
if (blackoutCalendar.getTime().before(blackoutStart)) {
// Add a day if blackout end date before start date after setting time
blackoutCalendar.add(Calendar.DATE, 1);
}
Date blackoutEnd = blackoutCalendar.getTime();
return checkForDate.after(blackoutStart) && checkForDate.before(blackoutEnd);
}
public Community saveCommunity(Community community) {
if (community.getCommunityId() == null) {
community.setCommunityId(identifierGenerator.generateCommunityId());
}
return motechService().saveCommunity(community);
}
public Facility saveNewFacility(Facility facility) {
facility.setFacilityId(identifierGenerator.generateFacilityId());
return motechService().saveFacility(facility);
}
public void setIdentifierGenerator(IdentifierGenerator identifierGenerator) {
this.identifierGenerator = identifierGenerator;
}
private Location getGhanaLocation() {
return locationService.getLocation(
MotechConstants.LOCATION_GHANA);
}
private String getTroubledPhoneProperty() {
return administrationService.getGlobalProperty(
MotechConstants.GLOBAL_PROPERTY_TROUBLED_PHONE);
}
private String getPatientCareRemindersProperty() {
return administrationService.getGlobalProperty(
MotechConstants.GLOBAL_PROPERTY_CARE_REMINDERS);
}
private String getPatientDayOfWeekProperty() {
return administrationService.getGlobalProperty(
MotechConstants.GLOBAL_PROPERTY_DAY_OF_WEEK);
}
private String getPatientTimeOfDayProperty() {
return administrationService.getGlobalProperty(
MotechConstants.GLOBAL_PROPERTY_TIME_OF_DAY);
}
/* Factored out methods end */
public Facility getFacilityById(Integer facilityId) {
return motechService().getFacilityById(facilityId);
}
public Community getCommunityById(Integer communityId) {
return motechService().getCommunityById(communityId);
}
public Community getCommunityByPatient(Patient patient) {
return motechService().getCommunityByPatient(patient);
}
public Facility getFacilityByPatient(Patient patient) {
return motechService().facilityFor(patient);
}
public Date getChildRegistrationDate() {
return motechService().getConfigurationFor("valid.child.registration.date").asDate();
}
public Facility getUnknownFacility() {
return motechService().unknownFacility();
}
public List<String> getStaffTypes() {
return staffTypes;
}
public void setStaffTypes(List<String> staffTypes) {
this.staffTypes = staffTypes;
}
public boolean isValidMotechIdCheckDigit(Integer motechId) {
if (motechId == null) {
return false;
}
String motechIdString = motechId.toString();
MotechIdVerhoeffValidator validator = new MotechIdVerhoeffValidator();
boolean isValid = false;
try {
isValid = validator.isValid(motechIdString);
} catch (Exception ignored) {
}
return isValid;
}
public boolean isValidIdCheckDigit(Integer idWithCheckDigit) {
if (idWithCheckDigit == null) {
return false;
}
String idWithCheckDigitString = idWithCheckDigit.toString();
VerhoeffValidator validator = new VerhoeffValidator();
boolean isValid = false;
try {
isValid = validator.isValid(idWithCheckDigitString);
} catch (Exception ignored) {
}
return isValid;
}
public void setRelationshipService(RelationshipService relationshipService) {
this.relationshipService = relationshipService;
}
public void setPatientService(PatientService patientService) {
this.patientService = patientService;
}
public void setPersonService(PersonService personService) {
this.personService = personService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
public void setAuthenticationService(AuthenticationService authenticationService) {
this.authenticationService = authenticationService;
}
public void setConceptService(ConceptService conceptService) {
this.conceptService = conceptService;
}
public void setLocationService(LocationService locationService) {
this.locationService = locationService;
}
public void setObsService(ObsService obsService) {
this.obsService = obsService;
}
public void setEncounterService(EncounterService encounterService) {
this.encounterService = encounterService;
}
public void setSchedulerService(SchedulerService schedulerService) {
this.schedulerService = schedulerService;
}
public void setAdministrationService(AdministrationService administrationService) {
this.administrationService = administrationService;
}
public void setRctService(RCTService rctService) {
this.rctService = rctService;
}
private MotechService motechService() {
return contextService.getMotechService();
}
private PatientIdentifierType getPatientIdentifierTypeForMotechId() {
return PATIENT_IDENTIFIER_MOTECH_ID.getIdentifierType(patientService);
}
private EncounterType getEncounterType(EncounterTypeEnum encounterType) {
return encounterType.getEncounterType(encounterService);
}
private Concept concept(ConceptEnum conceptEnum) {
return conceptEnum.getConcept(conceptService);
}
private boolean isNotNull(Object object) {
return object != null;
}
public void setMessageProgramService(MessageProgramServiceImpl messageProgramService) {
this.messageProgramService = messageProgramService;
}
public MessageProgramServiceImpl getMessageProgramService() {
return messageProgramService;
}
}
|
package name.abuchen.portfolio.datatransfer.pdf;
import static name.abuchen.portfolio.datatransfer.pdf.PDFExtractorUtils.checkAndSetGrossUnit;
import java.math.BigDecimal;
import java.math.RoundingMode;
import name.abuchen.portfolio.datatransfer.pdf.PDFParser.Block;
import name.abuchen.portfolio.datatransfer.pdf.PDFParser.DocumentType;
import name.abuchen.portfolio.datatransfer.pdf.PDFParser.Transaction;
import name.abuchen.portfolio.model.AccountTransaction;
import name.abuchen.portfolio.model.BuySellEntry;
import name.abuchen.portfolio.model.Client;
import name.abuchen.portfolio.model.PortfolioTransaction;
import name.abuchen.portfolio.money.Money;
@SuppressWarnings("nls")
public class EbasePDFExtractor extends AbstractPDFExtractor
{
public EbasePDFExtractor(Client client)
{
super(client);
addBankIdentifier("European Bank for Financial Services GmbH"); //$NON-NLS-1$
addBuySellTransaction();
addDividendeTransaction();
addAdvanceTaxTransaction();
addFeesWithSecurityTransaction();
addDeliveryInOutBoundTransaction();
}
@Override
public String getLabel()
{
return "European Bank for Financial Services GmbH"; //$NON-NLS-1$
}
private void addBuySellTransaction()
{
DocumentType type = new DocumentType("(Kauf"
+ "|Ansparplan"
+ "|Fondsertrag"
+ "|Verkauf"
+ "|Entgelt Verkauf"
+ "|Entgeltbelastung Verkauf"
+ "|Entnahmeplan"
+ "|Fondsumschichtung"
+ "|Wiederanlage Fondsertrag"
+ "|Wiederanlage Ertragsaussch.ttung)");
this.addDocumentTyp(type);
Transaction<BuySellEntry> pdfTransaction = new Transaction<>();
pdfTransaction.subject(() -> {
BuySellEntry entry = new BuySellEntry();
entry.setType(PortfolioTransaction.Type.BUY);
/***
* We have multiple entries in the document
* and cannot split it with "endWith",
* so the "skipTransaction" flag must be removed.
*/
type.getCurrentContext().remove("skipTransaction");
return entry;
});
Block firstRelevantLine = new Block("^(Kauf"
+ "|Ansparplan"
+ "|Fondsertrag"
+ "|Verkauf"
+ "|Entgelt Verkauf"
+ "|Entgeltbelastung Verkauf"
+ "|Entnahmeplan"
+ "|Fondsumschichtung \\((Abgang|Zugang)\\) .*"
+ "|Wiederanlage Fondsertrag [\\.,\\d]+ [\\w]+"
+ "|\\(Anteilpreis\\))( .*)?$");
type.addBlock(firstRelevantLine);
firstRelevantLine.set(pdfTransaction);
pdfTransaction
// Is type --> "Verkauf" change from BUY to SELL
.section("type").optional()
.match("^(?<type>(Kauf"
+ "|Ansparplan"
+ "|Fondsertrag"
+ "|Verkauf"
+ "|Entgelt Verkauf"
+ "|Entgeltbelastung Verkauf"
+ "|Entnahmeplan"
+ "|Fondsumschichtung \\(Abgang\\)"
+ "|Fondsumschichtung \\(Zugang\\)"
+ "|Wiederanlage Fondsertrag"
+ "|Wiederanlage Ertragsaussch.ttung)) .*$")
.assign((t, v) -> {
if (v.get("type").equals("Verkauf")
|| v.get("type").equals("Entgelt Verkauf")
|| v.get("type").equals("Entgeltbelastung Verkauf")
|| v.get("type").equals("Entnahmeplan")
|| v.get("type").equals("Fondsumschichtung (Abgang)"))
{
t.setType(PortfolioTransaction.Type.SELL);
}
})
/***
* Here we set a flag for all entries
* which should be skipped.
*
* If this is not done, it can happen that taxes and fees
* are included from the following entries
*/
.section("type").optional()
.match("^(?<type>Fondsertrag) .*$")
.assign((t, v) -> {
if (v.get("type").equals("Fondsertrag"))
type.getCurrentContext().put("skipTransaction", Boolean.TRUE.toString());
})
// Kauf 300,00 EUR mit Kursdatum 20.11.2019 in Depotposition 1234567890.01
// Xtr.(IE) - Russell Midcap Registered Shares 1C USD o.N.
// IE00BJZ2DC62 12,729132 26,002300 USD 1,105500 299,40 EUR
.section("name", "isin", "currency").optional()
.find("(Kauf"
+ "|Ansparplan"
+ "|Fondsertrag"
+ "|Verkauf"
+ "|Entgelt Verkauf"
+ "|Entgeltbelastung Verkauf"
+ "|Entnahmeplan"
+ "|Fondsumschichtung \\((Abgang|Zugang)\\)"
+ "|Wiederanlage Fondsertrag [\\.,\\d]+ [\\w]+) .*")
.match("^(?<name>.*)$")
.match("^(?<isin>[\\w]{12}) (\\-)?[\\.,\\d]+ [\\.,\\d]+ (?<currency>[\\w]{3})( [\\.,\\d]+)? [\\.,\\d]+ [\\w]{3}$")
.assign((t, v) -> t.setSecurity(getOrCreateSecurity(v)))
// 444444.09 iSh.ST.Gl.Sel.Div.100 U.ETF DE Inhaber-Anteile (ISIN DE000A0F5UH1)
.section("name", "isin", "currency").optional()
.match("^[\\d]+\\.[\\d]+ (?<name>.*) \\(ISIN (?<isin>[\\w]{12})\\)$$")
.match("^Wiederanlage Ertragsaussch.ttung .* (?<currency>[\\w]{3})$")
.assign((t, v) -> t.setSecurity(getOrCreateSecurity(v)))
.oneOf(
// Ref. Nr. XXXXXXXX/XXXXXXXX, Buchungsdatum 21.11.2019
section -> section
.attributes("date")
.match("^.* Buchungsdatum (?<date>[\\d]{2}\\.[\\d]{2}\\.[\\d]{4})$")
.assign((t, v) -> t.setDate(asDate(v.get("date"))))
,
section -> section
.attributes("date")
.match("^Wiederanlage Ertragsaussch.ttung .* (?<date>[\\d]{2}\\.[\\d]{2}\\.[\\d]{4}) [\\.,\\d]+ [\\.,\\d]+ [\\.,\\d]+ [\\w]{3}$")
.assign((t, v) -> t.setDate(asDate(v.get("date"))))
)
.oneOf(
// IE00BJZ2DC62 12,729132 26,002300 USD 1,105500 299,40 EUR
// LU0592215403 -0,084735 1,824200 USD 1,104100 0,14 EUR
section -> section
.attributes("shares")
.match("^[\\w]{12} (\\-)?(?<shares>[\\.,\\d]+) [\\.,\\d]+ [\\w]{3} [\\.,\\d]+ [\\.,\\d]+ [\\w]{3}$")
.assign((t, v) -> t.setShares(asShares(v.get("shares"))))
,
// FR0010405431 199,500000 1,055800 EUR 210,63 EUR
section -> section
.attributes("shares")
.match("^[\\w]{12} (\\-)?(?<shares>[\\.,\\d]+) [\\.,\\d]+ [\\w]{3} [\\.,\\d]+ [\\w]{3}$")
.assign((t, v) -> t.setShares(asShares(v.get("shares"))))
,
section -> section
.attributes("shares")
.match("^Wiederanlage Ertragsaussch.ttung .* [\\d]{2}\\.[\\d]{2}\\.[\\d]{4} [\\.,\\d]+ (?<shares>[\\.,\\d]+) [\\.,\\d]+ [\\w]{3}")
.assign((t, v) -> t.setShares(asShares(v.get("shares"))))
)
.section("amount", "currency").optional()
.match("^Wiederanlage Ertragsaussch.ttung .* [\\d]{2}\\.[\\d]{2}\\.[\\d]{4} [\\.,\\d]+ [\\.,\\d]+ (?<amount>[\\.,\\d]+) (?<currency>[\\w]{3})")
.assign((t, v) -> {
t.setAmount(asAmount(v.get("amount")));
t.setCurrencyCode(asCurrencyCode(v.get("currency")));
})
// DE49XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX 300,00 EUR
.section("amount", "currency").optional()
.find("Abwicklung über IBAN Institut Zahlungsbetrag")
.match("^.* (?<amount>[\\.,\\d]+) (?<currency>[\\w]{3})$")
.assign((t, v) -> {
t.setAmount(asAmount(v.get("amount")));
t.setCurrencyCode(asCurrencyCode(v.get("currency")));
})
// Zahlungsbetrag 0,37 EUR
.section("amount", "currency").optional()
.match("^Zahlungsbetrag( aus Überweisung)? (?<amount>[\\.,\\d]+) (?<currency>[\\w]{3})$")
.assign((t, v) -> {
t.setAmount(asAmount(v.get("amount")));
t.setCurrencyCode(asCurrencyCode(v.get("currency")));
})
/***
* If we have a "Verkauf wegen Vorabpauschale"
* we set this amount.
*/
// Verkauf wegen Vorabpauschale 0,13 EUR mit Kursdatum 27.01.2020 aus Depotposition XXXXXXXX.02
// abzgl. Steuereinbehalt 0,13 EUR
.section("amount", "currency").optional()
.find("Verkauf wegen Vorabpauschale .*")
.match("^abzgl\\. Steuereinbehalt (?<amount>[\\.,\\d]+) (?<currency>[\\w]{3})$")
.assign((t, v) -> {
t.setAmount(asAmount(v.get("amount")));
t.setCurrencyCode(asCurrencyCode(v.get("currency")));
})
/***
* If we have a "Entgelt Verkauf"
* in which fee are immediately withheld,
* without a separate transaction,
* we first post the sale and then the fee payment.
*/
// Entgelt Verkauf mit Kursdatum 20.12.2017 aus Depotposition 11111111111.01
// VL-Vertragsentgelt inkl. 16 % USt 9,75 EUR
.section("amount", "currency").optional()
.find("Entgelt Verkauf .*")
.match("^(Depotf.hrungsentgelt|VL\\-Vertragsentgelt) inkl\\. .* (?<amount>[\\.,\\d]+) (?<currency>[\\w]{3})$")
.assign((t, v) -> {
t.setAmount(asAmount(v.get("amount")));
t.setCurrencyCode(asCurrencyCode(v.get("currency")));
})
/***
* If we have a "Entgeltbelastung Verkauf"
* in which fee are immediately withheld,
* without a separate transaction,
* we first post the sale and then the fee payment.
*/
// Entgeltbelastung Verkauf 3,00 EUR mit Kursdatum 06.04.2021 aus Depotposition 99999999999.01
// Summe 3,00 EUR
.section("amount", "currency").optional()
.find("Entgeltbelastung Verkauf .*")
.match("^Summe (?<amount>[\\.,\\d]+) (?<currency>[\\w]{3})$")
.match("^(Depotf.hrungsentgelt|VL\\-Vertragsentgelt) inkl\\. .*$")
.assign((t, v) -> {
t.setAmount(asAmount(v.get("amount")));
t.setCurrencyCode(asCurrencyCode(v.get("currency")));
})
// IE00BJZ2DC62 12,729132 26,002300 USD 1,105500 299,40 EUR
// LU0552385295 -0,000268 136,090000 USD 1,216800 0,03 EUR
.section("fxCurrency", "exchangeRate", "gross", "currency").optional()
.match("^[\\w]{12} (\\-)?[\\.,\\d]+ [\\.,\\d]+ (?<fxCurrency>[\\w]{3}) (?<exchangeRate>[\\.,\\d]+) (?<gross>[\\.,\\d]+) (?<currency>[\\w]{3})$")
.assign((t, v) -> {
BigDecimal exchangeRate = asExchangeRate(v.get("exchangeRate"));
if (t.getPortfolioTransaction().getCurrencyCode().contentEquals(asCurrencyCode(v.get("fxCurrency"))))
{
exchangeRate = BigDecimal.ONE.divide(exchangeRate, 10, RoundingMode.HALF_DOWN);
}
type.getCurrentContext().put("exchangeRate", exchangeRate.toPlainString());
Money gross = Money.of(asCurrencyCode(v.get("currency")), asAmount(v.get("gross")));
Money fxGross = Money.of(asCurrencyCode(v.get("fxCurrency")),
BigDecimal.valueOf(gross.getAmount()).multiply(exchangeRate)
.setScale(0, RoundingMode.HALF_UP).longValue());
checkAndSetGrossUnit(gross, fxGross, t, type);
})
.section("note").optional()
.match("^(?<note>verm.genswirksame Leistungen)$")
.assign((t, v) -> t.setNote(v.get("note")))
// Verkauf wegen Vorabpauschale 0,14 EUR mit Kursdatum 27.01.2020 aus Depotposition XXXXXXXXXX.05
.section("note").optional()
.match("^(?<note>Verkauf wegen Vorabpauschale) .*$")
.assign((t, v) -> t.setNote(v.get("note")))
// Wiederanlage Fondsertrag 0,37 EUR mit Kursdatum 20.01.2020 in Depotposition 1234567890.21
.section("note").optional()
.match("^(?<note>Wiederanlage Fondsertrag) .*$")
.assign((t, v) -> t.setNote(v.get("note")))
.section("note").optional()
.match("^(?<note>Wiederanlage Ertragsaussch.ttung) .*$")
.assign((t, v) -> t.setNote(v.get("note")))
// Entgelt Verkauf mit Kursdatum 20.12.2017 aus Depotposition 11111111111.01
.section("note").optional()
.match("^(?<note>Entgelt Verkauf) .*$")
.assign((t, v) -> t.setNote(v.get("note")))
// Entgeltbelastung Verkauf 3,00 EUR mit Kursdatum 06.04.2021 aus Depotposition 99999999999.01
.section("note").optional()
.match("^(?<note>Entgeltbelastung Verkauf) .*$")
.assign((t, v) -> t.setNote(v.get("note")))
.wrap(t -> {
if (type.getCurrentContext().get("skipTransaction") == null)
return new BuySellEntryItem(t);
return null;
});
addTaxesSectionsTransaction(pdfTransaction, type);
addFeesSectionsTransaction(pdfTransaction, type);
}
private void addDividendeTransaction()
{
DocumentType type = new DocumentType("Fondsertrag");
this.addDocumentTyp(type);
Block block = new Block("^Fondsertrag .*$", "^(Zahlungsbetrag nach|Zahlungsbetrag(?! in)|Die Auszahlung|Summe der belasteten) .*$");
type.addBlock(block);
Transaction<AccountTransaction> pdfTransaction = new Transaction<AccountTransaction>()
.subject(() -> {
AccountTransaction entry = new AccountTransaction();
entry.setType(AccountTransaction.Type.DIVIDENDS);
return entry;
});
pdfTransaction
// Vanguard FTSE All-World U.ETF Registered Shares USD Dis.oN
// IE00B3RBWM25 7,332986 0,297309 USD 2,18 USD
.section("name", "isin", "currency")
.find("Fondsertrag .*")
.match("^(?<name>.*)$")
.match("^(?<isin>[\\w]{12}) [\\.,\\d]+ [\\.,\\d]+ (?<currency>[\\w]{3}) [\\.,\\d]+ [\\w]{3}$")
.assign((t, v) -> t.setSecurity(getOrCreateSecurity(v)))
// Ref. Nr. XXXXXXXX/XXXXXXXX, Buchungsdatum 02.01.2020
.section("date")
.match("^.* Buchungsdatum (?<date>[\\d]{2}\\.[\\d]{2}\\.[\\d]{4})$")
.assign((t, v) -> t.setDateTime(asDate(v.get("date"))))
.oneOf(
// IE00BJZ2DC62 12,729132 26,002300 USD 1,105500 299,40 EUR
section -> section
.attributes("shares")
.match("^[\\w]{12} (?<shares>[\\.,\\d]+) [\\.,\\d]+ [\\w]{3} [\\.,\\d]+ [\\.,\\d]+ [\\w]{3}$")
.assign((t, v) -> t.setShares(asShares(v.get("shares"))))
,
// FR0010405431 199,500000 1,055800 EUR 210,63 EUR
section -> section
.attributes("shares")
.match("^[\\w]{12} (?<shares>[\\.,\\d]+) [\\.,\\d]+ [\\w]{3} [\\.,\\d]+ [\\w]{3}$")
.assign((t, v) -> t.setShares(asShares(v.get("shares"))))
)
// DE123 European Bank for Financial Services 0,03 EUR
.section("amount", "currency").optional()
.match("^.* (?<amount>[\\.,\\d]+) (?<currency>[\\w]{3})$")
.match("^Die Auszahlung erfolgt über die oben genannte Bankverbindung.$")
.assign((t, v) -> {
t.setAmount(asAmount(v.get("amount")));
t.setCurrencyCode(asCurrencyCode(v.get("currency")));
})
// Zahlungsbetrag 1,79 USD
.section("amount", "currency").optional()
.match("^Zahlungsbetrag (?<amount>[\\.,\\d]+) (?<currency>[\\w]{3})$")
.assign((t, v) -> {
t.setAmount(asAmount(v.get("amount")));
t.setCurrencyCode(asCurrencyCode(v.get("currency")));
})
.section("amount", "currency").optional()
.match("^Zahlungsbetrag nach W.hrungskonvertierung .* [\\.,\\d]+ (?<amount>[\\.,\\d]+) (?<currency>[\\w]{3})$")
.assign((t, v) -> {
t.setAmount(asAmount(v.get("amount")));
t.setCurrencyCode(asCurrencyCode(v.get("currency")));
})
.section("fxGross", "fxCurrency", "exchangeRate", "gross", "currency").optional()
.match("^Zahlungsbetrag in Fremdw.hrung (?<fxGross>[\\.,\\d]+) (?<fxCurrency>[\\w]{3})$")
.match("^Zahlungsbetrag nach W.hrungskonvertierung .* (?<exchangeRate>[\\.,\\d]+) (?<gross>[\\.,\\d]+) (?<currency>[\\w]{3})$")
.assign((t, v) -> {
BigDecimal exchangeRate = asExchangeRate(v.get("exchangeRate"));
if (t.getCurrencyCode().contentEquals(asCurrencyCode(v.get("fxCurrency"))))
{
exchangeRate = BigDecimal.ONE.divide(exchangeRate, 10, RoundingMode.HALF_DOWN);
}
type.getCurrentContext().put("exchangeRate", exchangeRate.toPlainString());
Money gross = Money.of(asCurrencyCode(v.get("currency")), asAmount(v.get("gross")));
Money fxGross = Money.of(asCurrencyCode(v.get("fxCurrency")), asAmount(v.get("fxGross")));
checkAndSetGrossUnit(gross, fxGross, t, type);
})
// 0,34 EUR 0,01 EUR 0,00 EUR 1,117800 0,39 USD
.section("localCurrency", "exchangeRate").optional()
.match("^[\\.,\\d]+ (?<localCurrency>[\\w]{3}) [\\.,\\d]+ [\\w]{3} [\\.,\\d]+ [\\w]{3} (?<exchangeRate>[\\.,\\d]+) [\\.,\\d]+ [\\w]{3}$")
.assign((t, v) -> {
BigDecimal exchangeRate = asExchangeRate(v.get("exchangeRate"));
if (!t.getCurrencyCode().contentEquals(asCurrencyCode(v.get("localCurrency"))))
{
exchangeRate = BigDecimal.ONE.divide(exchangeRate, 10, RoundingMode.HALF_DOWN);
}
type.getCurrentContext().put("exchangeRate", exchangeRate.toPlainString());
})
.wrap(TransactionItem::new);
addTaxesSectionsTransaction(pdfTransaction, type);
addFeesSectionsTransaction(pdfTransaction, type);
block.set(pdfTransaction);
}
private void addAdvanceTaxTransaction()
{
DocumentType type = new DocumentType("Vorabpauschale zum Stichtag");
this.addDocumentTyp(type);
Transaction<AccountTransaction> pdfTransaction = new Transaction<>();
pdfTransaction.subject(() -> {
AccountTransaction entry = new AccountTransaction();
entry.setType(AccountTransaction.Type.TAXES);
return entry;
});
Block firstRelevantLine = new Block("^Vorabpauschale zum Stichtag .*$");
type.addBlock(firstRelevantLine);
firstRelevantLine.set(pdfTransaction);
pdfTransaction
// Vorabpauschale zum Stichtag 31.12.2019 aus Depotposition XXXXXXXXXX.05
// Xtrackers MSCI Philippines Inhaber-Anteile 1C-USD o.N.
// LU0592215403 0,005674390 EUR
.section("note", "name", "isin", "currency")
.match("^(?<note>Vorabpauschale zum Stichtag [\\d]{2}\\.[\\d]{2}\\.[\\d]{4}) .*$")
.match("^(?<name>.*)$")
.match("^(?<isin>[\\w]{12}) (\\-)?[\\.,\\d]+ (?<currency>[\\w]{3})$")
.assign((t, v) -> {
t.setShares(0L);
t.setSecurity(getOrCreateSecurity(v));
t.setNote(v.get("note"));
})
// Ref. Nr. XXXXXXXXXX/XXXXXXXXXX, Buchungsdatum 24.01.2020
.section("date")
.match("^.* Buchungsdatum (?<date>[\\d]{2}\\.[\\d]{2}\\.[\\d]{4})$")
.assign((t, v) -> t.setDateTime(asDate(v.get("date"))))
.section("currency", "amount").optional()
.match("^Belastung der angefallenen Steuern in H.he von (?<amount>[\\.,\\d]+) (?<currency>[\\w]{3}) .*$")
.assign((t, v) -> {
t.setAmount(asAmount(v.get("amount")));
t.setCurrencyCode(asCurrencyCode(v.get("currency")));
})
.wrap(t -> new TransactionItem(t));
}
private void addFeesWithSecurityTransaction()
{
DocumentType type = new DocumentType("(Entgelt|Entgeltbelastung) Verkauf");
this.addDocumentTyp(type);
Transaction<AccountTransaction> pdfTransaction = new Transaction<>();
pdfTransaction.subject(() -> {
AccountTransaction entry = new AccountTransaction();
entry.setType(AccountTransaction.Type.FEES);
return entry;
});
Block firstRelevantLine = new Block("^(Entgelt|Entgeltbelastung) Verkauf .*$");
type.addBlock(firstRelevantLine);
firstRelevantLine.set(pdfTransaction);
pdfTransaction
// Entgelt Verkauf mit Kursdatum 20.12.2017 aus Depotposition 11111111111.01
// db x-trackers DAX ETF (DR) Inhaber-Anteile 1C o.N.
// LU0274211480 -0,100548 127,228500 EUR 12,79 EUR
.section("name", "isin", "currency").optional()
.find("(Entgelt|Entgeltbelastung) Verkauf .*")
.match("^(?<name>.*)$")
.match("^(?<isin>[\\w]{12}) \\-[\\.,\\d]+ [\\.,\\d]+ (?<currency>[\\w]{3})( [\\.,\\d]+)? [\\.,\\d]+ [\\w]{3}$")
.assign((t, v) -> t.setSecurity(getOrCreateSecurity(v)))
.oneOf(
// IE00BJZ2DC62 -12,729132 26,002300 USD 1,105500 299,40 EUR
section -> section
.attributes("shares")
.match("^[\\w]{12} \\-(?<shares>[\\.,\\d]+) [\\.,\\d]+ [\\w]{3} [\\.,\\d]+ [\\.,\\d]+ [\\w]{3}$")
.assign((t, v) -> t.setShares(asShares(v.get("shares"))))
,
// LU0274211480 -0,100548 127,228500 EUR 12,79 EUR
section -> section
.attributes("shares")
.match("^[\\w]{12} \\-(?<shares>[\\.,\\d]+) [\\.,\\d]+ [\\w]{3} [\\.,\\d]+ [\\w]{3}$")
.assign((t, v) -> t.setShares(asShares(v.get("shares"))))
)
// Ref. Nr. XXXXXXXXXX/XXXXXXXXXX, Buchungsdatum 24.01.2020
.section("date")
.match("^.* Buchungsdatum (?<date>[\\d]{2}\\.[\\d]{2}\\.[\\d]{4})$")
.assign((t, v) -> t.setDateTime(asDate(v.get("date"))))
.section("note", "currency", "amount").optional()
.match("^(?<note>Depotf.hrungsentgelt) inkl\\. .* (?<amount>[\\.,\\d]+) (?<currency>[\\w]{3})$")
.assign((t, v) -> {
t.setAmount(asAmount(v.get("amount")));
t.setCurrencyCode(asCurrencyCode(v.get("currency")));
t.setNote(v.get("note"));
})
// VL-Vertragsentgelt inkl. 16 % USt 9,75 EUR
.section("note", "currency", "amount").optional()
.match("^(?<note>VL\\-Vertragsentgelt) inkl\\. .* (?<amount>[\\.,\\d]+) (?<currency>[\\w]{3})$")
.assign((t, v) -> {
t.setAmount(asAmount(v.get("amount")));
t.setCurrencyCode(asCurrencyCode(v.get("currency")));
t.setNote(v.get("note"));
})
// Entgeltbelastung Verkauf 3,00 EUR mit Kursdatum 06.04.2021 aus Depotposition 99999999999.01
// Summe 3,00 EUR
.section("amount", "currency", "note").optional()
.find("Entgeltbelastung Verkauf .*")
.match("^Summe (?<amount>[\\.,\\d]+) (?<currency>[\\w]{3})$")
.match("^(?<note>Depotf.hrungsentgelt|VL\\-Vertragsentgelt) inkl\\. .*$")
.assign((t, v) -> {
t.setAmount(asAmount(v.get("amount")));
t.setCurrencyCode(asCurrencyCode(v.get("currency")));
t.setNote(v.get("note"));
})
// IE00B4L5Y983 -0,167976 71,243400 USD 1,227400 9,75 EUR
// IE00BJZ2DC62 12,729132 26,002300 USD 1,105500 299,40 EUR
.section("fxCurrency", "exchangeRate", "gross", "currency").optional()
.match("^[\\w]{12} (\\-)?[\\.,\\d]+ [\\.,\\d]+ (?<fxCurrency>[\\w]{3}) (?<exchangeRate>[\\.,\\d]+) (?<gross>[\\.,\\d]+) (?<currency>[\\w]{3})$")
.assign((t, v) -> {
BigDecimal exchangeRate = asExchangeRate(v.get("exchangeRate"));
if (t.getCurrencyCode().contentEquals(asCurrencyCode(v.get("fxCurrency"))))
{
exchangeRate = BigDecimal.ONE.divide(exchangeRate, 10, RoundingMode.HALF_DOWN);
}
type.getCurrentContext().put("exchangeRate", exchangeRate.toPlainString());
Money gross = Money.of(asCurrencyCode(v.get("currency")), asAmount(v.get("gross")));
Money fxGross = Money.of(asCurrencyCode(v.get("fxCurrency")),
BigDecimal.valueOf(gross.getAmount()).multiply(exchangeRate)
.setScale(0, RoundingMode.HALF_UP).longValue());
checkAndSetGrossUnit(gross, fxGross, t, type);
})
.wrap(t -> new TransactionItem(t));
}
private void addDeliveryInOutBoundTransaction()
{
DocumentType type = new DocumentType("Eingang externer .bertrag");
this.addDocumentTyp(type);
Transaction<PortfolioTransaction> pdfTransaction = new Transaction<>();
pdfTransaction.subject(() -> {
PortfolioTransaction entry = new PortfolioTransaction();
entry.setType(PortfolioTransaction.Type.DELIVERY_OUTBOUND);
return entry;
});
Block firstRelevantLine = new Block("^Eingang externer .bertrag .*$", "^Gegenwert der Anteile: .*$");
type.addBlock(firstRelevantLine);
firstRelevantLine.set(pdfTransaction);
pdfTransaction
// Is type --> "Einbuchung" change from DELIVERY_OUTBOUND to DELIVERY_INBOUND
.section("type").optional()
.match("^(?<type>Eingang) externer .bertrag .*$")
.assign((t, v) -> {
if (v.get("type").equals("Eingang"))
{
t.setType(PortfolioTransaction.Type.DELIVERY_INBOUND);
}
})
// ComStage-Nikkei 225 UCITS ET99133507781F Inhaber-Anteile I o.N.
// LU0378453376 10,000000
// Gegenwert der Anteile: 202,64 EU
.section("name", "isin", "currency")
.match("^Eingang externer .bertrag .*$")
.match("^(?<name>.*)$")
.match("^(?<isin>[\\w]{12}) [\\.,\\d]+$")
.match("^Gegenwert der Anteile: [\\.,\\d]+ (?<currency>[\\w]{3})$")
.assign((t, v) -> t.setSecurity(getOrCreateSecurity(v)))
// Ref. Nr. XXXXXXXX/XXXXXXXX, Buchungsdatum 30.09.2019
.section("date")
.match("^.* Buchungsdatum (?<date>[\\d]{2}\\.[\\d]{2}\\.[\\d]{4})$")
.assign((t, v) -> t.setDateTime(asDate(v.get("date"))))
// LU0378453376 10,000000
.section("shares")
.match("^[\\w]{12} (?<shares>[\\.,\\d]+)$")
.assign((t, v) -> t.setShares(asShares(v.get("shares"))))
// Gegenwert der Anteile: 202,64 EUR
.section("amount", "currency")
.match("^Gegenwert der Anteile: (?<amount>[\\,.\\d]+) (?<currency>[\\w]{3})$")
.assign((t, v) -> {
t.setAmount(asAmount(v.get("amount")));
t.setCurrencyCode(asCurrencyCode(v.get("currency")));
})
.wrap(TransactionItem::new);
addTaxesSectionsTransaction(pdfTransaction, type);
addFeesSectionsTransaction(pdfTransaction, type);
}
private <T extends Transaction<?>> void addTaxesSectionsTransaction(T transaction, DocumentType type)
{
transaction
// 0,34 EUR 0,01 EUR 0,00 EUR 1,117800 0,39 USD
.section("tax", "currency").optional()
.find("Kapitalertragsteuer .*")
.match("^(?<tax>[\\.,\\d]+) (?<currency>[\\w]{3}) .*$")
.match("^(Zahlungsbetrag|Abwicklung|Summe der belasteten) .*$")
.assign((t, v) -> processTaxEntries(t, v, type))
// 0,34 EUR 0,01 EUR 0,00 EUR 1,117800 0,39 USD
.section("tax", "currency").optional()
.find(".* Solidarit.tszuschlag .*")
.match("^[\\.,\\d]+ [\\w]{3} (?<tax>[\\.,\\d]+) (?<currency>[\\w]{3}) .*$")
.match("^(Zahlungsbetrag|Abwicklung|Summe der belasteten) .*$")
.assign((t, v) -> processTaxEntries(t, v, type))
// 0,34 EUR 0,01 EUR 0,00 EUR 1,117800 0,39 USD
.section("tax", "currency").optional()
.find(".* Kirchensteuer .*")
.match("^[\\.,\\d]+ [\\w]{3} [\\.,\\d]+ [\\w]{3} (?<tax>[\\.,\\d]+) (?<currency>[\\w]{3}) .*$")
.match("^(Zahlungsbetrag|Abwicklung) .*$")
.assign((t, v) -> processTaxEntries(t, v, type));
}
private <T extends Transaction<?>> void addFeesSectionsTransaction(T transaction, DocumentType type)
{
transaction
// ETF-Transaktionsentgelt 0,60 EUR
.section("fee", "currency").optional()
.match("^ETF\\-Transaktionsentgelt (?<fee>[\\.,\\d]+) (?<currency>[\\w]{3})$")
.match("^(Zahlungsbetrag nach|Zahlungsbetrag(?! in)|Die Auszahlung|Abwicklung|Summe der belasteten) .*$")
.assign((t, v) -> processFeeEntries(t, v, type))
// ETF-Transaktionsentgelt 0,05 EUR 0,00 EUR 0,05 EUR
.section("fee", "currency").optional()
.match("^ETF\\-Transaktionsentgelt (?<fee>[\\.,\\d]+) (?<currency>[\\w]{3}) [\\.,\\d]+ [\\w]{3} [\\.,\\d]+ [\\w]{3}$")
.match("^(Zahlungsbetrag nach|Zahlungsbetrag(?! in)|Die Auszahlung|Abwicklung|Summe der belasteten) .*$")
.assign((t, v) -> processFeeEntries(t, v, type))
// gezahlte Vertriebsprovision 0,00 EUR (im Abrechnungskurs enthalten, 100,000 % Bonus)
.section("fee", "currency").optional()
.match("^gezahlte Vertriebsprovision (?<fee>[\\.,\\d]+) (?<currency>[\\w]{3}) .*$")
.match("^(Zahlungsbetrag nach|Zahlungsbetrag(?! in)|Die Auszahlung|Abwicklung|Summe der belasteten) .*$")
.assign((t, v) -> processFeeEntries(t, v, type))
// Additional Trading Costs (ATC) 0,13 EUR
.section("fee", "currency").optional()
.match("^Additional Trading Costs \\(ATC\\) (?<fee>[\\.,\\d]+) (?<currency>[\\w]{3})$")
.match("^(Zahlungsbetrag nach|Zahlungsbetrag(?! in)|Die Auszahlung|Abwicklung|Summe der belasteten) .*$")
.assign((t, v) -> processFeeEntries(t, v, type));
}
}
|
package name.abuchen.portfolio.online.portfolioreport;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.osgi.framework.FrameworkUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializer;
import com.google.gson.reflect.TypeToken;
import name.abuchen.portfolio.json.JClient;
import name.abuchen.portfolio.online.impl.PortfolioReportNet;
import name.abuchen.portfolio.util.WebAccess;
@SuppressWarnings("nls")
public class PRApiClient
{
private static final String ENDPOINT = "https://api.portfolio-report.net";
private CloseableHttpClient client;
private Gson gson;
public PRApiClient(String token)
{
List<Header> headers = new ArrayList<>();
headers.add(new BasicHeader("Authorization", "Bearer " + token));
headers.add(new BasicHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()));
headers.add(new BasicHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.toString()));
this.client = HttpClientBuilder.create()
.setDefaultRequestConfig(WebAccess.defaultRequestConfig)
.setDefaultHeaders(headers)
.setUserAgent("PortfolioPerformance/"
+ FrameworkUtil.getBundle(PortfolioReportNet.class).getVersion().toString())
.useSystemProperties()
.build();
this.gson = new GsonBuilder()
.registerTypeAdapter(Instant.class, (JsonSerializer<Instant>) (instant, type,
jsonSerializationContext) -> new JsonPrimitive(instant.toString()))
.registerTypeAdapter(Instant.class,
(JsonDeserializer<Instant>) (json, type, jsonDeserializationContext) -> Instant
.parse(json.getAsJsonPrimitive().getAsString()))
.create();
}
public List<PRPortfolio> listPortfolios() throws IOException
{
return list(PRPortfolio.class, "/portfolios");
}
public PRPortfolio createPortfolio(PRPortfolio portfolio) throws IOException
{
return create(PRPortfolio.class, "/portfolios", portfolio);
}
public List<PRSecurity> listSecurities(long portfolioId) throws IOException
{
return list(PRSecurity.class, "/portfolios/" + portfolioId + "/securities");
}
public PRSecurity updateSecurity(long portfolioId, PRSecurity security) throws IOException
{
return update(PRSecurity.class, "/portfolios/" + portfolioId + "/securities/" + security.getUuid(), security);
}
public PRSecurity deleteSecurity(long portfolioId, PRSecurity security) throws IOException
{
return deleteEntity(PRSecurity.class, "/portfolios/" + portfolioId + "/securities/" + security.getUuid());
}
public List<PRAccount> listAccounts(long portfolioId) throws IOException
{
return list(PRAccount.class, "/portfolios/" + portfolioId + "/accounts");
}
public PRAccount updateAccount(long portfolioId, PRAccount account) throws IOException
{
return update(PRAccount.class, "/portfolios/" + portfolioId + "/accounts/" + account.getUuid(), account);
}
public PRAccount deleteAccount(long portfolioId, PRAccount account) throws IOException
{
return deleteEntity(PRAccount.class, "/portfolios/" + portfolioId + "/accounts/" + account.getUuid());
}
public List<PRTransaction> listTransactions(long portfolioId) throws IOException
{
return list(PRTransaction.class, "/portfolios/" + portfolioId + "/transactions");
}
public PRTransaction updateTransaction(long portfolioId, PRTransaction transaction) throws IOException
{
return update(PRTransaction.class, "/portfolios/" + portfolioId + "/transactions/" + transaction.getUuid(),
transaction);
}
public PRTransaction deleteTransaction(long portfolioId, PRTransaction transaction) throws IOException
{
return deleteEntity(PRTransaction.class,
"/portfolios/" + portfolioId + "/transactions/" + transaction.getUuid());
}
private <T> List<T> list(Class<T> type, String path) throws IOException
{
HttpGet request = new HttpGet(ENDPOINT + path);
CloseableHttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
throw asError(request, response, null);
return this.gson.fromJson(EntityUtils.toString(response.getEntity()),
TypeToken.getParameterized(List.class, type).getType());
}
private <T> T create(Class<T> type, String path, T input) throws IOException
{
HttpPost request = new HttpPost(ENDPOINT + path);
request.setEntity(new StringEntity(this.gson.toJson(input), StandardCharsets.UTF_8));
CloseableHttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED)
throw asError(request, response, EntityUtils.toString(request.getEntity()));
return this.gson.fromJson(EntityUtils.toString(response.getEntity()), type);
}
private <T> T update(Class<T> type, String path, T input) throws IOException
{
HttpPut request = new HttpPut(ENDPOINT + path);
request.setEntity(new StringEntity(this.gson.toJson(input), StandardCharsets.UTF_8));
CloseableHttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
throw asError(request, response, EntityUtils.toString(request.getEntity()));
return this.gson.fromJson(EntityUtils.toString(response.getEntity()), type);
}
private <T> T deleteEntity(Class<T> type, String path) throws IOException
{
HttpDelete request = new HttpDelete(ENDPOINT + path);
CloseableHttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
throw asError(request, response, null);
return this.gson.fromJson(EntityUtils.toString(response.getEntity()), type);
}
private IOException asError(HttpRequestBase request, CloseableHttpResponse response, String requestBody)
throws IOException
{
return new IOException(request.toString() + " --> " + response.getStatusLine().getStatusCode() + "\n\n"
+ (requestBody != null ? requestBody + "\n\n" : "")
+ EntityUtils.toString(response.getEntity()));
}
}
|
package com.x.base.core.project.config;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.x.base.core.project.annotation.FieldDescribe;
import com.x.base.core.project.gson.XGsonBuilder;
import com.x.base.core.project.tools.DefaultCharset;
import com.x.base.core.project.tools.ListTools;
import org.apache.commons.io.FileUtils;
public class Components extends ConfigObject {
public static final String NAME_SETTING = "Setting";
public static final String NAME_ORG = "Org";
public static final String NAME_CMSMANAGER = "cmsManager";
public static final String NAME_APPLICATIONEXPLORER = "ApplicationExplorer";
public static final String NAME_PORTALEXPLORER = "PortalExplorer";
public static final String NAME_DATAEXPLORER = "DataExplorer";
public static final String NAME_SERVICEMANAGER = "service.ServiceManager";
public static final String NAME_APPMARKET = "AppMarketV2";
public static final String NAME_APPCENTER = "AppCenter";
public static final String NAME_LOGVIEWER = "LogViewer";
public static final String NAME_PROFILE = "Profile";
public static final String NAME_BAM = "BAM";
public static final String NAME_CMS = "cms";
public static final String NAME_TASKCENTER = "TaskCenter";
public static final String NAME_HOMEPAGE = "Homepage";
public static final String NAME_HOTARTICLE = "HotArticle";
public static final String NAME_FILE = "File";
public static final String NAME_NOTE = "Note";
public static final String NAME_MEETING = "Meeting";
public static final String NAME_ONLINEMEETING = "OnlineMeeting";
public static final String NAME_ATTENDANCE = "Attendance";
public static final String NAME_FORUM = "Forum";
public static final String NAME_MINDER = "Minder";
public static final String NAME_CALENDAR = "Calendar";
public static final String NAME_ANN = "ANN";
public static final String NAME_SEARCH = "Search";
public static List<String> SYSTEM_NAME_NAMES = ListTools.toList(NAME_SETTING, NAME_ORG, NAME_CMSMANAGER,
NAME_APPLICATIONEXPLORER, NAME_PORTALEXPLORER, NAME_DATAEXPLORER, NAME_SERVICEMANAGER, NAME_APPMARKET,
NAME_APPCENTER, NAME_LOGVIEWER, NAME_PROFILE, NAME_BAM, NAME_CMS, NAME_TASKCENTER, NAME_HOMEPAGE,
NAME_HOTARTICLE, NAME_FILE, NAME_NOTE, NAME_MEETING, NAME_ONLINEMEETING, NAME_ATTENDANCE, NAME_FORUM,
NAME_MINDER, NAME_CALENDAR, NAME_ANN, NAME_SEARCH);
public static final String APPICON_PNG = "appicon.png";
public static Component systemComponent(String name) {
switch (name) {
case NAME_SETTING:
return new Component(NAME_SETTING, NAME_SETTING, "", APPICON_PNG, 1, Component.TYPE_SYSTEM);
case NAME_ORG:
return new Component(NAME_ORG, NAME_ORG, "", APPICON_PNG, 2, Component.TYPE_SYSTEM);
case NAME_CMSMANAGER:
return new Component(NAME_CMSMANAGER, "cms.Column", "", APPICON_PNG, 3, Component.TYPE_SYSTEM);
case NAME_APPLICATIONEXPLORER:
return new Component(NAME_APPLICATIONEXPLORER, "process.ApplicationExplorer", "", APPICON_PNG, 4,
Component.TYPE_SYSTEM);
case NAME_PORTALEXPLORER:
return new Component(NAME_PORTALEXPLORER, "portal.PortalExplorer", "", APPICON_PNG, 5,
Component.TYPE_SYSTEM);
case NAME_DATAEXPLORER:
return new Component(NAME_DATAEXPLORER, "query.QueryExplorer", "", APPICON_PNG, 6,
Component.TYPE_SYSTEM);
case NAME_SERVICEMANAGER:
return new Component(NAME_SERVICEMANAGER, NAME_SERVICEMANAGER, "", APPICON_PNG, 7,
Component.TYPE_SYSTEM);
case NAME_APPMARKET:
return new Component(NAME_APPMARKET, NAME_APPMARKET, "", APPICON_PNG, 8, Component.TYPE_SYSTEM);
case NAME_APPCENTER:
return new Component(NAME_APPCENTER, NAME_APPCENTER, "", APPICON_PNG, 9, Component.TYPE_SYSTEM);
case NAME_LOGVIEWER:
return new Component(NAME_LOGVIEWER, NAME_LOGVIEWER, "", APPICON_PNG, 10, Component.TYPE_SYSTEM);
case NAME_PROFILE:
return new Component(NAME_PROFILE, NAME_PROFILE, "", APPICON_PNG, 11, Component.TYPE_SYSTEM);
case NAME_BAM:
return new Component(NAME_BAM, NAME_BAM, "", APPICON_PNG, 12, Component.TYPE_SYSTEM);
case NAME_CMS:
return new Component(NAME_CMS, "cms.Index", "", APPICON_PNG, 12, Component.TYPE_SYSTEM);
case NAME_TASKCENTER:
return new Component(NAME_TASKCENTER, "process.TaskCenter", "", APPICON_PNG, 13, Component.TYPE_SYSTEM);
case NAME_HOMEPAGE:
return new Component(NAME_HOMEPAGE, NAME_HOMEPAGE, "", APPICON_PNG, 14, Component.TYPE_SYSTEM);
case NAME_HOTARTICLE:
return new Component(NAME_HOTARTICLE, NAME_HOTARTICLE, "", APPICON_PNG, 15, Component.TYPE_SYSTEM);
case NAME_FILE:
return new Component(NAME_FILE, NAME_FILE, "", APPICON_PNG, 16, Component.TYPE_SYSTEM);
case NAME_NOTE:
return new Component(NAME_NOTE, NAME_NOTE, "", APPICON_PNG, 17, Component.TYPE_SYSTEM);
case NAME_MEETING:
return new Component(NAME_MEETING, NAME_MEETING, "", APPICON_PNG, 18, Component.TYPE_SYSTEM);
case NAME_ONLINEMEETING:
return new Component(NAME_ONLINEMEETING, NAME_ONLINEMEETING, "", APPICON_PNG, 19,
Component.TYPE_SYSTEM);
case NAME_ATTENDANCE:
return new Component(NAME_ATTENDANCE, NAME_ATTENDANCE, "", APPICON_PNG, 20, Component.TYPE_SYSTEM);
case NAME_FORUM:
return new Component(NAME_FORUM, NAME_FORUM, "", APPICON_PNG, 21, Component.TYPE_SYSTEM);
case NAME_MINDER:
return new Component(NAME_MINDER, NAME_MINDER, "", APPICON_PNG, 22, Component.TYPE_SYSTEM);
case NAME_CALENDAR:
return new Component(NAME_CALENDAR, NAME_CALENDAR, "", APPICON_PNG, 23, Component.TYPE_SYSTEM);
case NAME_ANN:
return new Component(NAME_ANN, NAME_ANN, "", APPICON_PNG, 24, Component.TYPE_SYSTEM);
case NAME_SEARCH:
return new Component(NAME_SEARCH, NAME_SEARCH, "", APPICON_PNG, 25, Component.TYPE_SYSTEM);
default:
return null;
}
}
public static Components defaultInstance() {
Components o = new Components();
o.systems.add(systemComponent(NAME_SETTING));
o.systems.add(systemComponent(NAME_ORG));
o.systems.add(systemComponent(NAME_CMSMANAGER));
o.systems.add(systemComponent(NAME_CMS));
o.systems.add(systemComponent(NAME_APPLICATIONEXPLORER));
o.systems.add(systemComponent(NAME_PORTALEXPLORER));
o.systems.add(systemComponent(NAME_DATAEXPLORER));
o.systems.add(systemComponent(NAME_SERVICEMANAGER));
o.systems.add(systemComponent(NAME_APPMARKET));
o.systems.add(systemComponent(NAME_APPCENTER));
o.systems.add(systemComponent(NAME_LOGVIEWER));
o.systems.add(systemComponent(NAME_PROFILE));
o.systems.add(systemComponent(NAME_BAM));
o.systems.add(systemComponent(NAME_TASKCENTER));
o.systems.add(systemComponent(NAME_HOMEPAGE));
o.systems.add(systemComponent(NAME_HOTARTICLE));
o.systems.add(systemComponent(NAME_FILE));
o.systems.add(systemComponent(NAME_NOTE));
o.systems.add(systemComponent(NAME_MEETING));
o.systems.add(systemComponent(NAME_ONLINEMEETING));
o.systems.add(systemComponent(NAME_ATTENDANCE));
o.systems.add(systemComponent(NAME_FORUM));
o.systems.add(systemComponent(NAME_MINDER));
o.systems.add(systemComponent(NAME_CALENDAR));
o.systems.add(systemComponent(NAME_ANN));
o.systems.add(systemComponent(NAME_SEARCH));
return o;
}
@FieldDescribe("")
private List<Component> systems = new ArrayList<>();
public Components() {
// nothing
}
public void save() throws Exception {
File file = new File(Config.base(), Config.PATH_CONFIG_PORTAL);
FileUtils.write(file, XGsonBuilder.toJson(this), DefaultCharset.charset);
}
public static class Component {
public static final String TYPE_SYSTEM = "system";
public static final String TYPE_CUSTOM = "custom";
public Component() {
}
public Component(String name, String path, String title, String iconPath, Integer orderNumber, String type) {
this.name = name;
this.path = path;
this.title = title;
this.iconPath = iconPath;
this.orderNumber = orderNumber;
this.type = type;
}
@FieldDescribe("")
private String name;
@FieldDescribe("")
private String path;
@FieldDescribe("")
private String title;
@FieldDescribe("iconPath")
private String iconPath;
@FieldDescribe("")
private Integer orderNumber;
@FieldDescribe("")
private String type;
@FieldDescribe(",person,role")
private List<String> allowList = new ArrayList<>();
@FieldDescribe(",person,role")
private List<String> dentyList = new ArrayList<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIconPath() {
return iconPath;
}
public void setIconPath(String iconPath) {
this.iconPath = iconPath;
}
public List<String> getAllowList() {
return allowList;
}
public void setAllowList(List<String> allowList) {
this.allowList = allowList;
}
public List<String> getDentyList() {
return dentyList;
}
public void setDentyList(List<String> dentyList) {
this.dentyList = dentyList;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Integer getOrderNumber() {
return orderNumber;
}
public void setOrderNumber(Integer orderNumber) {
this.orderNumber = orderNumber;
}
}
public List<Component> getSystems() {
return systems;
}
public void setSystems(List<Component> systems) {
this.systems = systems;
}
}
|
package org.gbif.occurrence.search.es;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.*;
import com.vividsolutions.jts.geom.*;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.common.geo.ShapeRelation;
import org.elasticsearch.common.geo.builders.*;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.gbif.api.model.common.paging.Pageable;
import org.gbif.api.model.occurrence.search.OccurrenceSearchParameter;
import org.gbif.api.model.occurrence.search.OccurrenceSearchRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import static org.gbif.api.util.SearchTypeValidator.isRange;
import static org.gbif.occurrence.search.es.EsQueryUtils.SEARCH_TO_ES_MAPPING;
import static org.gbif.occurrence.search.es.EsQueryUtils.RANGE_SEPARATOR;
public class EsSearchRequestBuilder {
// TODO: sorting!!
private EsSearchRequestBuilder() {}
public static SearchRequest buildSearchRequest(
OccurrenceSearchRequest searchRequest,
boolean facetsEnabled,
int maxOffset,
int maxLimit,
String index) {
SearchRequest esRequest = new SearchRequest();
esRequest.indices(index);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
esRequest.source(searchSourceBuilder);
// size and offset
searchSourceBuilder.size(Math.min(searchRequest.getLimit(), maxLimit));
searchSourceBuilder.from((int) Math.min(maxOffset, searchRequest.getOffset()));
// group params
GroupedParams groupedParams = groupParameters(searchRequest);
// add query
buildQuery(groupedParams.queryParams).ifPresent(searchSourceBuilder::query);
// add aggs
buildAggs(searchRequest, groupedParams.postFilterParams, facetsEnabled)
.ifPresent(aggsList -> aggsList.forEach(searchSourceBuilder::aggregation));
// post-filter
buildPostFilter(groupedParams.postFilterParams).ifPresent(searchSourceBuilder::postFilter);
return esRequest;
}
@VisibleForTesting
static GroupedParams groupParameters(OccurrenceSearchRequest searchRequest) {
GroupedParams groupedParams = new GroupedParams();
if (!searchRequest.isMultiSelectFacets()
|| searchRequest.getFacets() == null
|| searchRequest.getFacets().isEmpty()) {
groupedParams.queryParams = searchRequest.getParameters();
return groupedParams;
}
groupedParams.queryParams = ArrayListMultimap.create();
groupedParams.postFilterParams = ArrayListMultimap.create();
searchRequest
.getParameters()
.asMap()
.forEach(
(k, v) -> {
if (searchRequest.getFacets().contains(k)) {
groupedParams.postFilterParams.putAll(k, v);
} else {
groupedParams.queryParams.putAll(k, v);
}
});
return groupedParams;
}
private static Optional<QueryBuilder> buildPostFilter(
Multimap<OccurrenceSearchParameter, String> postFilterParams) {
if (postFilterParams == null || postFilterParams.isEmpty()) {
return Optional.empty();
}
BoolQueryBuilder bool = QueryBuilders.boolQuery();
postFilterParams
.asMap()
.entrySet()
.stream()
.flatMap(
e ->
buildTermQuery(e.getValue(), e.getKey(), SEARCH_TO_ES_MAPPING.get(e.getKey()))
.stream())
.forEach(q -> bool.filter().add(q));
return Optional.of(bool);
}
private static Optional<List<AggregationBuilder>> buildAggs(
OccurrenceSearchRequest searchRequest,
Multimap<OccurrenceSearchParameter, String> postFilterParams,
boolean facetsEnabled) {
if (!facetsEnabled
|| searchRequest.getFacets() == null
|| searchRequest.getFacets().isEmpty()) {
return Optional.empty();
}
if (searchRequest.isMultiSelectFacets()
&& postFilterParams != null
&& !postFilterParams.isEmpty()) {
return Optional.of(buildFacetsMultiselect(searchRequest, postFilterParams));
}
return Optional.of(buildFacets(searchRequest));
}
private static List<AggregationBuilder> buildFacetsMultiselect(
OccurrenceSearchRequest searchRequest,
Multimap<OccurrenceSearchParameter, String> postFilterParams) {
if (searchRequest.getFacets().size() == 1) {
// same case as normal facets
return buildFacets(searchRequest);
}
return searchRequest
.getFacets()
.stream()
.filter(p -> SEARCH_TO_ES_MAPPING.get(p) != null)
.map(
facetParam -> {
// build filter aggs
BoolQueryBuilder bool = QueryBuilders.boolQuery();
postFilterParams
.asMap()
.entrySet()
.stream()
.filter(entry -> entry.getKey() != facetParam)
.flatMap(
e ->
buildTermQuery(
e.getValue(), e.getKey(), SEARCH_TO_ES_MAPPING.get(e.getKey()))
.stream())
.forEach(q -> bool.filter().add(q));
// add filter to the aggs
OccurrenceEsField esField = SEARCH_TO_ES_MAPPING.get(facetParam);
FilterAggregationBuilder filterAggs =
AggregationBuilders.filter(esField.getFieldName(), bool);
// build terms aggs and add it to the filter aggs
TermsAggregationBuilder termsAggs =
buildTermsAggs(
"filtered_" + esField.getFieldName(),
esField,
searchRequest.getFacetPage(facetParam),
searchRequest.getFacetMinCount());
filterAggs.subAggregation(termsAggs);
return filterAggs;
})
.collect(Collectors.toList());
}
private static List<AggregationBuilder> buildFacets(OccurrenceSearchRequest searchRequest) {
return searchRequest
.getFacets()
.stream()
.filter(p -> SEARCH_TO_ES_MAPPING.get(p) != null)
.map(
facetParam -> {
OccurrenceEsField esField = SEARCH_TO_ES_MAPPING.get(facetParam);
return buildTermsAggs(
esField.getFieldName(),
esField,
searchRequest.getFacetPage(facetParam),
searchRequest.getFacetMinCount());
})
.collect(Collectors.toList());
}
private static TermsAggregationBuilder buildTermsAggs(
String aggsName, OccurrenceEsField esField, Pageable facetPage, Integer minCount) {
TermsAggregationBuilder termsAggsBuilder =
AggregationBuilders.terms(aggsName).field(esField.getFieldName());
Optional.ofNullable(facetPage).ifPresent(p -> termsAggsBuilder.size(p.getLimit()));
Optional.ofNullable(minCount).ifPresent(termsAggsBuilder::minDocCount);
// TODO: offset not supported in ES. Implement workaround
return termsAggsBuilder;
}
public static Optional<QueryBuilder> buildQuery(
Multimap<OccurrenceSearchParameter, String> params) {
// get query params
if (params == null || params.isEmpty()) {
return Optional.empty();
}
// create bool node
BoolQueryBuilder bool = QueryBuilders.boolQuery();
// adding geometry to bool
if (params.containsKey(OccurrenceSearchParameter.GEOMETRY)) {
BoolQueryBuilder shouldGeometry = QueryBuilders.boolQuery();
params
.get(OccurrenceSearchParameter.GEOMETRY)
.forEach(wkt -> shouldGeometry.should().add(buildGeoShapeQuery(wkt)));
bool.filter().add(shouldGeometry);
}
// adding term queries to bool
params
.asMap()
.entrySet()
.stream()
.filter(e -> Objects.nonNull(SEARCH_TO_ES_MAPPING.get(e.getKey())))
.flatMap(
e ->
buildTermQuery(e.getValue(), e.getKey(), SEARCH_TO_ES_MAPPING.get(e.getKey()))
.stream())
.forEach(q -> bool.filter().add(q));
return Optional.of(bool);
}
private static List<QueryBuilder> buildTermQuery(
Collection<String> values, OccurrenceSearchParameter param, OccurrenceEsField esField) {
List<QueryBuilder> queries = new ArrayList<>();
// collect queries for each value
List<String> parsedValues = new ArrayList<>();
for (String value : values) {
if (isRange(value)) {
queries.add(buildRangeQuery(esField, value));
} else if (param.type() != Date.class) {
if (Enum.class.isAssignableFrom(param.type())) { // enums are capitalized
value = value.toUpperCase();
}
parsedValues.add(value);
}
}
if (parsedValues.size() == 1) {
// single term
queries.add(QueryBuilders.termQuery(esField.getFieldName(), parsedValues.get(0)));
} else if (parsedValues.size() > 1) {
// multi term query
queries.add(QueryBuilders.termsQuery(esField.getFieldName(), parsedValues));
}
return queries;
}
private static RangeQueryBuilder buildRangeQuery(OccurrenceEsField esField, String value) {
String[] values = value.split(RANGE_SEPARATOR);
return QueryBuilders.rangeQuery(esField.getFieldName())
.gte(Double.valueOf(values[0]))
.lte(Double.valueOf(values[1]));
}
private static GeoShapeQueryBuilder buildGeoShapeQuery(String wkt) {
Geometry geometry;
try {
geometry = new WKTReader().read(wkt);
} catch (ParseException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
Function<Polygon, PolygonBuilder> polygonToBuilder =
polygon -> {
PolygonBuilder polygonBuilder =
ShapeBuilders.newPolygon(Arrays.asList(polygon.getExteriorRing().getCoordinates()));
for (int i = 0; i < polygon.getNumInteriorRing(); i++) {
polygonBuilder.hole(
ShapeBuilders.newLineString(
Arrays.asList(polygon.getInteriorRingN(i).getCoordinates())));
}
return polygonBuilder;
};
String type =
"LinearRing".equals(geometry.getGeometryType())
? "LINESTRING"
: geometry.getGeometryType().toUpperCase();
ShapeBuilder shapeBuilder = null;
if (("POINT").equals(type)) {
shapeBuilder = ShapeBuilders.newPoint(geometry.getCoordinate());
} else if ("LINESTRING".equals(type)) {
shapeBuilder = ShapeBuilders.newLineString(Arrays.asList(geometry.getCoordinates()));
} else if ("POLYGON".equals(type)) {
shapeBuilder = polygonToBuilder.apply((Polygon) geometry);
} else if ("MULTIPOLYGON".equals(type)) {
// multipolygon
MultiPolygonBuilder multiPolygonBuilder = ShapeBuilders.newMultiPolygon();
for (int i = 0; i < geometry.getNumGeometries(); i++) {
multiPolygonBuilder.polygon(polygonToBuilder.apply((Polygon) geometry.getGeometryN(i)));
}
shapeBuilder = multiPolygonBuilder;
} else {
throw new IllegalArgumentException(type + " shape is not supported");
}
try {
return QueryBuilders.geoShapeQuery(
OccurrenceEsField.COORDINATE_SHAPE.getFieldName(), shapeBuilder)
.relation(ShapeRelation.WITHIN);
} catch (IOException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
static class GroupedParams {
Multimap<OccurrenceSearchParameter, String> postFilterParams;
Multimap<OccurrenceSearchParameter, String> queryParams;
}
}
|
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.io.File;
import org.opensim.modeling.*;
class TestTables {
public static void test_DataTable() {
DataTable table = new DataTable();
// Set column labels.
StdVectorString labels = new StdVectorString();
labels.add("0"); labels.add("1"); labels.add("2"); labels.add("3");
table.setColumnLabels(labels);
assert table.getColumnLabels().size() == 4;
assert table.getColumnLabel(0).equals("0");
assert table.getColumnLabel(1).equals("1");
assert table.getColumnLabel(2).equals("2");
assert table.getColumnLabel(3).equals("3");
assert table.hasColumn("2");
assert !table.hasColumn("not-found");
table.setColumnLabel(0, "zero");
table.setColumnLabel(2, "two");
assert table.getColumnLabel(0).equals("zero");
assert table.getColumnLabel(2).equals("two");
assert table.getColumnIndex("zero") == 0;
assert table.getColumnIndex("two") == 2;
// Append row to the table.
RowVector row = new RowVector(4, 1);
table.appendRow(0.1, row);
assert table.getNumRows() == 1;
assert table.getNumColumns() == 4;
RowVectorView row0 = table.getRowAtIndex(0);
assert row0.get(0) == 1 &&
row0.get(1) == 1 &&
row0.get(2) == 1 &&
row0.get(3) == 1;
System.out.println(table);
// Append another row to table.
row.set(0, 2); row.set(1, 2); row.set(2, 2); row.set(3, 2);
table.appendRow(0.2, row);
assert table.getNumRows() == 2;
assert table.getNumColumns() == 4;
RowVectorView row1 = table.getRow(0.2);
assert row1.get(0) == 2 &&
row1.get(1) == 2 &&
row1.get(2) == 2 &&
row1.get(3) == 2;
System.out.println(table);
// Append another row to table.
row.set(0, 3); row.set(1, 3); row.set(2, 3); row.set(3, 3);
table.appendRow(0.3, row);
assert table.getNumRows() == 3;
assert table.getNumColumns() == 4;
RowVectorView row2 = table.getRow(0.3);
assert row2.get(0) == 3 &&
row2.get(1) == 3 &&
row2.get(2) == 3 &&
row2.get(3) == 3;
System.out.println(table);
// Get independent column.
StdVectorDouble indCol = table.getIndependentColumn();
assert indCol.get(0) == 0.1 &&
indCol.get(1) == 0.2 &&
indCol.get(2) == 0.3;
// Get dependent column.
VectorView col1 = table.getDependentColumnAtIndex(1);
assert col1.get(0) == 1 &&
col1.get(1) == 2 &&
col1.get(2) == 3;
VectorView col3 = table.getDependentColumnAtIndex(3);
assert col3.get(0) == 1 &&
col3.get(1) == 2 &&
col3.get(2) == 3;
assert table.hasColumn(0);
assert table.hasColumn(2);
// Edit rows of the table.
row0 = table.getRowAtIndex(0);
row0.set(0, 10); row0.set(1, 10); row0.set(2, 10); row0.set(3, 10);
assert table.getRowAtIndex(0).get(0) == 10 &&
table.getRowAtIndex(0).get(1) == 10 &&
table.getRowAtIndex(0).get(2) == 10 &&
table.getRowAtIndex(0).get(3) == 10;
row2 = table.getRow(0.3);
row2.set(0, 20); row2.set(1, 20); row2.set(2, 20); row2.set(3, 20);
assert table.getRowAtIndex(2).get(0) == 20 &&
table.getRowAtIndex(2).get(1) == 20 &&
table.getRowAtIndex(2).get(2) == 20 &&
table.getRowAtIndex(2).get(3) == 20;
System.out.println(table);
// Edit columns of the table.
VectorView col0 = table.getDependentColumnAtIndex(0);
col0.set(0, 30); col0.set(1, 30); col0.set(2, 30);
assert table.getDependentColumnAtIndex(0).get(0) == 30 &&
table.getDependentColumnAtIndex(0).get(1) == 30 &&
table.getDependentColumnAtIndex(0).get(2) == 30;
col3 = table.getDependentColumn("3");
col3.set(0, 40); col3.set(1, 40); col3.set(2, 40);
assert table.getDependentColumn("3").get(0) == 40 &&
table.getDependentColumn("3").get(1) == 40 &&
table.getDependentColumn("3").get(2) == 40;
System.out.println(table);
// Add table metadata.
table.addTableMetaDataString("subject-name", "Java");
table.addTableMetaDataString("subject-yob" , "1995");
assert table.getTableMetaDataString("subject-name").equals("Java");
assert table.getTableMetaDataString("subject-yob" ).equals("1995");
System.out.println(table);
// Access element with index out of bounds. Exception expected.
try {
double shouldThrow = row0.get(4);
assert false;
} catch (java.lang.RuntimeException exc) {}
try {
double shouldThrow = col1.get(5);
assert false;
} catch (java.lang.RuntimeException exc) {}
// Access row with index/time out of bounds. Exception expected.
try {
RowVectorView shouldThrow = table.getRowAtIndex(5);
assert false;
} catch (java.lang.RuntimeException exc) {}
try {
RowVectorView shouldThrow = table.getRow(5.5);
assert false;
} catch (java.lang.RuntimeException exc) {}
// Access column with index/label out of bounds. Exception expected.
try {
VectorView shouldThrow = table.getDependentColumnAtIndex(5);
assert false;
} catch (java.lang.RuntimeException exc) {}
try {
VectorView shouldThrow = table.getDependentColumn("not-found");
assert false;
} catch (java.lang.RuntimeException exc) {}
// Test pack-ing of columns of DataTable.
table = new DataTable();
labels = new StdVectorString();
labels.add("col0_x"); labels.add("col0_y"); labels.add("col0_z");
labels.add("col1_x"); labels.add("col1_y"); labels.add("col1_z");
labels.add("col2_x"); labels.add("col2_y"); labels.add("col2_z");
labels.add("col3_x"); labels.add("col3_y"); labels.add("col3_z");
table.setColumnLabels(labels);
row = new RowVector(12, 1);
table.appendRow(1, row);
row = new RowVector(12, 2);
table.appendRow(2, row);
row = new RowVector(12, 3);
table.appendRow(3, row);
assert table.getColumnLabels().size() == 12;
assert table.getNumRows() == 3;
assert table.getNumColumns() == 12;
System.out.println(table);
StdVectorString suffixes = new StdVectorString();
suffixes.add("_x"); suffixes.add("_y"); suffixes.add("_z");
DataTableVec3 tableVec3 = table.packVec3(suffixes);
assert tableVec3.getColumnLabel(0).equals("col0");
assert tableVec3.getColumnLabel(1).equals("col1");
assert tableVec3.getColumnLabel(2).equals("col2");
assert tableVec3.getColumnLabel(3).equals("col3");
assert tableVec3.getNumRows() == 3;
assert tableVec3.getNumColumns() == 4;
System.out.println(tableVec3);
tableVec3 = table.packVec3();
assert tableVec3.getColumnLabel(0).equals("col0");
assert tableVec3.getColumnLabel(1).equals("col1");
assert tableVec3.getColumnLabel(2).equals("col2");
assert tableVec3.getColumnLabel(3).equals("col3");
assert tableVec3.getNumRows() == 3;
assert tableVec3.getNumColumns() == 4;
System.out.println(tableVec3);
DataTable tableFlat = tableVec3.flatten();
assert tableFlat.getColumnLabels().size() == 12;
assert tableFlat.getColumnLabel( 0).equals("col0_1");
assert tableFlat.getColumnLabel(11).equals("col3_3");
assert tableFlat.getNumRows() == 3;
assert tableFlat.getNumColumns() == 12;
System.out.println(tableFlat);
DataTableUnitVec3 tableUnitVec3 = table.packUnitVec3();
assert tableUnitVec3.getColumnLabel(0).equals("col0");
assert tableUnitVec3.getColumnLabel(1).equals("col1");
assert tableUnitVec3.getColumnLabel(2).equals("col2");
assert tableUnitVec3.getColumnLabel(3).equals("col3");
assert tableUnitVec3.getNumRows() == 3;
assert tableUnitVec3.getNumColumns() == 4;
System.out.println(tableUnitVec3);
tableFlat = tableUnitVec3.flatten();
assert tableFlat.getColumnLabels().size() == 12;
assert tableFlat.getColumnLabel( 0).equals("col0_1");
assert tableFlat.getColumnLabel(11).equals("col3_3");
assert tableFlat.getNumRows() == 3;
assert tableFlat.getNumColumns() == 12;
System.out.println(tableFlat);
labels = new StdVectorString();
labels.add("col0.0"); labels.add("col0.1"); labels.add("col0.2");
labels.add("col0.3"); labels.add("col1.0"); labels.add("col1.1");
labels.add("col1.2"); labels.add("col1.3"); labels.add("col2.0");
labels.add("col2.1"); labels.add("col2.2"); labels.add("col2.3");
table.setColumnLabels(labels);
DataTableQuaternion tableQuat = table.packQuaternion();
assert tableQuat.getColumnLabel(0).equals("col0");
assert tableQuat.getColumnLabel(1).equals("col1");
assert tableQuat.getColumnLabel(2).equals("col2");
assert tableQuat.getNumRows() == 3;
assert tableQuat.getNumColumns() == 3;
System.out.println(tableQuat);
tableFlat = tableQuat.flatten();
assert tableFlat.getColumnLabels().size() == 12;
assert tableFlat.getColumnLabel( 0).equals("col0_1");
assert tableFlat.getColumnLabel(11).equals("col2_4");
assert tableFlat.getNumRows() == 3;
assert tableFlat.getNumColumns() == 12;
System.out.println(tableFlat);
labels = new StdVectorString();
labels.add("col0.0"); labels.add("col0.1"); labels.add("col0.2");
labels.add("col0.3"); labels.add("col0.4"); labels.add("col0.5");
labels.add("col1.0"); labels.add("col1.1"); labels.add("col1.2");
labels.add("col1.3"); labels.add("col1.4"); labels.add("col1.5");
table.setColumnLabels(labels);
DataTableSpatialVec tableSVec = table.packSpatialVec();
assert tableSVec.getColumnLabel(0).equals("col0");
assert tableSVec.getColumnLabel(1).equals("col1");
assert tableSVec.getNumRows() == 3;
assert tableSVec.getNumColumns() == 2;
System.out.println(tableSVec);
tableFlat = tableSVec.flatten();
assert tableFlat.getColumnLabels().size() == 12;
assert tableFlat.getColumnLabel( 0).equals("col0_1");
assert tableFlat.getColumnLabel(11).equals("col1_6");
assert tableFlat.getNumRows() == 3;
assert tableFlat.getNumColumns() == 12;
System.out.println(tableFlat);
}
public static void test_DataTableVec3() {
DataTableVec3 table = new DataTableVec3();
// Set column labels.
StdVectorString labels = new StdVectorString();
labels.add("0"); labels.add("1"); labels.add("2"); labels.add("3");
table.setColumnLabels(labels);
// Append row to the table.
Vec3 elem = new Vec3(1, 1, 1);
StdVectorVec3 elems = new StdVectorVec3();
elems.add(elem); elems.add(elem); elems.add(elem); elems.add(elem);
RowVectorOfVec3 row = new RowVectorOfVec3(elems);
table.appendRow(0.1, row);
assert table.getNumRows() == 1;
assert table.getNumColumns() == 4;
RowVectorViewVec3 row0 = table.getRowAtIndex(0);
assert row0.get(0).get(0) == 1 && row0.get(0).get(1) == 1 &&
row0.get(0).get(2) == 1 && row0.get(1).get(0) == 1 &&
row0.get(1).get(1) == 1 && row0.get(1).get(2) == 1 &&
row0.get(2).get(0) == 1 && row0.get(2).get(1) == 1 &&
row0.get(2).get(2) == 1 && row0.get(3).get(0) == 1 &&
row0.get(3).get(1) == 1 && row0.get(3).get(2) == 1;
System.out.println(table);
// Append another row to the table.
elem.set(0, 2); elem.set(1, 2); elem.set(2, 2);
row.set(0, elem); row.set(1, elem); row.set(2, elem); row.set(3, elem);
table.appendRow(0.2, row);
assert table.getNumRows() == 2;
assert table.getNumColumns() == 4;
RowVectorViewVec3 row1 = table.getRowAtIndex(1);
assert row1.get(0).get(0) == 2 && row1.get(0).get(1) == 2 &&
row1.get(0).get(2) == 2 && row1.get(1).get(0) == 2 &&
row1.get(1).get(1) == 2 && row1.get(1).get(2) == 2 &&
row1.get(2).get(0) == 2 && row1.get(2).get(1) == 2 &&
row1.get(2).get(2) == 2 && row1.get(3).get(0) == 2 &&
row1.get(3).get(1) == 2 && row1.get(3).get(2) == 2;
System.out.println(table);
// Append another row to the table.
elem.set(0, 3); elem.set(1, 3); elem.set(2, 3);
row.set(0, elem); row.set(1, elem); row.set(2, elem); row.set(3, elem);
table.appendRow(0.3, row);
assert table.getNumRows() == 3;
assert table.getNumColumns() == 4;
RowVectorViewVec3 row2 = table.getRowAtIndex(2);
assert row2.get(0).get(0) == 3 && row2.get(0).get(1) == 3 &&
row2.get(0).get(2) == 3 && row2.get(1).get(0) == 3 &&
row2.get(1).get(1) == 3 && row2.get(1).get(2) == 3 &&
row2.get(2).get(0) == 3 && row2.get(2).get(1) == 3 &&
row2.get(2).get(2) == 3 && row2.get(3).get(0) == 3 &&
row2.get(3).get(1) == 3 && row2.get(3).get(2) == 3;
System.out.println(table);
// Get independent column.
StdVectorDouble indCol = table.getIndependentColumn();
assert indCol.get(0) == 0.1 &&
indCol.get(1) == 0.2 &&
indCol.get(2) == 0.3;
// Get dependent column.
VectorViewVec3 col1 = table.getDependentColumnAtIndex(1);
assert col1.get(0).get(0) == 1 && col1.get(0).get(1) == 1 &&
col1.get(0).get(2) == 1 && col1.get(1).get(0) == 2 &&
col1.get(1).get(1) == 2 && col1.get(1).get(2) == 2 &&
col1.get(2).get(0) == 3 && col1.get(2).get(1) == 3 &&
col1.get(2).get(2) == 3;
VectorViewVec3 col2 = table.getDependentColumn("2");
assert col2.get(0).get(0) == 1 && col2.get(0).get(1) == 1 &&
col2.get(0).get(2) == 1 && col2.get(1).get(0) == 2 &&
col2.get(1).get(1) == 2 && col2.get(1).get(2) == 2 &&
col2.get(2).get(0) == 3 && col2.get(2).get(1) == 3 &&
col2.get(2).get(2) == 3;
// Flatten table into table of doubles.
DataTable tableDouble = table.flatten();
assert tableDouble.getNumRows() == 3;
assert tableDouble.getNumColumns() == 12;
assert tableDouble.getColumnLabels().size() == 12;
assert tableDouble.getColumnLabel( 0).equals("0_1");
assert tableDouble.getColumnLabel( 1).equals("0_2");
assert tableDouble.getColumnLabel( 2).equals("0_3");
assert tableDouble.getColumnLabel( 3).equals("1_1");
assert tableDouble.getColumnLabel( 4).equals("1_2");
assert tableDouble.getColumnLabel( 5).equals("1_3");
assert tableDouble.getColumnLabel( 6).equals("2_1");
assert tableDouble.getColumnLabel( 7).equals("2_2");
assert tableDouble.getColumnLabel( 8).equals("2_3");
assert tableDouble.getColumnLabel( 9).equals("3_1");
assert tableDouble.getColumnLabel(10).equals("3_2");
assert tableDouble.getColumnLabel(11).equals("3_3");
assert tableDouble.getRowAtIndex(0).get( 0) == 1;
assert tableDouble.getRowAtIndex(0).get( 5) == 1;
assert tableDouble.getRowAtIndex(0).get(11) == 1;
assert tableDouble.getRowAtIndex(1).get( 0) == 2;
assert tableDouble.getRowAtIndex(1).get( 5) == 2;
assert tableDouble.getRowAtIndex(1).get(11) == 2;
assert tableDouble.getRowAtIndex(2).get( 0) == 3;
assert tableDouble.getRowAtIndex(2).get( 5) == 3;
assert tableDouble.getRowAtIndex(2).get(11) == 3;
System.out.println(tableDouble);
StdVectorString suffixes = new StdVectorString();
suffixes.add("_x"); suffixes.add("_y"); suffixes.add("_z");
tableDouble = table.flatten(suffixes);
assert tableDouble.getNumRows() == 3;
assert tableDouble.getNumColumns() == 12;
assert tableDouble.getColumnLabels().size() == 12;
assert tableDouble.getColumnLabel( 0).equals("0_x");
assert tableDouble.getColumnLabel( 1).equals("0_y");
assert tableDouble.getColumnLabel( 2).equals("0_z");
assert tableDouble.getColumnLabel( 3).equals("1_x");
assert tableDouble.getColumnLabel( 4).equals("1_y");
assert tableDouble.getColumnLabel( 5).equals("1_z");
assert tableDouble.getColumnLabel( 6).equals("2_x");
assert tableDouble.getColumnLabel( 7).equals("2_y");
assert tableDouble.getColumnLabel( 8).equals("2_z");
assert tableDouble.getColumnLabel( 9).equals("3_x");
assert tableDouble.getColumnLabel(10).equals("3_y");
assert tableDouble.getColumnLabel(11).equals("3_z");
assert tableDouble.getRowAtIndex(0).get( 0) == 1;
assert tableDouble.getRowAtIndex(0).get( 5) == 1;
assert tableDouble.getRowAtIndex(0).get(11) == 1;
assert tableDouble.getRowAtIndex(1).get( 0) == 2;
assert tableDouble.getRowAtIndex(1).get( 5) == 2;
assert tableDouble.getRowAtIndex(1).get(11) == 2;
assert tableDouble.getRowAtIndex(2).get( 0) == 3;
assert tableDouble.getRowAtIndex(2).get( 5) == 3;
assert tableDouble.getRowAtIndex(2).get(11) == 3;
System.out.println(tableDouble);
// Edit rows of the table.
row0 = table.getRowAtIndex(0);
elem.set(0, 10); elem.set(1, 10); elem.set(2, 10);
row0.set(0, elem); row0.set(1, elem);
row0.set(2, elem); row0.set(3, elem);
Vec3 elem0 = table.getRowAtIndex(0).get(0);
Vec3 elem1 = table.getRowAtIndex(0).get(1);
Vec3 elem2 = table.getRowAtIndex(0).get(2);
Vec3 elem3 = table.getRowAtIndex(0).get(3);
assert elem0.get(0) == 10 && elem0.get(1) == 10 && elem0.get(2) == 10 &&
elem1.get(0) == 10 && elem1.get(1) == 10 && elem1.get(2) == 10 &&
elem2.get(0) == 10 && elem2.get(1) == 10 && elem2.get(2) == 10 &&
elem3.get(0) == 10 && elem3.get(1) == 10 && elem3.get(2) == 10;
row2 = table.getRow(0.3);
elem.set(0, 20); elem.set(1, 20); elem.set(2, 20);
row2.set(0, elem); row2.set(1, elem);
row2.set(2, elem); row2.set(3, elem);
elem0 = table.getRow(0.3).get(0);
elem1 = table.getRow(0.3).get(1);
elem2 = table.getRow(0.3).get(2);
elem3 = table.getRow(0.3).get(3);
assert elem0.get(0) == 20 && elem0.get(1) == 20 && elem0.get(2) == 20 &&
elem1.get(0) == 20 && elem1.get(1) == 20 && elem1.get(2) == 20 &&
elem2.get(0) == 20 && elem2.get(1) == 20 && elem2.get(2) == 20 &&
elem3.get(0) == 20 && elem3.get(1) == 20 && elem3.get(2) == 20;
System.out.println(table);
// Edit columns of the table.
col1 = table.getDependentColumnAtIndex(1);
elem.set(0, 30); elem.set(1, 30); elem.set(2, 30);
col1.set(0, elem); col1.set(1, elem); col1.set(2, elem);
elem0 = table.getDependentColumnAtIndex(1).get(0);
elem1 = table.getDependentColumnAtIndex(1).get(1);
elem2 = table.getDependentColumnAtIndex(1).get(2);
assert elem0.get(0) == 30 && elem0.get(1) == 30 && elem0.get(2) == 30 &&
elem1.get(0) == 30 && elem1.get(1) == 30 && elem1.get(2) == 30 &&
elem2.get(0) == 30 && elem2.get(1) == 30 && elem2.get(2) == 30;
col2 = table.getDependentColumn("2");
elem.set(0, 40); elem.set(1, 40); elem.set(2, 40);
col2.set(0, elem); col2.set(1, elem); col2.set(2, elem);
elem0 = table.getDependentColumn("2").get(0);
elem1 = table.getDependentColumn("2").get(1);
elem2 = table.getDependentColumn("2").get(2);
assert elem0.get(0) == 40 && elem0.get(1) == 40 && elem0.get(2) == 40 &&
elem1.get(0) == 40 && elem1.get(1) == 40 && elem1.get(2) == 40 &&
elem2.get(0) == 40 && elem2.get(1) == 40 && elem2.get(2) == 40;
System.out.println(table);
}
public static void test_TimeSeriesTable() {
TimeSeriesTable table = new TimeSeriesTable();
StdVectorString labels = new StdVectorString();
labels.add("0"); labels.add("1"); labels.add("2"); labels.add("3");
table.setColumnLabels(labels);
// Append a row to the table.
RowVector row = new RowVector(4, 1);
table.appendRow(0.1, row);
assert table.getNumRows() == 1;
assert table.getNumColumns() == 4;
RowVectorView row0 = table.getRowAtIndex(0);
assert row0.get(0) == 1 &&
row0.get(1) == 1 &&
row0.get(2) == 1 &&
row0.get(3) == 1;
System.out.println(table);
// Append another row to the table.
row.set(0, 2); row.set(1, 2); row.set(2, 2); row.set(3, 2);
table.appendRow(0.2, row);
assert table.getNumRows() == 2;
assert table.getNumColumns() == 4;
RowVectorView row1 = table.getRow(0.2);
assert row1.get(0) == 2 &&
row1.get(1) == 2 &&
row1.get(2) == 2 &&
row1.get(3) == 2;
System.out.println(table);
// Append another row to the table with a timestamp
// less than the previous one. Exception expected.
try {
table.appendRow(0.15, row);
assert false;
} catch(java.lang.RuntimeException exc) {}
System.out.println(table);
// Test pack-ing of columns of DataTable.
table = new TimeSeriesTable();
labels = new StdVectorString();
labels.add("col0_x"); labels.add("col0_y"); labels.add("col0_z");
labels.add("col1_x"); labels.add("col1_y"); labels.add("col1_z");
labels.add("col2_x"); labels.add("col2_y"); labels.add("col2_z");
labels.add("col3_x"); labels.add("col3_y"); labels.add("col3_z");
table.setColumnLabels(labels);
row = new RowVector(12, 1);
table.appendRow(1, row);
row = new RowVector(12, 2);
table.appendRow(2, row);
row = new RowVector(12, 3);
table.appendRow(3, row);
assert table.getColumnLabels().size() == 12;
assert table.getNumRows() == 3;
assert table.getNumColumns() == 12;
System.out.println(table);
RowVector avgRow = table.averageRow(1, 3);
assert avgRow.ncol() == 12;
assert Math.abs(avgRow.get( 0) - 2) < 1e-8/*epsilon*/;
assert Math.abs(avgRow.get( 5) - 2) < 1e-8/*epsilon*/;
assert Math.abs(avgRow.get(11) - 2) < 1e-8/*epsilon*/;
RowVectorView nearRow = table.getNearestRow(1.1);
assert nearRow.ncol() == 12;
assert nearRow.get( 0) == 1;
assert nearRow.get( 5) == 1;
assert nearRow.get(11) == 1;
StdVectorString suffixes = new StdVectorString();
suffixes.add("_x"); suffixes.add("_y"); suffixes.add("_z");
TimeSeriesTableVec3 tableVec3 = table.packVec3(suffixes);
assert tableVec3.getColumnLabel(0).equals("col0");
assert tableVec3.getColumnLabel(1).equals("col1");
assert tableVec3.getColumnLabel(2).equals("col2");
assert tableVec3.getColumnLabel(3).equals("col3");
assert tableVec3.getNumRows() == 3;
assert tableVec3.getNumColumns() == 4;
System.out.println(tableVec3);
TimeSeriesTable tableFlat = tableVec3.flatten();
assert tableFlat.getColumnLabels().size() == 12;
assert tableFlat.getColumnLabel( 0).equals("col0_1");
assert tableFlat.getColumnLabel(11).equals("col3_3");
assert tableFlat.getNumRows() == 3;
assert tableFlat.getNumColumns() == 12;
System.out.println(tableFlat);
tableVec3 = table.packVec3();
assert tableVec3.getColumnLabel(0).equals("col0");
assert tableVec3.getColumnLabel(1).equals("col1");
assert tableVec3.getColumnLabel(2).equals("col2");
assert tableVec3.getColumnLabel(3).equals("col3");
assert tableVec3.getNumRows() == 3;
assert tableVec3.getNumColumns() == 4;
System.out.println(tableVec3);
tableFlat = tableVec3.flatten();
assert tableFlat.getColumnLabels().size() == 12;
assert tableFlat.getColumnLabel( 0).equals("col0_1");
assert tableFlat.getColumnLabel(11).equals("col3_3");
assert tableFlat.getNumRows() == 3;
assert tableFlat.getNumColumns() == 12;
System.out.println(tableFlat);
RowVectorOfVec3 avgRowVec3 = tableVec3.averageRow(1, 2);
assert avgRowVec3.ncol() == 4;
assert Math.abs(avgRowVec3.get(0).get(0) - 1.5) < 1e-8/*epsilon*/;
assert Math.abs(avgRowVec3.get(3).get(2) - 1.5) < 1e-8/*epsilon*/;
RowVectorViewVec3 nearRowVec3 = tableVec3.getNearestRow(1.1);
assert nearRowVec3.ncol() == 4;
assert nearRowVec3.get(0).get(0) == 1;
assert nearRowVec3.get(3).get(2) == 1;
TimeSeriesTableUnitVec3 tableUnitVec3 = table.packUnitVec3();
assert tableUnitVec3.getColumnLabel(0).equals("col0");
assert tableUnitVec3.getColumnLabel(1).equals("col1");
assert tableUnitVec3.getColumnLabel(2).equals("col2");
assert tableUnitVec3.getColumnLabel(3).equals("col3");
assert tableUnitVec3.getNumRows() == 3;
assert tableUnitVec3.getNumColumns() == 4;
System.out.println(tableUnitVec3);
tableFlat = tableUnitVec3.flatten();
assert tableFlat.getColumnLabels().size() == 12;
assert tableFlat.getColumnLabel( 0).equals("col0_1");
assert tableFlat.getColumnLabel(11).equals("col3_3");
assert tableFlat.getNumRows() == 3;
assert tableFlat.getNumColumns() == 12;
System.out.println(tableFlat);
labels = new StdVectorString();
labels.add("col0.0"); labels.add("col0.1"); labels.add("col0.2");
labels.add("col0.3"); labels.add("col1.0"); labels.add("col1.1");
labels.add("col1.2"); labels.add("col1.3"); labels.add("col2.0");
labels.add("col2.1"); labels.add("col2.2"); labels.add("col2.3");
table.setColumnLabels(labels);
TimeSeriesTableQuaternion tableQuat = table.packQuaternion();
assert tableQuat.getColumnLabel(0).equals("col0");
assert tableQuat.getColumnLabel(1).equals("col1");
assert tableQuat.getColumnLabel(2).equals("col2");
assert tableQuat.getNumRows() == 3;
assert tableQuat.getNumColumns() == 3;
System.out.println(tableQuat);
// tableFlat = tableQuat.flatten();
// assert tableFlat.getColumnLabels().size() == 12;
// assert tableFlat.getColumnLabel( 0).equals("col0_1");
// assert tableFlat.getColumnLabel(11).equals("col2_4");
// assert tableFlat.getNumRows() == 3;
// assert tableFlat.getNumColumns() == 12;
// System.out.println(tableFlat);
labels = new StdVectorString();
labels.add("col0.0"); labels.add("col0.1"); labels.add("col0.2");
labels.add("col0.3"); labels.add("col0.4"); labels.add("col0.5");
labels.add("col1.0"); labels.add("col1.1"); labels.add("col1.2");
labels.add("col1.3"); labels.add("col1.4"); labels.add("col1.5");
table.setColumnLabels(labels);
TimeSeriesTableSpatialVec tableSVec = table.packSpatialVec();
assert tableSVec.getColumnLabel(0).equals("col0");
assert tableSVec.getColumnLabel(1).equals("col1");
assert tableSVec.getNumRows() == 3;
assert tableSVec.getNumColumns() == 2;
System.out.println(tableSVec);
tableFlat = tableSVec.flatten();
assert tableFlat.getColumnLabels().size() == 12;
assert tableFlat.getColumnLabel( 0).equals("col0_1");
assert tableFlat.getColumnLabel(11).equals("col1_6");
assert tableFlat.getNumRows() == 3;
assert tableFlat.getNumColumns() == 12;
System.out.println(tableFlat);
}
public static void test_TimeSeriesTableVec3() {
TimeSeriesTableVec3 table = new TimeSeriesTableVec3();
// Set column labels.
StdVectorString labels = new StdVectorString();
labels.add("0"); labels.add("1"); labels.add("2"); labels.add("3");
table.setColumnLabels(labels);
// Append row to the table.
Vec3 elem = new Vec3(1, 1, 1);
StdVectorVec3 elems = new StdVectorVec3();
elems.add(elem); elems.add(elem); elems.add(elem); elems.add(elem);
RowVectorOfVec3 row = new RowVectorOfVec3(elems);
table.appendRow(0.1, row);
assert table.getNumRows() == 1;
assert table.getNumColumns() == 4;
RowVectorViewVec3 row0 = table.getRowAtIndex(0);
assert row0.get(0).get(0) == 1 && row0.get(0).get(1) == 1 &&
row0.get(0).get(2) == 1 && row0.get(1).get(0) == 1 &&
row0.get(1).get(1) == 1 && row0.get(1).get(2) == 1 &&
row0.get(2).get(0) == 1 && row0.get(2).get(1) == 1 &&
row0.get(2).get(2) == 1 && row0.get(3).get(0) == 1 &&
row0.get(3).get(1) == 1 && row0.get(3).get(2) == 1;
System.out.println(table);
// Append another row to the table.
elem.set(0, 2); elem.set(1, 2); elem.set(2, 2);
row.set(0, elem); row.set(1, elem); row.set(2, elem); row.set(3, elem);
table.appendRow(0.2, row);
assert table.getNumRows() == 2;
assert table.getNumColumns() == 4;
RowVectorViewVec3 row1 = table.getRowAtIndex(1);
assert row1.get(0).get(0) == 2 && row1.get(0).get(1) == 2 &&
row1.get(0).get(2) == 2 && row1.get(1).get(0) == 2 &&
row1.get(1).get(1) == 2 && row1.get(1).get(2) == 2 &&
row1.get(2).get(0) == 2 && row1.get(2).get(1) == 2 &&
row1.get(2).get(2) == 2 && row1.get(3).get(0) == 2 &&
row1.get(3).get(1) == 2 && row1.get(3).get(2) == 2;
System.out.println(table);
// Append another row to the table with a timestamp
// less than the previous one. Exception expected.
try {
table.appendRow(0.15, row);
assert false;
} catch(java.lang.RuntimeException exc) {}
System.out.println(table);
// Average row.
RowVectorOfVec3 avgRow = table.averageRow(0.1, 0.2);
assert avgRow.ncol() == 4;
assert Math.abs(avgRow.get(0).get(0) - 1.5) < 1e-8/*epsilon*/;
assert Math.abs(avgRow.get(3).get(2) - 1.5) < 1e-8/*epsilon*/;
// Nearest row.
RowVectorViewVec3 nearRow = table.getNearestRow(0.13);
assert nearRow.ncol() == 4;
assert nearRow.get(0).get(0) == 1;
assert nearRow.get(3).get(2) == 1;
// Flatten table into table of doubles.
TimeSeriesTable tableDouble = table.flatten();
assert tableDouble.getNumRows() == 2;
assert tableDouble.getNumColumns() == 12;
assert tableDouble.getColumnLabels().size() == 12;
assert tableDouble.getColumnLabel( 0).equals("0_1");
assert tableDouble.getColumnLabel( 1).equals("0_2");
assert tableDouble.getColumnLabel( 2).equals("0_3");
assert tableDouble.getColumnLabel( 3).equals("1_1");
assert tableDouble.getColumnLabel( 4).equals("1_2");
assert tableDouble.getColumnLabel( 5).equals("1_3");
assert tableDouble.getColumnLabel( 6).equals("2_1");
assert tableDouble.getColumnLabel( 7).equals("2_2");
assert tableDouble.getColumnLabel( 8).equals("2_3");
assert tableDouble.getColumnLabel( 9).equals("3_1");
assert tableDouble.getColumnLabel(10).equals("3_2");
assert tableDouble.getColumnLabel(11).equals("3_3");
assert tableDouble.getRowAtIndex(0).get( 0) == 1;
assert tableDouble.getRowAtIndex(0).get( 5) == 1;
assert tableDouble.getRowAtIndex(0).get(11) == 1;
assert tableDouble.getRowAtIndex(1).get( 0) == 2;
assert tableDouble.getRowAtIndex(1).get( 5) == 2;
assert tableDouble.getRowAtIndex(1).get(11) == 2;
System.out.println(tableDouble);
StdVectorString suffixes = new StdVectorString();
suffixes.add("_x"); suffixes.add("_y"); suffixes.add("_z");
tableDouble = table.flatten(suffixes);
assert tableDouble.getNumRows() == 2;
assert tableDouble.getNumColumns() == 12;
assert tableDouble.getColumnLabels().size() == 12;
assert tableDouble.getColumnLabel( 0).equals("0_x");
assert tableDouble.getColumnLabel( 1).equals("0_y");
assert tableDouble.getColumnLabel( 2).equals("0_z");
assert tableDouble.getColumnLabel( 3).equals("1_x");
assert tableDouble.getColumnLabel( 4).equals("1_y");
assert tableDouble.getColumnLabel( 5).equals("1_z");
assert tableDouble.getColumnLabel( 6).equals("2_x");
assert tableDouble.getColumnLabel( 7).equals("2_y");
assert tableDouble.getColumnLabel( 8).equals("2_z");
assert tableDouble.getColumnLabel( 9).equals("3_x");
assert tableDouble.getColumnLabel(10).equals("3_y");
assert tableDouble.getColumnLabel(11).equals("3_z");
assert tableDouble.getRowAtIndex(0).get( 0) == 1;
assert tableDouble.getRowAtIndex(0).get( 5) == 1;
assert tableDouble.getRowAtIndex(0).get(11) == 1;
assert tableDouble.getRowAtIndex(1).get( 0) == 2;
assert tableDouble.getRowAtIndex(1).get( 5) == 2;
assert tableDouble.getRowAtIndex(1).get(11) == 2;
System.out.println(tableDouble);
}
public static void test_FlattenWithIK() throws java.io.IOException {
String setupFileName = new String("subject01_Setup_IK_generic.xml");
String markerFileName = new String("walk_free_01.trc");
String modelFileName = new String("subject01_gait2392_scaled.osim");
TRCFileAdapter trcAdapter = new TRCFileAdapter();
TimeSeriesTableVec3 markerTable = trcAdapter.read(markerFileName);
System.out.println(markerTable);
StdVectorString suffixes = new StdVectorString();
suffixes.add(".x"); suffixes.add(".y"); suffixes.add(".z");
TimeSeriesTable markerTableFlat = markerTable.flatten(suffixes);
System.out.println(markerTableFlat);
STOFileAdapter stoAdapter = new STOFileAdapter();
markerFileName = "walk_free_01.sto";
stoAdapter.write(markerTableFlat, markerFileName);
InverseKinematicsTool ikTool = new InverseKinematicsTool(setupFileName);
ikTool.setName("ik_test");
ikTool.setModel(new Model(modelFileName));
ikTool.setMarkerDataFileName(markerFileName);
StdVectorDouble timeColumn = markerTable.getIndependentColumn();
ikTool.setStartTime(timeColumn.get(0));
ikTool.setEndTime(timeColumn.get((int)(timeColumn.size() - 1)));
String ikResultsFileName = new String("ik_results.mot");
ikTool.setOutputMotionFileName(ikResultsFileName);
ikTool.run();
}
public static void test_vector_rowvector() {
{
RowVector rowVec = new RowVector(4);
for(int i = 0; i < 4; ++i)
rowVec.set(i, i);
Vector colVec = rowVec.transpose();
assert colVec.size() == 4;
for(int i = 0; i < 4; ++i)
assert colVec.get(i) == i;
RowVector rowVec_copy = colVec.transpose();
assert rowVec_copy.size() == 4;
for(int i = 0; i < 4; ++i)
assert rowVec_copy.get(i) == i;
}
{
StdVectorVec3 elems = new StdVectorVec3();
for(int i = 0; i < 4; ++i)
elems.add(new Vec3(i, i+1, i+2));
RowVectorOfVec3 rowVec = new RowVectorOfVec3(elems);
VectorOfVec3 colVec = rowVec.transpose();
assert colVec.size() == 4;
for(int i = 0; i < 4; ++i)
assert colVec.get(i).get(0) == i &&
colVec.get(i).get(1) == i+1 &&
colVec.get(i).get(2) == i+2;
RowVectorOfVec3 rowVec_copy = colVec.transpose();
assert rowVec_copy.size() == 4;
for(int i = 0; i < 4; ++i)
assert rowVec_copy.get(i).get(0) == i &&
rowVec_copy.get(i).get(1) == i+1 &&
rowVec_copy.get(i).get(2) == i+2;
}
}
public static void main(String[] args) throws java.io.IOException {
test_DataTable();
test_DataTableVec3();
test_TimeSeriesTable();
test_TimeSeriesTableVec3();
test_FlattenWithIK();
test_vector_rowvector();
}
}
|
package org.jpos.q2.iso;
import org.jdom2.Element;
import org.jpos.core.ConfigurationException;
import org.jpos.iso.*;
import org.jpos.q2.QBeanSupport;
import org.jpos.q2.QFactory;
import org.jpos.space.*;
import org.jpos.util.Loggeable;
import org.jpos.util.NameRegistrar;
import java.io.IOException;
import java.io.PrintStream;
import java.util.*;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* @author Alejandro Revilla
*/
@SuppressWarnings("unchecked")
public class QMUX
extends QBeanSupport
implements SpaceListener, MUX, QMUXMBean, Loggeable
{
static final String nomap = "0123456789";
static final String DEFAULT_KEY = "41, 11";
protected LocalSpace sp;
protected String in, out, unhandled;
protected String[] ready;
protected String[] key;
protected String ignorerc;
protected String[] mtiMapping;
private boolean headerIsKey;
private LocalSpace isp; // internal space
private Map<String,String[]> mtiKey = new HashMap<>();
List<ISORequestListener> listeners;
int rx, tx, rxExpired, txExpired, rxPending, rxUnhandled, rxForwarded;
long lastTxn = 0L;
boolean listenerRegistered;
public QMUX () {
super ();
listeners = new ArrayList<ISORequestListener>();
}
public void initService () throws ConfigurationException {
Element e = getPersist ();
sp = grabSpace (e.getChild ("space"));
isp = cfg.getBoolean("reuse-space", false) ? sp : new TSpace();
in = e.getChildTextTrim ("in");
out = e.getChildTextTrim ("out");
ignorerc = e.getChildTextTrim ("ignore-rc");
key = toStringArray(DEFAULT_KEY, ", ", null);
for (Element keyElement : e.getChildren("key")) {
String mtiOverride = keyElement.getAttributeValue("mti");
if (mtiOverride != null && mtiOverride.length() >= 2) {
mtiKey.put (mtiOverride.substring(0,2), toStringArray(keyElement.getTextTrim(), ", ", null));
} else {
key = toStringArray(e.getChildTextTrim("key"), ", ", DEFAULT_KEY);
}
}
ready = toStringArray(e.getChildTextTrim ("ready"));
mtiMapping = toStringArray(e.getChildTextTrim ("mtimapping"));
if (mtiMapping == null || mtiMapping.length != 3)
mtiMapping = new String[] { nomap, nomap, "0022446789" };
addListeners ();
unhandled = e.getChildTextTrim ("unhandled");
NameRegistrar.register ("mux."+getName (), this);
}
public void startService () {
if (!listenerRegistered) {
listenerRegistered = true;
// Handle messages that could be in the in queue at start time
synchronized (sp) {
Object[] pending = SpaceUtil.inpAll(sp, in);
sp.addListener (in, this);
for (Object o : pending)
sp.out(in, o);
}
}
}
public void stopService () {
listenerRegistered = false;
sp.removeListener (in, this);
}
public void destroyService () {
NameRegistrar.unregister ("mux."+getName ());
}
/**
* @return MUX with name using NameRegistrar
* @throws NameRegistrar.NotFoundException
* @see NameRegistrar
*/
public static MUX getMUX (String name)
throws NameRegistrar.NotFoundException
{
return (MUX) NameRegistrar.get ("mux."+name);
}
/**
* @param m message to send
* @param timeout amount of time in millis to wait for a response
* @return response or null
*/
public ISOMsg request (ISOMsg m, long timeout) throws ISOException {
String key = getKey (m);
String req = key + ".req";
if (isp.rdp (req) != null)
throw new ISOException ("Duplicate key '" + req + "' detected");
isp.out (req, m);
m.setDirection(0);
if (timeout > 0)
sp.out (out, m, timeout);
else
sp.out (out, m);
ISOMsg resp = null;
try {
synchronized (this) { tx++; rxPending++; }
for (;;) {
resp = (ISOMsg) isp.in (key, timeout);
if (!shouldIgnore (resp))
break;
}
if (resp == null && isp.inp (req) == null) {
// possible race condition, retry for a few extra seconds
resp = (ISOMsg) isp.in (key, 10000);
}
synchronized (this) {
if (resp != null)
{
rx++;
lastTxn = System.currentTimeMillis();
}else {
rxExpired++;
if (m.getDirection() != ISOMsg.OUTGOING)
txExpired++;
}
}
} finally {
synchronized (this) { rxPending
}
return resp;
}
public void notify (Object k, Object value) {
Object obj = sp.inp (k);
if (obj instanceof ISOMsg) {
ISOMsg m = (ISOMsg) obj;
try {
if (m.isResponse()) {
String key = getKey (m);
String req = key + ".req";
Object r = isp.inp (req);
if (r != null) {
if (r instanceof AsyncRequest) {
((AsyncRequest) r).responseReceived (m);
} else {
isp.out (key, m);
}
return;
}
}
} catch (ISOException e) {
getLog().warn ("notify", e);
}
processUnhandled (m);
}
}
public String getKey (ISOMsg m) throws ISOException {
StringBuilder sb = new StringBuilder (out);
sb.append ('.');
sb.append (mapMTI(m.getMTI()));
if (headerIsKey && m.getHeader()!=null) {
sb.append ('.');
sb.append(ISOUtil.hexString(m.getHeader()));
sb.append ('.');
}
boolean hasFields = false;
String[] k = mtiKey.getOrDefault(m.getMTI().substring(0,2), key);
for (String f : k) {
String v = m.getString(f);
if (v != null) {
if ("11".equals(f)) {
String vt = v.trim();
int l = m.getMTI().charAt(0) == '2' ? 12 : 6;
if (vt.length() < l)
v = ISOUtil.zeropad(vt, l);
}
if ("41".equals(f)) {
v = ISOUtil.zeropad(v.trim(), 16); // BIC ANSI to ISO hack
}
hasFields = true;
sb.append(v);
}
}
if (!hasFields)
throw new ISOException ("Key fields not found - not sending " + sb.toString());
return sb.toString();
}
private String mapMTI (String mti) throws ISOException {
StringBuilder sb = new StringBuilder();
if (mti != null) {
if (mti.length() < 4)
mti = ISOUtil.zeropad(mti, 4); // #jPOS-55
if (mti.length() == 4) {
for (int i=0; i<mtiMapping.length; i++) {
int c = mti.charAt (i) - '0';
if (c >= 0 && c < 10)
sb.append (mtiMapping[i].charAt(c));
}
}
}
return sb.toString();
}
public synchronized void setInQueue (String in) {
this.in = in;
getPersist().getChild("in").setText (in);
setModified (true);
}
public String getInQueue () {
return in;
}
public synchronized void setOutQueue (String out) {
this.out = out;
getPersist().getChild("out").setText (out);
setModified (true);
}
public String getOutQueue () {
return out;
}
public Space getSpace() {
return sp;
}
public synchronized void setUnhandledQueue (String unhandled) {
this.unhandled = unhandled;
getPersist().getChild("unhandled").setText (unhandled);
setModified (true);
}
public String getUnhandledQueue () {
return unhandled;
}
public void request (ISOMsg m, long timeout, ISOResponseListener rl, Object handBack)
throws ISOException
{
String key = getKey (m);
String req = key + ".req";
if (isp.rdp (req) != null)
throw new ISOException ("Duplicate key '" + req + "' detected.");
m.setDirection(0);
AsyncRequest ar = new AsyncRequest (rl, handBack);
synchronized (ar) {
if (timeout > 0)
ar.setFuture(getScheduledThreadPoolExecutor().schedule(ar, timeout, TimeUnit.MILLISECONDS));
}
isp.out (req, ar, timeout);
sp.out (out, m, timeout);
}
@SuppressWarnings("unused")
public String[] getReadyIndicatorNames() {
return ready;
}
private void addListeners ()
throws ConfigurationException
{
QFactory factory = getFactory ();
Iterator iter = getPersist().getChildren (
"request-listener"
).iterator();
while (iter.hasNext()) {
Element l = (Element) iter.next();
ISORequestListener listener = (ISORequestListener)
factory.newInstance (l.getAttributeValue ("class"));
factory.setLogger (listener, l);
factory.setConfiguration (listener, l);
addISORequestListener (listener);
}
}
public void addISORequestListener(ISORequestListener l) {
listeners.add (l);
}
public boolean removeISORequestListener(ISORequestListener l) {
return listeners.remove(l);
}
public synchronized void resetCounters() {
rx = tx = rxExpired = txExpired = rxPending = rxUnhandled = rxForwarded = 0;
lastTxn = 0l;
}
public String getCountersAsString () {
StringBuffer sb = new StringBuffer();
append (sb, "tx=", tx);
append (sb, ", rx=", rx);
append (sb, ", tx_expired=", txExpired);
append (sb, ", tx_pending=", sp.size(out));
append (sb, ", rx_expired=", rxExpired);
append (sb, ", rx_pending=", rxPending);
append (sb, ", rx_unhandled=", rxUnhandled);
append (sb, ", rx_forwarded=", rxForwarded);
sb.append (", connected=");
sb.append (Boolean.toString(isConnected()));
sb.append (", last=");
sb.append (lastTxn);
if (lastTxn > 0) {
sb.append (", idle=");
sb.append(System.currentTimeMillis() - lastTxn);
sb.append ("ms");
}
return sb.toString();
}
public int getTXCounter() {
return tx;
}
public int getRXCounter() {
return rx;
}
public long getLastTxnTimestampInMillis() {
return lastTxn;
}
public long getIdleTimeInMillis() {
return lastTxn > 0L ? System.currentTimeMillis() - lastTxn : -1L;
}
protected void processUnhandled (ISOMsg m) {
ISOSource source = m.getSource () != null ? m.getSource() : this;
Iterator iter = listeners.iterator();
if (iter.hasNext())
synchronized (this) { rxForwarded++; }
while (iter.hasNext())
if (((ISORequestListener)iter.next()).process (source, m))
return;
if (unhandled != null) {
synchronized (this) { rxUnhandled++; }
sp.out (unhandled, m, 120000);
}
}
private LocalSpace grabSpace (Element e)
throws ConfigurationException
{
String uri = e != null ? e.getText() : "";
Space sp = SpaceFactory.getSpace (uri);
if (sp instanceof LocalSpace) {
return (LocalSpace) sp;
}
throw new ConfigurationException ("Invalid space " + uri);
}
/**
* sends (or hands back) an ISOMsg
*
* @param m the Message to be sent
* @throws java.io.IOException
* @throws org.jpos.iso.ISOException
* @throws org.jpos.iso.ISOFilter.VetoException;
*/
public void send(ISOMsg m) throws IOException, ISOException {
if (!isConnected())
throw new ISOException ("MUX is not connected");
sp.out (out, m);
}
public boolean isConnected() {
if (running() && ready != null && ready.length > 0) {
for (String aReady : ready)
if (sp.rdp(aReady) != null)
return true;
return false;
}
return running();
}
public void dump (PrintStream p, String indent) {
p.println (indent + getCountersAsString());
}
private String[] toStringArray(String s, String delimiter, String def) {
if (s == null)
s = def;
String[] arr = null;
if (s != null && s.length() > 0) {
StringTokenizer st;
if (delimiter != null)
st = new StringTokenizer(s, delimiter);
else
st = new StringTokenizer(s);
List<String> l = new ArrayList<String>();
while (st.hasMoreTokens()) {
String t = st.nextToken();
if ("header".equalsIgnoreCase(t)) {
headerIsKey = true;
} else {
l.add (t);
}
}
arr = l.toArray(new String[l.size()]);
}
return arr;
}
private String[] toStringArray(String s) {
return toStringArray(s, null,null);
}
private boolean shouldIgnore (ISOMsg m) {
if (m != null && ignorerc != null
&& ignorerc.length() > 0 && m.hasField(39))
{
return ignorerc.contains(m.getString(39));
}
return false;
}
private void append (StringBuffer sb, String name, int value) {
sb.append (name);
sb.append (value);
}
public static class AsyncRequest implements Runnable {
ISOResponseListener rl;
Object handBack;
ScheduledFuture future;
public AsyncRequest (ISOResponseListener rl, Object handBack) {
super();
this.rl = rl;
this.handBack = handBack;
}
public void setFuture(ScheduledFuture future) {
this.future = future;
}
public void responseReceived (ISOMsg response) {
if (future == null || future.cancel(false))
rl.responseReceived (response, handBack);
}
public void run() {
rl.expired(handBack);
}
}
}
|
package yuku.alkitab.base.fr;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.style.StyleSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import yuku.afw.V;
import yuku.alkitab.R;
import yuku.alkitab.base.S;
import yuku.alkitab.base.fr.base.BaseGotoFragment;
import yuku.alkitab.base.util.Jumper;
public class GotoDirectFragment extends BaseGotoFragment {
public static final String TAG = GotoDirectFragment.class.getSimpleName();
private static final String EXTRA_verse = "verse"; //$NON-NLS-1$
private static final String EXTRA_chapter = "chapter"; //$NON-NLS-1$
private static final String EXTRA_bookId = "bookId"; //$NON-NLS-1$
TextView lContohLoncat;
EditText tAlamatLoncat;
View bOk;
int bookId;
int chapter_1;
int verse_1;
public static Bundle createArgs(int bookId, int chapter_1, int verse_1) {
Bundle args = new Bundle();
args.putInt(EXTRA_bookId, bookId);
args.putInt(EXTRA_chapter, chapter_1);
args.putInt(EXTRA_verse, verse_1);
return args;
}
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args != null) {
bookId = args.getInt(EXTRA_bookId, -1);
chapter_1 = args.getInt(EXTRA_chapter);
verse_1 = args.getInt(EXTRA_verse);
}
}
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View res = inflater.inflate(R.layout.fragment_goto_direct, container, false);
lContohLoncat = V.get(res, R.id.lContohLoncat);
tAlamatLoncat = V.get(res, R.id.tAlamatLoncat);
bOk = V.get(res, R.id.bOk);
bOk.setOnClickListener(bOk_click);
tAlamatLoncat.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
bOk_click.onClick(bOk);
return true;
}
});
return res;
}
@Override public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
{
String example = S.activeVersion.reference(bookId, chapter_1, verse_1);
String text = getString(R.string.loncat_ke_alamat_titikdua);
int pos = text.indexOf("%s"); //$NON-NLS-1$
if (pos >= 0) {
SpannableStringBuilder sb = new SpannableStringBuilder();
sb.append(text.substring(0, pos));
sb.append(example);
sb.append(text.substring(pos + 2));
sb.setSpan(new StyleSpan(Typeface.BOLD), pos, pos + example.length(), 0);
lContohLoncat.setText(sb, BufferType.SPANNABLE);
}
}
tAlamatLoncat.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
showKeyboard();
}
}
});
tAlamatLoncat.requestFocus();
}
OnClickListener bOk_click = new OnClickListener() {
@Override public void onClick(View v) {
String reference = tAlamatLoncat.getText().toString();
if (reference.trim().length() == 0) {
return; // do nothing
}
Jumper jumper = new Jumper(reference);
if (! jumper.getParseSucceeded()) {
new AlertDialog.Builder(getActivity())
.setMessage(getString(R.string.alamat_tidak_sah_alamat, reference))
.setPositiveButton(R.string.ok, null)
.show();
return;
}
final int bookId = jumper.getBookId(S.activeVersion.getConsecutiveBooks());
final int chapter = jumper.getChapter();
final int verse = jumper.getVerse();
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(tAlamatLoncat.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
imm.hideSoftInputFromWindow(tAlamatLoncat.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
((GotoFinishListener) getActivity()).onGotoFinished(GotoFinishListener.GOTO_TAB_direct, bookId, chapter, verse);
}
};
public void onTabSelected() {
showKeyboard();
}
private void showKeyboard() {
if (getActivity() != null) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(tAlamatLoncat, InputMethodManager.SHOW_IMPLICIT);
}
}
}
|
package bayesGame.minigame;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.apache.commons.math3.fraction.Fraction;
import bayesGame.levelcontrollers.LevelController;
import bayesGame.levelcontrollers.Script;
import bayesGame.ui.InterfaceView;
import bayesGame.viewcontrollers.MinigameViewController;
import bayesGame.viewcontrollers.ViewController;
import bayesGame.world.GameCharacters;
import bayesGame.world.PlayerCharacter;
import bayesGame.bayesbayes.*;
public class MinigameController {
private MinigameViewController viewController;
private Map<Object,String[]> discussions;
private DiscussionNet gameNet;
private int timeLimit;
private Set<Object> hiddenNodes;
private Set<Object> targetNodes;
private int gameMode;
private int reaction;
private Object successResult;
private Object failureResult;
private boolean ready = false;
private int turnsTaken;
private boolean energycost = false;
private PlayerCharacter PC;
private LevelController owner;
public MinigameController(DiscussionNet gameNet, Set<Object> targetNodes) {
this.gameNet = gameNet;
this.targetNodes = targetNodes;
this.gameMode = 0;
this.reaction = 0;
this.successResult = "";
this.failureResult = "Restart";
if (targetNodes.size() == 0){
for (BayesNode n : gameNet.getGraph().getVertices().toArray(new BayesNode[gameNet.getGraph().getVertexCount()])){
targetNodes.add(n.type);
}
}
this.hiddenNodes = new HashSet<Object>();
this.discussions = new HashMap<Object,String[]>();
this.viewController = new MinigameViewController(this, gameNet);
}
public void setHiddenNodes(Set<Object> hiddenNodes){
this.hiddenNodes = hiddenNodes;
}
public void setGameMode(int gameMode){
this.gameMode = gameMode;
}
public void enableEnergyCost(){
this.PC = GameCharacters.PC;
energycost = true;
}
public void hideTargetNodes(){
hiddenNodes.addAll(targetNodes);
}
public void hideTargetNodeFamily(){
for (Object o : targetNodes){
List<Object> targetNodeFamily = gameNet.getFamily(o);
hiddenNodes.addAll(targetNodeFamily);
}
}
public void randomizeHiddenNodes(double percentage){
if (percentage > 1){
percentage = 1;
} else if (percentage < 0){
percentage = 0;
}
int nodecount = gameNet.getGraph().getVertexCount();
int hidden_node_count = (int)(percentage * nodecount);
if (hidden_node_count == 0){
hidden_node_count = 1;
}
if (hidden_node_count == nodecount){
hidden_node_count
}
int nodes_hidden_already = hiddenNodes.size();
int nodes_to_hide = hidden_node_count - nodes_hidden_already;
if (nodes_to_hide > 0){
randomizeHiddenNodes(nodes_to_hide);
}
}
public void randomizeHiddenNodes(int amount){
Random random = new Random();
BayesNode[] nodes = gameNet.getGraph().getVertices().toArray(new BayesNode[gameNet.getGraph().getVertexCount()]);
for(int i = 0; i < amount; i++){
// pick a random node which is not already in the set of hidden nodes
int item;
do{
item = random.nextInt(nodes.length);
} while (!hiddenNodes.contains(nodes[item].type));
hiddenNodes.add(nodes[item].type);
}
}
public void randomizeTargetNodes(int amount){
Random random = new Random();
BayesNode[] nodes = gameNet.getGraph().getVertices().toArray(new BayesNode[gameNet.getGraph().getVertexCount()]);
targetNodes.clear();
for(int i = 0; i < amount; i++){
int item = random.nextInt(nodes.length);
targetNodes.add(nodes[item].type);
}
}
public void randomizeTargetNode(){
List<Object> nodefamily;
do {
randomizeTargetNodes(1);
Object[] nodearray = targetNodes.toArray();
Object node = nodearray[0];
nodefamily = gameNet.getFamily(node);
} while (nodefamily.size() < 2);
}
public void setDiscussions(Map<Object,String[]> discussions){
this.discussions = discussions;
}
public void startGame(){
startGame(0, new Object[0]);
}
// game mode 1 = figure out the contents of target nodes
public void startGame(int timeLimit, Object[] knowledges){
this.timeLimit = timeLimit;
turnsTaken = 0;
// mark known nodes as known
for (Object o : knowledges){
gameNet.observe(o);
}
for (Object h : hiddenNodes){
gameNet.addProperty(h, "hidden");
}
for (Object t : targetNodes){
gameNet.addProperty(t, "target");
}
ready = true;
viewController.display();
}
public void chooseNode(Object node){
if (ready){
if (!hiddenNodes.contains(node) && !gameNet.isObserved(node)){
viewController.displayOptions(node);
}
}
}
private void endOfTurn(int timeTaken){
if (ready){
turnsTaken = turnsTaken + timeTaken;
boolean allTargetNodesKnown = true;
for (Object o : targetNodes){
if (gameNet.getProbability(o).doubleValue() > 0.0d && gameNet.getProbability(o).doubleValue() < 1.0d){
allTargetNodesKnown = false;
break;
}
}
if (timeLimit > 0){
viewController.showText("Turn " + turnsTaken + "/" + timeLimit);
}
if (allTargetNodesKnown && gameMode == 0 && timeLimit > 0){
viewController.showText("Success!");
viewController.showText("Clearing this level with " + (timeLimit - turnsTaken) + " turns to spare confers " + (timeLimit - turnsTaken) + "fame.");
clear(true);
} else if (turnsTaken == timeLimit && timeLimit > 0){
viewController.showText("Failure!");
clear(false);
} else if (allTargetNodesKnown && gameMode == 0){
if (energycost){
finishedThinking();
}
clear(true);
}
}
}
private void decisionMade(Object node){
Fraction probability = gameNet.getProbability(node);
if (probability.doubleValue() > 0.5d){
reaction++;
clear(true);
// viewController.addText("Positive reaction! Current reaction " + reaction);
} else {
reaction
clear(false);
// viewController.addText("Negative reaction! Current reaction " + reaction);
}
}
private void clear(boolean success){
ready = false;
viewController.processEventQueue();
if (success){
processGameEnd(successResult);
} else {
processGameEnd(failureResult);
}
}
private void processGameEnd(Object resultType) {
if (resultType.equals("Restart")){
// TODO: Restart
} else if (resultType instanceof Script){
Script script = (Script)resultType;
script.run();
} else {
owner.minigameCompleted(viewController);
}
}
public void observeNode(Object type, OptionNodeOption option) {
if (ready){
if (!hiddenNodes.contains(type)){
if ((!energycost) || PC.getEnergy() > 0){
boolean nodeTrue = gameNet.observe(type);
int timeSpent = 1;
if (option != null){
timeSpent = option.getTimeSpent();
viewController.showText(option.getDescription());
String response;
if (nodeTrue){
response = option.getPositiveResponse();
} else {
response = option.getNegativeResponse();
}
viewController.showText(response);
// viewController.displayPopup(option.getDescription(), response);
}
gameNet.updateBeliefs();
viewController.addRefreshDisplay();
viewController.processEventQueue();
if (gameMode == 1 && targetNodes.contains(type)){
decisionMade(type);
}
if (energycost){
PC.useEnergy(1);
viewController.showText("Figuring this out costs you some mental energy. You have " + PC.getEnergy() + " points of energy left.");
}
this.endOfTurn(timeSpent);
} else if (energycost && PC.getEnergy() <= 0){
viewController.showText("You're exhausted and can't think about this kind of thing anymore.");
}
}
}
}
public void setOwner(LevelController levelController) {
this.owner = levelController;
}
public void offerViewController(ViewController viewController) {
viewController.giveControlTo(this.viewController);
}
public void setFailureResult(String string) {
this.failureResult = string;
}
public void setSuccessResult(Script script) {
this.successResult = script;
}
public void genericMessageReceived(){
finishedThinking();
}
public void setLectureMode(boolean b) {
viewController.setLectureMode(b);
}
public void finishedThinking(){
int correct = 0;
int score = 0;
List<BayesNode> priorNodes = new ArrayList<BayesNode>();
List<BayesNode> otherNodes = new ArrayList<BayesNode>();
Map<BayesNode,Fraction> probabilities = new HashMap<BayesNode,Fraction>();
for (BayesNode n : gameNet){
Fraction probability = n.getProbability();
probabilities.put(n, probability);
if (n.cptName.equals("Prior")){
priorNodes.add(n);
} else {
otherNodes.add(n);
}
}
int scoreThreshold = probabilities.size() / 2;
if (probabilities.size() % 2 == 1){
scoreThreshold++;
}
priorNodes.addAll(otherNodes);
for (BayesNode n : priorNodes){
n.observe();
gameNet.updateBeliefs();
Fraction oldProbability = probabilities.get(n);
boolean prediction = oldProbability.compareTo(Fraction.ONE_HALF) > 0;
Fraction newProbability = n.getProbability();
boolean actualValue = newProbability.equals(Fraction.ONE);
String adjective ="";
if (prediction == actualValue){
correct++;
adjective = " YAY! ";
if (correct > scoreThreshold){
score++;
adjective = adjective + "SCORE! ";
}
} else {
n.addProperty("misguessed");
}
viewController.showText("Variable " + n.type + ": had " + (int)(oldProbability.doubleValue()*100) + "% probability, prediction: " + prediction + ". Is " + actualValue + ". " + adjective + "Correct predictions: " + correct + ", score: " + score);
viewController.updateGraph();
}
if (correct == probabilities.size()){
int scorebonus = probabilities.size() / 2;
score = score + scorebonus;
viewController.showText("All predictions correct! Bonus score: " + scorebonus + ", total score: " + score);
}
clear(true);
}
}
|
package org.bimserver.geometry;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.bimserver.BimserverDatabaseException;
import org.bimserver.Color4f;
import org.bimserver.GenerateGeometryResult;
import org.bimserver.GeometryGeneratingException;
import org.bimserver.ObjectListener;
import org.bimserver.ObjectProviderProxy;
import org.bimserver.ProductDef;
import org.bimserver.Range;
import org.bimserver.TemporaryGeometryData;
import org.bimserver.database.DatabaseSession;
import org.bimserver.database.queries.QueryObjectProvider;
import org.bimserver.database.queries.om.Query;
import org.bimserver.database.queries.om.QueryPart;
import org.bimserver.models.geometry.GeometryPackage;
import org.bimserver.plugins.PluginConfiguration;
import org.bimserver.plugins.renderengine.EntityNotFoundException;
import org.bimserver.plugins.renderengine.Metrics;
import org.bimserver.plugins.renderengine.RenderEngine;
import org.bimserver.plugins.renderengine.RenderEngineException;
import org.bimserver.plugins.renderengine.RenderEngineFilter;
import org.bimserver.plugins.renderengine.RenderEngineGeometry;
import org.bimserver.plugins.renderengine.RenderEngineInstance;
import org.bimserver.plugins.renderengine.RenderEngineModel;
import org.bimserver.plugins.renderengine.RenderEngineSettings;
import org.bimserver.plugins.serializers.ObjectProvider;
import org.bimserver.plugins.serializers.OidConvertingSerializer;
import org.bimserver.plugins.serializers.StreamingSerializer;
import org.bimserver.plugins.serializers.StreamingSerializerPlugin;
import org.bimserver.renderengine.RenderEnginePool;
import org.bimserver.shared.HashMapVirtualObject;
import org.bimserver.shared.HashMapWrappedVirtualObject;
import org.bimserver.shared.QueryContext;
import org.bimserver.shared.WrappedVirtualObject;
import org.bimserver.utils.UuidUtils;
import org.eclipse.emf.ecore.EClass;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.primitives.UnsignedBytes;
public class GeometryRunner implements Runnable {
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(GeometryRunner.class);
private final StreamingGeometryGenerator streamingGeometryGenerator;
private EClass eClass;
private RenderEngineSettings renderEngineSettings;
private RenderEngineFilter renderEngineFilter;
private StreamingSerializerPlugin ifcSerializerPlugin;
private GenerateGeometryResult generateGeometryResult;
private ObjectProvider objectProvider;
private QueryContext queryContext;
private DatabaseSession databaseSession;
private RenderEnginePool renderEnginePool;
private boolean geometryReused;
private Map<Long, ProductDef> map;
private ReportJob job;
private boolean reuseGeometry;
private boolean writeOutputFiles = false;
private GeometryGenerationDebugger geometryGenerationDebugger;
private Query originalQuery;
public GeometryRunner(StreamingGeometryGenerator streamingGeometryGenerator, EClass eClass, RenderEnginePool renderEnginePool, DatabaseSession databaseSession, RenderEngineSettings renderEngineSettings, ObjectProvider objectProvider,
StreamingSerializerPlugin ifcSerializerPlugin, RenderEngineFilter renderEngineFilter, GenerateGeometryResult generateGeometryResult, QueryContext queryContext, boolean geometryReused,
Map<Long, ProductDef> map, ReportJob job, boolean reuseGeometry, GeometryGenerationDebugger geometryGenerationDebugger, Query query) {
this.streamingGeometryGenerator = streamingGeometryGenerator;
this.eClass = eClass;
this.renderEnginePool = renderEnginePool;
this.databaseSession = databaseSession;
this.renderEngineSettings = renderEngineSettings;
this.objectProvider = objectProvider;
this.ifcSerializerPlugin = ifcSerializerPlugin;
this.renderEngineFilter = renderEngineFilter;
this.generateGeometryResult = generateGeometryResult;
this.queryContext = queryContext;
this.geometryReused = geometryReused;
this.map = map;
this.job = job;
this.reuseGeometry = reuseGeometry;
this.geometryGenerationDebugger = geometryGenerationDebugger;
this.job.setUsesMapping(map != null);
this.originalQuery = query;
}
@Override
public void run() {
Thread.currentThread().setName("GeometryRunner");
long start = System.nanoTime();
job.setStartNanos(start);
// For all objects "hitchhiking" on this GeometryRunner, we also want to couple them to the job
if (map != null) {
for (long oid : map.keySet()) {
if (map.get(oid).getMasterOid() != oid) {
try {
job.addObject(oid, databaseSession.getEClassForOid(oid).getName());
} catch (BimserverDatabaseException e) {
e.printStackTrace();
}
}
}
}
try {
HashMapVirtualObject next = objectProvider.next();
Query query = new Query("Double buffer query " + eClass.getName(), this.streamingGeometryGenerator.packageMetaData);
QueryPart queryPart = query.createQueryPart();
while (next != null) {
long oid = next.getOid();
queryPart.addOid(oid);
if (eClass.isSuperTypeOf(next.eClass())) {
for (QueryPart qp : originalQuery.getQueryParts()) {
if (qp.getOids().contains(oid)) {
job.addObject(next.getOid(), next.eClass().getName());
}
}
}
next = objectProvider.next();
}
objectProvider = new QueryObjectProvider(databaseSession, this.streamingGeometryGenerator.bimServer, query, Collections.singleton(queryContext.getRoid()), this.streamingGeometryGenerator.packageMetaData);
StreamingSerializer serializer = ifcSerializerPlugin.createSerializer(new PluginConfiguration());
RenderEngine renderEngine = null;
byte[] bytes = null;
try {
final Set<HashMapVirtualObject> objects = new LinkedHashSet<>();
ObjectProviderProxy proxy = new ObjectProviderProxy(objectProvider, new ObjectListener() {
@Override
public void newObject(HashMapVirtualObject next) {
if (eClass.isSuperTypeOf(next.eClass())) {
if (next.eGet(GeometryRunner.this.streamingGeometryGenerator.representationFeature) != null) {
for (QueryPart qp : originalQuery.getQueryParts()) {
if (qp.getOids().contains(next.getOid())) {
objects.add(next);
}
}
}
}
}
});
serializer.init(proxy, null, null, this.streamingGeometryGenerator.bimServer.getPluginManager(), this.streamingGeometryGenerator.packageMetaData);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(serializer.getInputStream(), baos);
bytes = baos.toByteArray();
InputStream in = new ByteArrayInputStream(bytes);
Map<Long, HashMapVirtualObject> notFoundObjects = new HashMap<>();
Set<Range> reusableGeometryData = new HashSet<>();
Map<Long, TemporaryGeometryData> productToData = new HashMap<>();
try {
if (!objects.isEmpty()) {
renderEngine = renderEnginePool.borrowObject();
try (RenderEngineModel renderEngineModel = renderEngine.openModel(in, bytes.length)) {
renderEngineModel.setSettings(renderEngineSettings);
renderEngineModel.setFilter(renderEngineFilter);
try {
renderEngineModel.generateGeneralGeometry();
} catch (RenderEngineException e) {
if (e.getCause() instanceof java.io.EOFException) {
if (objects.isEmpty() || eClass.getName().equals("IfcAnnotation")) {
// SKIP
} else {
StreamingGeometryGenerator.LOGGER.error("Error in " + eClass.getName(), e);
}
}
}
OidConvertingSerializer oidConvertingSerializer = (OidConvertingSerializer) serializer;
Map<Long, Long> oidToEid = oidConvertingSerializer.getOidToEid();
Map<Long, DebuggingInfo> debuggingInfo = new HashMap<>();
for (HashMapVirtualObject ifcProduct : objects) {
if (!this.streamingGeometryGenerator.running) {
return;
}
Long expressId = oidToEid.get(ifcProduct.getOid());
try {
RenderEngineInstance renderEngineInstance = renderEngineModel.getInstanceFromExpressId(expressId);
RenderEngineGeometry geometry = renderEngineInstance.generateGeometry();
boolean translate = true;
if (geometry != null && geometry.getNrIndices() > 0) {
HashMapVirtualObject geometryInfo = new HashMapVirtualObject(queryContext, GeometryPackage.eINSTANCE.getGeometryInfo());
HashMapWrappedVirtualObject bounds = new HashMapWrappedVirtualObject(GeometryPackage.eINSTANCE.getBounds());
HashMapWrappedVirtualObject minBounds = new HashMapWrappedVirtualObject(GeometryPackage.eINSTANCE.getVector3f());
HashMapWrappedVirtualObject maxBounds = new HashMapWrappedVirtualObject(GeometryPackage.eINSTANCE.getVector3f());
minBounds.set("x", Double.POSITIVE_INFINITY);
minBounds.set("y", Double.POSITIVE_INFINITY);
minBounds.set("z", Double.POSITIVE_INFINITY);
maxBounds.set("x", -Double.POSITIVE_INFINITY);
maxBounds.set("y", -Double.POSITIVE_INFINITY);
maxBounds.set("z", -Double.POSITIVE_INFINITY);
geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_IfcProductOid(), ifcProduct.getOid());
geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_IfcProductUuid(), UuidUtils.toByteArray(ifcProduct.getUuid()));
geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_IfcProductRid(), ifcProduct.getRid());
geometryInfo.setReference(GeometryPackage.eINSTANCE.getGeometryInfo_Bounds(), bounds);
bounds.setReference(GeometryPackage.eINSTANCE.getBounds_Min(), minBounds);
bounds.setReference(GeometryPackage.eINSTANCE.getBounds_Max(), maxBounds);
HashMapWrappedVirtualObject boundsUntransformed = new HashMapWrappedVirtualObject(GeometryPackage.eINSTANCE.getBounds());
WrappedVirtualObject minBoundsUntranslated = new HashMapWrappedVirtualObject(GeometryPackage.eINSTANCE.getVector3f());
WrappedVirtualObject maxBoundsUntranslated = new HashMapWrappedVirtualObject(GeometryPackage.eINSTANCE.getVector3f());
minBoundsUntranslated.set("x", Double.POSITIVE_INFINITY);
minBoundsUntranslated.set("y", Double.POSITIVE_INFINITY);
minBoundsUntranslated.set("z", Double.POSITIVE_INFINITY);
maxBoundsUntranslated.set("x", -Double.POSITIVE_INFINITY);
maxBoundsUntranslated.set("y", -Double.POSITIVE_INFINITY);
maxBoundsUntranslated.set("z", -Double.POSITIVE_INFINITY);
boundsUntransformed.setReference(GeometryPackage.eINSTANCE.getBounds_Min(), minBoundsUntranslated);
boundsUntransformed.setReference(GeometryPackage.eINSTANCE.getBounds_Max(), maxBoundsUntranslated);
geometryInfo.setReference(GeometryPackage.eINSTANCE.getGeometryInfo_BoundsUntransformed(), boundsUntransformed);
double volume = 0;
volume = setCalculatedQuantities(renderEngineInstance, geometryInfo, volume);
HashMapVirtualObject geometryData = new HashMapVirtualObject(queryContext, GeometryPackage.eINSTANCE.getGeometryData());
geometryData.set("type", databaseSession.getCid(eClass));
ByteBuffer indices = geometry.getIndices();
IntBuffer indicesAsInt = indices.order(ByteOrder.LITTLE_ENDIAN).asIntBuffer();
geometryData.setAttribute(GeometryPackage.eINSTANCE.getGeometryData_Reused(), 1);
geometryData.setReference(GeometryPackage.eINSTANCE.getGeometryData_Indices(), createBuffer(queryContext, indices));
geometryData.set("nrIndices", indicesAsInt.capacity());
ByteBuffer vertices = geometry.getVertices();
DoubleBuffer verticesAsDouble = vertices.order(ByteOrder.LITTLE_ENDIAN).asDoubleBuffer();
geometryData.set("nrVertices", verticesAsDouble.capacity());
geometryData.setReference(GeometryPackage.eINSTANCE.getGeometryData_Vertices(), createBuffer(queryContext, vertices));
ByteBuffer normals = geometry.getNormals();
FloatBuffer normalsAsFloat = normals.order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer();
geometryData.set("nrNormals", normalsAsFloat.capacity());
geometryData.setReference(GeometryPackage.eINSTANCE.getGeometryData_Normals(), createBuffer(queryContext, normals));
ByteBuffer lineIndices = generateLineRendering(indicesAsInt);
geometryData.set("nrLineIndices", lineIndices.capacity() / 4);
geometryData.setReference(GeometryPackage.eINSTANCE.getGeometryData_LineIndices(), createBuffer(queryContext, lineIndices));
geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_PrimitiveCount(), indicesAsInt.capacity() / 3);
job.setTrianglesGenerated(indicesAsInt.capacity() / 3);
job.getReport().incrementTriangles(indicesAsInt.capacity() / 3);
streamingGeometryGenerator.cacheGeometryData(geometryData, vertices);
ColorMap colorMap = new ColorMap();
ByteBuffer colors = ByteBuffer.wrap(new byte[0]);
IntBuffer materialIndices = geometry.getMaterialIndices().order(ByteOrder.LITTLE_ENDIAN).asIntBuffer();
if (materialIndices != null && materialIndices.capacity() > 0) {
FloatBuffer materialsAsFloat = geometry.getMaterials().order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer();
boolean hasMaterial = false;
colors = ByteBuffer.allocate((verticesAsDouble.capacity() / 3) * 4);
double[] triangle = new double[9];
// LOGGER.info(ifcProduct.eClass().getName() + " " + ifcProduct.getOid());
// dump("Material indices", materialIndices);
// dump("Materials", materialsAsFloat);
for (int i = 0; i < materialIndices.capacity(); ++i) {
int c = materialIndices.get(i);
if (c > -1) {
Color4f color = new Color4f();
for (int l = 0; l < 4; ++l) {
float val = fixColor(materialsAsFloat.get(4 * c + l));
color.set(l, val);
}
if (color.isBlack()) {
continue;
}
for (int j = 0; j < 3; ++j) {
int k = indicesAsInt.get(i * 3 + j);
triangle[j * 3 + 0] = verticesAsDouble.get(3 * k);
triangle[j * 3 + 1] = verticesAsDouble.get(3 * k + 1);
triangle[j * 3 + 2] = verticesAsDouble.get(3 * k + 2);
hasMaterial = true;
for (int l = 0; l < 4; ++l) {
float val = fixColor(materialsAsFloat.get(4 * c + l));
colors.put(4 * k + l, UnsignedBytes.checkedCast((int)(val * 255)));
}
}
colorMap.addTriangle(triangle, color);
}
}
if (hasMaterial) {
ColorMap2 colorMap2 = new ColorMap2();
byte[] colorB = new byte[4];
for (int i=0; i<colors.capacity(); i+=4) {
colors.get(colorB);
colorMap2.addColor(colorB);
}
HashMapVirtualObject colorPack = new HashMapVirtualObject(queryContext, GeometryPackage.eINSTANCE.getColorPack());
colorPack.setAttribute(GeometryPackage.eINSTANCE.getColorPack_Data(), colorMap2.toByteArray());
colorPack.save();
geometryData.setReference(GeometryPackage.eINSTANCE.getGeometryData_ColorPack(), colorPack.getOid(), 0);
}
if (colorMap.usedColors() == 0) {
} else if (colorMap.usedColors() == 1) {
WrappedVirtualObject color = new HashMapWrappedVirtualObject(GeometryPackage.eINSTANCE.getVector4f());
Color4f firstColor = colorMap.getFirstColor();
color.set("x", firstColor.getR());
color.set("y", firstColor.getG());
color.set("z", firstColor.getB());
color.set("w", firstColor.getA());
geometryData.setReference(GeometryPackage.eINSTANCE.getGeometryData_Color(), color);
// This tells the code further on to not store this geometry, as it can be easily generated
hasMaterial = false;
} else {
Color4f mostUsed = colorMap.getMostUsedColor();
WrappedVirtualObject color = new HashMapWrappedVirtualObject(GeometryPackage.eINSTANCE.getVector4f());
color.set("x", mostUsed.getR());
color.set("y", mostUsed.getG());
color.set("z", mostUsed.getB());
color.set("w", mostUsed.getA());
geometryData.setReference(GeometryPackage.eINSTANCE.getGeometryData_MostUsedColor(), color);
}
if (hasMaterial) {
geometryData.set("nrColors", colors.capacity());
geometryData.setReference(GeometryPackage.eINSTANCE.getGeometryData_ColorsQuantized(), createBuffer(queryContext, colors), -1);
} else {
geometryData.set("nrColors", 0);
}
} else {
geometryData.set("nrColors", 0);
}
boolean hasTransparency = colorMap.hasTransparency();
double[] productTranformationMatrix = new double[16];
if (translate && renderEngineInstance.getTransformationMatrix() != null) {
productTranformationMatrix = renderEngineInstance.getTransformationMatrix();
} else {
Matrix.setIdentityM(productTranformationMatrix, 0);
}
geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_NrColors(), colors.position());
geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_NrVertices(), verticesAsDouble.capacity());
geometryInfo.setReference(GeometryPackage.eINSTANCE.getGeometryInfo_Data(), geometryData.getOid(), 0);
geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_HasTransparency(), hasTransparency);
geometryData.setAttribute(GeometryPackage.eINSTANCE.getGeometryData_HasTransparency(), hasTransparency);
long size = this.streamingGeometryGenerator.getSize(geometryData);
for (int i = 0; i < indicesAsInt.capacity(); i++) {
this.streamingGeometryGenerator.processExtends(minBounds, maxBounds, productTranformationMatrix, verticesAsDouble, indicesAsInt.get(i) * 3, generateGeometryResult);
this.streamingGeometryGenerator.processExtendsUntranslated(geometryInfo, verticesAsDouble, indicesAsInt.get(i) * 3, generateGeometryResult);
}
HashMapWrappedVirtualObject boundsUntransformedMm = createMmBounds(geometryInfo, boundsUntransformed, generateGeometryResult.getMultiplierToMm());
geometryInfo.set("boundsUntransformedMm", boundsUntransformedMm);
HashMapWrappedVirtualObject boundsMm = createMmBounds(geometryInfo, bounds, generateGeometryResult.getMultiplierToMm());
geometryInfo.set("boundsMm", boundsMm);
ByteBuffer normalsQuantized = quantizeNormals(normalsAsFloat);
geometryData.setReference(GeometryPackage.eINSTANCE.getGeometryData_NormalsQuantized(), createBuffer(queryContext, normalsQuantized));
HashMapWrappedVirtualObject geometryDataBounds = new HashMapWrappedVirtualObject(GeometryPackage.eINSTANCE.getBounds());
WrappedVirtualObject geometryDataBoundsMin = new HashMapWrappedVirtualObject(GeometryPackage.eINSTANCE.getVector3f());
WrappedVirtualObject geometryDataBoundsMax = new HashMapWrappedVirtualObject(GeometryPackage.eINSTANCE.getVector3f());
geometryDataBoundsMin.set("x", ((HashMapWrappedVirtualObject)boundsMm.get("min")).get("x"));
geometryDataBoundsMin.set("y", ((HashMapWrappedVirtualObject)boundsMm.get("min")).get("y"));
geometryDataBoundsMin.set("z", ((HashMapWrappedVirtualObject)boundsMm.get("min")).get("z"));
geometryDataBoundsMax.set("x", ((HashMapWrappedVirtualObject)boundsMm.get("max")).get("x"));
geometryDataBoundsMax.set("y", ((HashMapWrappedVirtualObject)boundsMm.get("max")).get("y"));
geometryDataBoundsMax.set("z", ((HashMapWrappedVirtualObject)boundsMm.get("max")).get("z"));
geometryDataBounds.setReference(GeometryPackage.eINSTANCE.getBounds_Min(), geometryDataBoundsMin);
geometryDataBounds.setReference(GeometryPackage.eINSTANCE.getBounds_Max(), geometryDataBoundsMax);
geometryData.setReference(GeometryPackage.eINSTANCE.getGeometryData_BoundsMm(), geometryDataBounds);
if (volume == 0) {
volume = getVolumeFromBounds(boundsUntransformed);
}
float nrTriangles = geometry.getNrIndices() / 3;
Density density = new Density(eClass.getName(), (float) volume, getBiggestFaceFromBounds(boundsUntransformedMm), (long) nrTriangles, geometryInfo.getOid());
geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_Density(), density.getDensityValue());
generateGeometryResult.addDensity(density);
double[] mibu = new double[] { (double) minBoundsUntranslated.eGet(GeometryPackage.eINSTANCE.getVector3f_X()), (double) minBoundsUntranslated.eGet(GeometryPackage.eINSTANCE.getVector3f_Y()),
(double) minBoundsUntranslated.eGet(GeometryPackage.eINSTANCE.getVector3f_Z()), 1d };
double[] mabu = new double[] { (double) maxBoundsUntranslated.eGet(GeometryPackage.eINSTANCE.getVector3f_X()), (double) maxBoundsUntranslated.eGet(GeometryPackage.eINSTANCE.getVector3f_Y()),
(double) maxBoundsUntranslated.eGet(GeometryPackage.eINSTANCE.getVector3f_Z()), 1d };
if (reuseGeometry) {
/* TODO It still happens that geometry that should be reused is not reused, one of the reasons is still concurrency:
* - When the same geometry is processed concurrently they could both do the hash check at a time when there is no cached version, then they both think it's non-reused geometry
*/
int hash = this.streamingGeometryGenerator.hash(indices, vertices, normals, colors);
int firstIndex = indicesAsInt.get(0);
int lastIndex = indicesAsInt.get(indicesAsInt.capacity() - 1);
double[] firstVertex = new double[] { verticesAsDouble.get(firstIndex), verticesAsDouble.get(firstIndex + 1), verticesAsDouble.get(firstIndex + 2) };
double[] lastVertex = new double[] { verticesAsDouble.get(lastIndex * 3), verticesAsDouble.get(lastIndex * 3 + 1), verticesAsDouble.get(lastIndex * 3 + 2) };
Range range = new Range(firstVertex, lastVertex);
Long referenceOid = this.streamingGeometryGenerator.hashes.get(hash);
if (referenceOid != null) {
HashMapVirtualObject referencedData = databaseSession.getFromCache(referenceOid);
if (referencedData == null) {
LOGGER.error("Object not found in cache: " + referenceOid + " (hash: " + hash + ")");
}
synchronized (referencedData) {
Integer currentValue = (Integer) referencedData.get("reused");
referencedData.set("reused", currentValue + 1);
}
HashMapWrappedVirtualObject dataBounds = (HashMapWrappedVirtualObject) referencedData.get("boundsMm");
extendBounds(boundsMm, dataBounds);
referencedData.saveOverwrite();
geometryInfo.setReference(GeometryPackage.eINSTANCE.getGeometryInfo_Data(), referenceOid, 0);
this.streamingGeometryGenerator.bytesSavedByHash.addAndGet(size);
} else if (geometryReused) {
// This is true when this geometry is part of a mapped item mapping (and used more than once)
boolean found = false;
// for (Range r :
// reusableGeometryData) {
// if (r.isSimilar(range)) {
// geometryInfo.setReference(GeometryPackage.eINSTANCE.getGeometryInfo_Data(),
// r.getGeometryDataOid(), 0);
// float[] offset =
// r.getOffset(range);
// ProductDef productDef =
// map.get(ifcProduct.getOid());
// double[] mappedItemMatrix =
// null;
// if (productDef != null &&
// productDef.getMatrix() !=
// null) {
// mappedItemMatrix =
// productDef.getMatrix();
// } else {
// Matrix.translateM(mappedItemMatrix,
// 0, offset[0], offset[1],
// offset[2]);
// double[] result = new
// double[16];
// Matrix.multiplyMM(result, 0,
// mappedItemMatrix, 0,
// productTranformationMatrix,
// setTransformationMatrix(geometryInfo,
// result); // Overwritten?
// bytesSavedByTransformation.addAndGet(size);
// found = true;
// break;
if (!found) {
range.setGeometryDataOid(geometryData.getOid());
reusableGeometryData.add(range);
volume = setCalculatedQuantities(renderEngineInstance, geometryInfo, volume);
geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_PrimitiveCount(), indicesAsInt.capacity() / 3);
productToData.put(ifcProduct.getOid(), new TemporaryGeometryData(geometryData.getOid(), renderEngineInstance.getAdditionalData(), indicesAsInt.capacity() / 3, size, mibu, mabu, indicesAsInt, verticesAsDouble, hasTransparency, colors.position()));
geometryData.save();
databaseSession.cache((HashMapVirtualObject) geometryData);
}
} else {
// if (sizes.containsKey(size)
// && sizes.get(size).eClass()
// == ifcProduct.eClass()) {
// LOGGER.info("More reuse might
// be possible " + size + " " +
// ifcProduct.eClass().getName()
// + ":" + ifcProduct.getOid() +
// sizes.get(size).eClass().getName()
// sizes.get(size).getOid());
// if (geometryReused) {
// range.setGeometryDataOid(geometryData.getOid());
// reusableGeometryData.add(range);
// productToData.put(ifcProduct.getOid(), new TemporaryGeometryData(geometryData.getOid(), renderEngineInstance.getArea(), renderEngineInstance.getVolume(), indices.length / 3, size, mibu, mabu, indices, vertices));
// } // TODO else??
// So reuse is on, the data was not found by hash, and this item is not in a mapped item
// By saving it before putting it in the cache/hashmap, we make sure we won't get a BimserverConcurrentModificationException
geometryData.save(); // TODO Why??
databaseSession.cache((HashMapVirtualObject) geometryData);
this.streamingGeometryGenerator.hashes.put(hash, geometryData.getOid());
// sizes.put(size, ifcProduct);
}
} else {
geometryData.save();
databaseSession.cache((HashMapVirtualObject) geometryData);
}
this.streamingGeometryGenerator.setTransformationMatrix(geometryInfo, productTranformationMatrix);
debuggingInfo.put(ifcProduct.getOid(), new DebuggingInfo(productTranformationMatrix, indices.asIntBuffer(), vertices.asFloatBuffer()));
geometryInfo.save();
this.streamingGeometryGenerator.totalBytes.addAndGet(size);
ifcProduct.setReference(this.streamingGeometryGenerator.geometryFeature, geometryInfo.getOid(), 0);
ifcProduct.saveOverwrite();
// Doing a sync here because probably
// writing large amounts of data, and db
// only syncs every 100.000 writes by
// default
// databaseSession.getKeyValueStore().sync();
} else {
// TODO
}
} catch (EntityNotFoundException e) {
// e.printStackTrace();
// As soon as we find a representation that
// is not Curve2D, then we should show a
// "INFO" message in the log to indicate
// there could be something wrong
boolean ignoreNotFound = eClass.getName().equals("IfcAnnotation");
// for (Object rep : representations) {
// if (rep instanceof
// IfcShapeRepresentation) {
// IfcShapeRepresentation
// ifcShapeRepresentation =
// (IfcShapeRepresentation)rep;
// (!"Curve2D".equals(ifcShapeRepresentation.getRepresentationType()))
// ignoreNotFound = false;
if (!ignoreNotFound) {
// LOGGER.warn("Entity not found " +
// ifcProduct.eClass().getName() + " " +
// (expressId) + "/" +
// ifcProduct.getOid());
notFoundObjects.put(expressId, ifcProduct);
}
} catch (BimserverDatabaseException | RenderEngineException e) {
StreamingGeometryGenerator.LOGGER.error("", e);
}
}
if (geometryReused && map != null) {
// We pick the first product and use that product to try and get the original data
long firstKey = map.keySet().iterator().next();
ProductDef masterProductDef = map.get(firstKey);
for (long key : map.keySet()) {
if (key != firstKey) {
ProductDef productDef = map.get(key);
HashMapVirtualObject ifcProduct = productDef.getObject();
TemporaryGeometryData masterGeometryData = productToData.get(productDef.getMasterOid());
if (masterGeometryData != null) {
HashMapVirtualObject geometryInfo = new HashMapVirtualObject(queryContext, GeometryPackage.eINSTANCE.getGeometryInfo());
HashMapWrappedVirtualObject bounds = new HashMapWrappedVirtualObject(GeometryPackage.eINSTANCE.getBounds());
HashMapWrappedVirtualObject minBounds = new HashMapWrappedVirtualObject(GeometryPackage.eINSTANCE.getVector3f());
HashMapWrappedVirtualObject maxBounds = new HashMapWrappedVirtualObject(GeometryPackage.eINSTANCE.getVector3f());
geometryInfo.setReference(GeometryPackage.eINSTANCE.getGeometryInfo_Bounds(), bounds);
geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_HasTransparency(), masterGeometryData.hasTransparancy());
geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_NrColors(), masterGeometryData.getNrColors());
geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_NrVertices(), masterGeometryData.getNrVertices());
bounds.set("min", minBounds);
bounds.set("max", maxBounds);
minBounds.set("x", Double.POSITIVE_INFINITY);
minBounds.set("y", Double.POSITIVE_INFINITY);
minBounds.set("z", Double.POSITIVE_INFINITY);
maxBounds.set("x", -Double.POSITIVE_INFINITY);
maxBounds.set("y", -Double.POSITIVE_INFINITY);
maxBounds.set("z", -Double.POSITIVE_INFINITY);
double[] mibu = masterGeometryData.getMibu();
double[] mabu = masterGeometryData.getMabu();
HashMapWrappedVirtualObject boundsUntransformed = new HashMapWrappedVirtualObject(GeometryPackage.eINSTANCE.getBounds());
WrappedVirtualObject minBoundsUntransformed = new HashMapWrappedVirtualObject(GeometryPackage.eINSTANCE.getVector3f());
WrappedVirtualObject maxBoundsUntransformed = new HashMapWrappedVirtualObject(GeometryPackage.eINSTANCE.getVector3f());
minBoundsUntransformed.set("x", mibu[0]);
minBoundsUntransformed.set("y", mibu[1]);
minBoundsUntransformed.set("z", mibu[2]);
maxBoundsUntransformed.set("x", mabu[0]);
maxBoundsUntransformed.set("y", mabu[1]);
maxBoundsUntransformed.set("z", mabu[2]);
geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_IfcProductOid(), ifcProduct.getOid());
geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_IfcProductUuid(), UuidUtils.toByteArray(ifcProduct.getUuid()));
geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_IfcProductRid(), ifcProduct.getRid());
boundsUntransformed.setReference(GeometryPackage.eINSTANCE.getBounds_Min(), minBoundsUntransformed);
boundsUntransformed.setReference(GeometryPackage.eINSTANCE.getBounds_Max(), maxBoundsUntransformed);
geometryInfo.setReference(GeometryPackage.eINSTANCE.getGeometryInfo_BoundsUntransformed(), boundsUntransformed);
double volume = 0;
if (streamingGeometryGenerator.isCalculateQuantities()) {
ObjectNode additionalData = masterGeometryData.getAdditionalData();
if (additionalData != null) {
geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_AdditionalData(), additionalData.toString());
if (additionalData.has("TOTAL_SURFACE_AREA")) {
geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_Area(), additionalData.get("TOTAL_SURFACE_AREA").asDouble());
}
if (additionalData.has("TOTAL_SHAPE_VOLUME")) {
volume = additionalData.get("TOTAL_SHAPE_VOLUME").asDouble();
geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_Volume(), volume);
}
}
}
geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_PrimitiveCount(), masterGeometryData.getNrPrimitives());
job.getReport().incrementTriangles(masterGeometryData.getNrPrimitives());
this.streamingGeometryGenerator.bytesSavedByMapping.addAndGet(masterGeometryData.getSize());
this.streamingGeometryGenerator.totalBytes.addAndGet(masterGeometryData.getSize());
// First, invert the master's mapping matrix
double[] inverted = Matrix.identity();
if (!Matrix.invertM(inverted, 0, masterProductDef.getMappingMatrix(), 0)) {
LOGGER.info("No inverse, this should not be able to happen at this time, please report");
continue;
}
double[] finalMatrix = Matrix.identity();
double[] totalTranformationMatrix = Matrix.identity();
// Apply the mapping matrix of the product
Matrix.multiplyMM(finalMatrix, 0, productDef.getMappingMatrix(), 0, inverted, 0);
// Apply the product matrix of the product
Matrix.multiplyMM(totalTranformationMatrix, 0, productDef.getProductMatrix(), 0, finalMatrix, 0);
if (geometryGenerationDebugger != null) {
// if (debuggingInfo.containsKey(ifcProduct.getOid())) {
// DebuggingInfo debuggingInfo2 = debuggingInfo.get(ifcProduct.getOid());
// DebuggingInfo debuggingInfo3 = debuggingInfo.get(productDef.getMasterOid());
// if (debuggingInfo2.getIndices().length != debuggingInfo3.getIndices().length) {
// LOGGER.error("Different sizes for indices, weird...");
// LOGGER.error(ifcProduct.getOid() + " / " + productDef.getMasterOid());
// } else {
// for (int i=0; i<debuggingInfo2.getIndices().length; i++) {
// int index = debuggingInfo2.getIndices()[i];
// float[] vertex = new float[]{debuggingInfo2.getVertices()[index * 3], debuggingInfo2.getVertices()[index * 3 + 1], debuggingInfo2.getVertices()[index * 3 + 2], 1};
// float[] transformedOriginal = new float[4];
// Matrix.multiplyMV(transformedOriginal, 0, debuggingInfo2.getProductTranformationMatrix(), 0, vertex, 0);
// float[] transformedNew = new float[4];
// int index2 = debuggingInfo3.getIndices()[i];
// float[] vertex2 = new float[]{debuggingInfo3.getVertices()[index2 * 3], debuggingInfo3.getVertices()[index2 * 3 + 1], debuggingInfo3.getVertices()[index2 * 3 + 2], 1};
// Matrix.multiplyMV(transformedNew, 0, totalTranformationMatrix, 0, vertex2, 0);
// // TODO margin should depend on bb of complete model
// if (!almostTheSame((String)ifcProduct.get("GlobalId"), transformedNew, transformedOriginal, 0.05F)) {
// geometryGenerationDebugger.transformedVertexNotMatching(ifcProduct, transformedOriginal, transformedNew, debuggingInfo2.getProductTranformationMatrix(), totalTranformationMatrix);
// almostTheSame((String)ifcProduct.get("GlobalId"), debuggingInfo2.getProductTranformationMatrix(), totalTranformationMatrix, 0.01D);
}
IntBuffer indices = masterGeometryData.getIndices();
for (int i = 0; i < indices.capacity(); i++) {
this.streamingGeometryGenerator.processExtends(minBounds, maxBounds, totalTranformationMatrix, masterGeometryData.getVertices(), indices.get(i) * 3, generateGeometryResult);
}
HashMapWrappedVirtualObject boundsUntransformedMm = createMmBounds(geometryInfo, boundsUntransformed, generateGeometryResult.getMultiplierToMm());
geometryInfo.set("boundsUntransformedMm", boundsUntransformedMm);
HashMapWrappedVirtualObject boundsMm = createMmBounds(geometryInfo, bounds, generateGeometryResult.getMultiplierToMm());
geometryInfo.set("boundsMm", boundsMm);
float nrTriangles = masterGeometryData.getNrPrimitives();
Density density = new Density(eClass.getName(), (float) volume, getBiggestFaceFromBounds(boundsUntransformedMm), (long) nrTriangles, geometryInfo.getOid());
geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_Density(), density.getDensityValue());
generateGeometryResult.addDensity(density);
HashMapVirtualObject referencedData = databaseSession.getFromCache(masterGeometryData.getOid());
Integer currentValue = (Integer) referencedData.get("reused");
referencedData.set("reused", currentValue + 1);
HashMapWrappedVirtualObject dataBounds = (HashMapWrappedVirtualObject) referencedData.get("boundsMm");
extendBounds(boundsMm, dataBounds);
// TODO this keeping track of the amount of reuse, takes it's toll on memory usage. Basically all geometry ends up in memory by the time the Geometry generation is done
// We should try to see whether we can use BDB's mechanism to do partial retrievals/updates of a records here, because we only need to update just one value
// Another, simpler option would be to introduce another layer between GeometryInfo and GeometryData, so we don't have to cache the actual data (vertices etc... the bulk)
// In that case however the BinarySerializer would increase in complexity
// This seems to have been partially solved now since GeometryData does not contain the bulk of the data anymore (the byte[]s are now in "Buffer").
referencedData.saveOverwrite();
geometryInfo.setReference(GeometryPackage.eINSTANCE.getGeometryInfo_Data(), masterGeometryData.getOid(), 0);
// for (int i = 0; i <
// indices.length; i++) {
// processExtends(geometryInfo,
// productTranformationMatrix,
// vertices, indices[i] * 3,
// generateGeometryResult);
// processExtendsUntranslated(geometryInfo,
// vertices, indices[i] * 3,
// generateGeometryResult);
// calculateObb(geometryInfo,
// productTranformationMatrix,
// indices, vertices,
// generateGeometryResult);
this.streamingGeometryGenerator.setTransformationMatrix(geometryInfo, totalTranformationMatrix);
geometryInfo.save();
// totalBytes.addAndGet(size);
ifcProduct.setReference(this.streamingGeometryGenerator.geometryFeature, geometryInfo.getOid(), 0);
ifcProduct.saveOverwrite();
}
}
}
}
}
}
} finally {
if (renderEngine != null) {
Metrics metrics = renderEngine.getMetrics();
if (metrics != null) {
job.setCpuTimeMs(metrics.getCpuTimeMs());
job.setMaxMemoryBytes(metrics.getMaxMemoryBytes());
}
renderEnginePool.returnObject(renderEngine);
}
try {
if (!notFoundObjects.isEmpty()) {
writeDebugFile(bytes, false, notFoundObjects);
StringBuilder sb = new StringBuilder();
for (Long key : notFoundObjects.keySet()) {
sb.append(key + " (" + notFoundObjects.get(key).getOid() + ")");
sb.append(", ");
}
sb.delete(sb.length() - 2, sb.length());
job.setException(new Exception("Missing objects in model (" + sb.toString() + ")"));
} else if (writeOutputFiles) {
writeDebugFile(bytes, false, null);
}
in.close();
} catch (Throwable e) {
} finally {
}
this.streamingGeometryGenerator.jobsDone.incrementAndGet();
this.streamingGeometryGenerator.updateProgress();
}
} catch (Exception e) {
StreamingGeometryGenerator.LOGGER.error("", e);
writeDebugFile(bytes, true, null);
job.setException(e);
// LOGGER.error("Original query: " + originalQuery, e);
}
} catch (Exception e) {
StreamingGeometryGenerator.LOGGER.error("", e);
// LOGGER.error("Original query: " + originalQuery, e);
}
long end = System.nanoTime();
job.setEndNanos(end);
}
private void dump(String string, IntBuffer materialIndices) {
StringBuilder sb = new StringBuilder();
for (int i=0; i<materialIndices.capacity(); i++) {
sb.append(materialIndices.get(i) + ", ");
}
LOGGER.info(string + ": " + sb.toString());
}
private void dump(String string, FloatBuffer floatBuffer) {
StringBuilder sb = new StringBuilder();
for (int i=0; i<floatBuffer.capacity(); i++) {
sb.append(floatBuffer.get(i) + ", ");
}
LOGGER.info(string + ": " + sb.toString());
}
private double setCalculatedQuantities(RenderEngineInstance renderEngineInstance, HashMapVirtualObject geometryInfo, double volume) throws RenderEngineException, BimserverDatabaseException {
if (streamingGeometryGenerator.isCalculateQuantities()) {
ObjectNode additionalData = renderEngineInstance.getAdditionalData();
if (additionalData != null) {
geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_AdditionalData(), additionalData.toString());
if (additionalData.has("TOTAL_SURFACE_AREA")) {
geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_Area(), additionalData.get("TOTAL_SURFACE_AREA").asDouble());
}
if (additionalData.has("TOTAL_SHAPE_VOLUME")) {
volume = additionalData.get("TOTAL_SHAPE_VOLUME").asDouble();
geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_Volume(), volume);
}
}
}
return volume;
}
private ByteBuffer generateLineRendering(IntBuffer indicesAsInt) {
Set<Line> lines = new HashSet<>();
for (int i=0; i<indicesAsInt.capacity(); i+=3) {
for (int j=0; j<3; j++) {
int index1 = indicesAsInt.get(i + j);
int index2 = indicesAsInt.get(i + (j + 1) % 3);
Line line = new Line(index1, index2);
if (lines.contains(line)) {
lines.remove(line);
} else {
lines.add(line);
}
}
}
ByteBuffer byteBuffer = ByteBuffer.allocate(lines.size() * 2 * 4).order(ByteOrder.LITTLE_ENDIAN);
IntBuffer newIndices = byteBuffer.asIntBuffer();
for (Line line : lines) {
newIndices.put(line.getIndex1());
newIndices.put(line.getIndex2());
}
return byteBuffer;
}
private float fixColor(float input) {
if (input >= 0 && input <=1) {
return input;
}
return 0.5f;
}
private long createBuffer(QueryContext queryContext, ByteBuffer data) throws BimserverDatabaseException {
HashMapVirtualObject buffer = new HashMapVirtualObject(queryContext, GeometryPackage.eINSTANCE.getBuffer());
buffer.set("data", data.array());
buffer.save();
return buffer.getOid();
}
private ByteBuffer quantizeColors(byte[] vertex_colors) {
ByteBuffer quantizedColors = ByteBuffer.wrap(new byte[vertex_colors.length]);
for (int i=0; i<vertex_colors.length; i++) {
float c = vertex_colors[i];
quantizedColors.put(UnsignedBytes.checkedCast((int) (c * 255)));
}
return quantizedColors;
}
private ByteBuffer quantizeNormals(FloatBuffer normals) {
ByteBuffer quantizedNormals = ByteBuffer.wrap(new byte[normals.capacity()]);
quantizedNormals.order(ByteOrder.LITTLE_ENDIAN);
for (int i=0; i<normals.capacity(); i++) {
float normal = normals.get(i);
quantizedNormals.put((byte)(normal * 127));
}
return quantizedNormals;
}
private float[] createQuantizationMatrixFromBounds(HashMapWrappedVirtualObject boundsMm) {
float[] matrix = Matrix.identityF();
float scale = 32768;
HashMapWrappedVirtualObject min = (HashMapWrappedVirtualObject) boundsMm.get("min");
HashMapWrappedVirtualObject max = (HashMapWrappedVirtualObject) boundsMm.get("max");
// Move the model with its center to the origin
Matrix.translateM(matrix, 0, (float)(-((double)max.eGet("x") + (double)min.eGet("x")) / 2f), (float)(-((double)max.eGet("y") + (double)min.eGet("y")) / 2f), (float)(-((double)max.eGet("z") + (double)min.eGet("z")) / 2f));
// Scale the model to make sure all values fit within a 2-byte signed short
Matrix.scaleM(matrix, 0, (float)(scale / ((double)max.eGet("x") - (double)min.eGet("x"))), (float)(scale / ((double)max.eGet("y") - (double)min.eGet("y"))), (float)(scale / ((double)max.eGet("z") - (double)min.eGet("z"))));
return matrix;
}
private ByteBuffer quantizeVertices(float[] vertices, float[] quantizationMatrix, float multiplierToMm) {
ByteBuffer quantizedBuffer = ByteBuffer.wrap(new byte[vertices.length * 2]);
quantizedBuffer.order(ByteOrder.LITTLE_ENDIAN);
float[] vertex = new float[4];
float[] result = new float[4];
vertex[3] = 1;
int nrVertices = vertices.length;
for (int i=0; i<nrVertices; i+=3) {
vertex[0] = vertices[i];
vertex[1] = vertices[i+1];
vertex[2] = vertices[i+2];
if (multiplierToMm != 1f) {
vertex[0] = vertex[0] * multiplierToMm;
vertex[1] = vertex[1] * multiplierToMm;
vertex[2] = vertex[2] * multiplierToMm;
}
Matrix.multiplyMV(result, 0, quantizationMatrix, 0, vertex, 0);
quantizedBuffer.putShort((short)result[0]);
quantizedBuffer.putShort((short)result[1]);
quantizedBuffer.putShort((short)result[2]);
}
return quantizedBuffer;
}
private void extendBounds(HashMapWrappedVirtualObject source, HashMapWrappedVirtualObject target) throws BimserverDatabaseException {
HashMapWrappedVirtualObject sourceMin = (HashMapWrappedVirtualObject) source.eGet("min");
HashMapWrappedVirtualObject sourceMax = (HashMapWrappedVirtualObject) source.eGet("max");
HashMapWrappedVirtualObject targetMin = (HashMapWrappedVirtualObject) target.eGet("min");
HashMapWrappedVirtualObject targetMax = (HashMapWrappedVirtualObject) target.eGet("max");
extendMin(sourceMin, targetMin);
extendMax(sourceMax, targetMax);
}
private void extendMin(HashMapWrappedVirtualObject sourceMin, HashMapWrappedVirtualObject targetMin) throws BimserverDatabaseException {
if (((double)sourceMin.get("x")) < (double)targetMin.get("x")) {
targetMin.set("x", sourceMin.get("x"));
}
if (((double)sourceMin.get("y")) < (double)targetMin.get("y")) {
targetMin.set("y", sourceMin.get("y"));
}
if (((double)sourceMin.get("z")) < (double)targetMin.get("z")) {
targetMin.set("z", sourceMin.get("z"));
}
}
private void extendMax(HashMapWrappedVirtualObject sourceMax, HashMapWrappedVirtualObject targetMax) throws BimserverDatabaseException {
if (((double)sourceMax.get("x")) > (double)targetMax.get("x")) {
targetMax.set("x", sourceMax.get("x"));
}
if (((double)sourceMax.get("y")) > (double)targetMax.get("y")) {
targetMax.set("y", sourceMax.get("y"));
}
if (((double)sourceMax.get("z")) > (double)targetMax.get("z")) {
targetMax.set("z", sourceMax.get("z"));
}
}
private float getVolumeFromBounds(HashMapWrappedVirtualObject bounds) throws GeometryGeneratingException {
HashMapWrappedVirtualObject min = (HashMapWrappedVirtualObject) bounds.eGet("min");
HashMapWrappedVirtualObject max = (HashMapWrappedVirtualObject) bounds.eGet("max");
double minX = (double)min.eGet(min.eClass().getEStructuralFeature("x"));
double minY = (double)min.eGet(min.eClass().getEStructuralFeature("y"));
double minZ = (double)min.eGet(min.eClass().getEStructuralFeature("z"));
double maxX = (double)max.eGet(max.eClass().getEStructuralFeature("x"));
double maxY = (double)max.eGet(max.eClass().getEStructuralFeature("y"));
double maxZ = (double)max.eGet(max.eClass().getEStructuralFeature("z"));
float volume = (float) (
(maxX - minX) *
(maxY - minY) *
(maxZ - minZ));
if (volume == 0f) {
volume = 0.00001f;
}
return volume;
}
private float getBiggestFaceFromBounds(HashMapWrappedVirtualObject bounds) throws GeometryGeneratingException {
HashMapWrappedVirtualObject min = (HashMapWrappedVirtualObject) bounds.eGet("min");
HashMapWrappedVirtualObject max = (HashMapWrappedVirtualObject) bounds.eGet("max");
double minX = (double)min.eGet(min.eClass().getEStructuralFeature("x"));
double minY = (double)min.eGet(min.eClass().getEStructuralFeature("y"));
double minZ = (double)min.eGet(min.eClass().getEStructuralFeature("z"));
double maxX = (double)max.eGet(max.eClass().getEStructuralFeature("x"));
double maxY = (double)max.eGet(max.eClass().getEStructuralFeature("y"));
double maxZ = (double)max.eGet(max.eClass().getEStructuralFeature("z"));
float front = (float) ((maxX - minX) * (maxY - minY));
float top = (float) ((maxX - minX) * (maxZ - minZ));
float side = (float) ((maxY - minY) * (maxZ - minZ));
return Math.max(Math.max(front, top), side);
}
private HashMapWrappedVirtualObject createMmBounds(HashMapVirtualObject geometryInfo, HashMapWrappedVirtualObject boundsUntransformed, float toMmFactor) throws BimserverDatabaseException {
HashMapWrappedVirtualObject boundsMm = new HashMapWrappedVirtualObject(GeometryPackage.eINSTANCE.getBounds());
WrappedVirtualObject minBoundsMm = new HashMapWrappedVirtualObject(GeometryPackage.eINSTANCE.getVector3f());
WrappedVirtualObject maxBoundsMm = new HashMapWrappedVirtualObject(GeometryPackage.eINSTANCE.getVector3f());
boundsMm.setReference(GeometryPackage.eINSTANCE.getBounds_Min(), minBoundsMm);
boundsMm.setReference(GeometryPackage.eINSTANCE.getBounds_Max(), maxBoundsMm);
HashMapWrappedVirtualObject min = (HashMapWrappedVirtualObject) boundsUntransformed.eGet("min");
HashMapWrappedVirtualObject max = (HashMapWrappedVirtualObject) boundsUntransformed.eGet("max");
minBoundsMm.set("x", toMmFactor * (double)min.eGet("x"));
minBoundsMm.set("y", toMmFactor * (double)min.eGet("y"));
minBoundsMm.set("z", toMmFactor * (double)min.eGet("z"));
maxBoundsMm.set("x", toMmFactor * (double)max.eGet("x"));
maxBoundsMm.set("y", toMmFactor * (double)max.eGet("y"));
maxBoundsMm.set("z", toMmFactor * (double)max.eGet("z"));
return boundsMm;
}
private boolean almostTheSame(String identifier, double[] a, double[] b, double margin) {
if (a.length != b.length) {
throw new RuntimeException("Unequal sizes");
}
for (int i=0; i<a.length; i++) {
double q = a[i];
double r = b[i];
if (Math.abs(q - r) < margin) {
} else {
System.out.println("Not the same " + identifier);
Matrix.dump(a);
Matrix.dump(b);
return false;
}
}
return true;
}
private boolean almostTheSame(String identifier, float[] a, float[] b, float margin) {
if (a.length != b.length) {
throw new RuntimeException("Unequal sizes");
}
for (int i=0; i<a.length; i++) {
double q = a[i];
double r = b[i];
if (Math.abs(q - r) < margin) {
} else {
return false;
}
}
return true;
}
private synchronized void writeDebugFile(byte[] bytes, boolean error, Map<Long, HashMapVirtualObject> notFoundObjects) throws FileNotFoundException, IOException {
boolean debug = true;
if (debug) {
Path debugPath = this.streamingGeometryGenerator.bimServer.getHomeDir().resolve("debug");
if (!Files.exists(debugPath)) {
Files.createDirectories(debugPath);
}
Path folder = debugPath.resolve(this.streamingGeometryGenerator.getDebugIdentifier());
if (!Files.exists(folder)) {
Files.createDirectories(folder);
}
String basefilenamename = "all";
if (eClass != null) {
basefilenamename = eClass.getName();
}
if (error) {
basefilenamename += "-error";
}
Path file = folder.resolve(basefilenamename + "-" + job.getId() + ".ifc");
job.getReport().addDebugFile(file.toString(), job.getId());
// if (notFoundObjects != null) {
// StringBuilder sb = new StringBuilder();
// for (Integer expressId : notFoundObjects.keySet()) {
// sb.append(notFoundObjects.get(expressId) + ": " + expressId + "\r\n");
// FileUtils.writeStringToFile(Paths.get(file.toAbsolutePath().toString() + ".txt").toFile(), sb.toString());
// StreamingGeometryGenerator.LOGGER.info("Writing debug file to " + file.toAbsolutePath().toString());
FileUtils.writeByteArrayToFile(file.toFile(), bytes);
}
}
}
|
package org.avallach.daedalus.ide.highlighting;
import com.intellij.codeHighlighting.TextEditorHighlightingPassRegistrar;
import com.intellij.codeInsight.daemon.impl.HighlightInfoType;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.markup.EffectType;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.ui.JBColor;
import java.awt.*;
public class ReferenceHighlighter extends PsiHighlighterFactoryBase {
public static HighlightInfoType unresolvedReferenceHighlight = new HighlightInfoType.HighlightInfoTypeImpl(
HighlightSeverity.INFORMATION,
TextAttributesKey.createTextAttributesKey(
"UNRESOLVED_REFERENCE",
new TextAttributes
(
JBColor.RED,
null,
JBColor.RED,
EffectType.WAVE_UNDERSCORE,
Font.PLAIN
))
);
public ReferenceHighlighter(Project project, TextEditorHighlightingPassRegistrar registrar) {
super(project, registrar);
}
private boolean isUnresolvedReference(PsiElement element) {
PsiReference reference = element.getReference();
return reference != null && reference.resolve() == null;
}
@Override
protected HighlightInfoType getStyle(PsiElement element) {
return isUnresolvedReference(element) ? unresolvedReferenceHighlight : null;
}
}
|
// RMG - Reaction Mechanism Generator
// RMG Team (rmg_dev@mit.edu)
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
package jing.rxn;
import jing.param.Pressure;
import jing.param.Temperature;
import jing.rxnSys.Logger;
/**
* A model of pressure-dependent reaction kinetics k(T, P) of the form
*
* k(T, P) = A(P) * T ^ n(P) * exp( -Ea(P) / R * T )
*
* The values of A(P), n(P), and Ea(P) are stored for multiple pressures and
* interpolation on a log P scale is used.
*
* @author jwallen
*/
public class PDepArrheniusKinetics implements PDepKinetics {
/**
* The list of pressures at which we have Arrhenius parameters.
*/
public Pressure[] pressures;
/**
* The list of Arrhenius kinetics fitted at each pressure.
*/
private ArrheniusKinetics[] kinetics;
protected int numPressures = 0;
public PDepArrheniusKinetics(int numP) {
pressures = new Pressure[numP];
kinetics = new ArrheniusKinetics[numP];
setNumPressures(numP);
}
public void setKinetics(int index, Pressure P, ArrheniusKinetics kin) {
if (index < 0 || index >= pressures.length)
throw new RuntimeException(String.format("Cannot set kinetics with index %s because array is only of size %s",index,pressures.length));
pressures[index] = P;
kinetics[index] = kin;
}
/**
* Calculate the rate cofficient at the specified conditions.
* @param T The temperature of interest
* @param P The pressure of interest
* @return The rate coefficient evaluated at T and P
*/
public double calculateRate(Temperature T, Pressure P) {
int index1 = -1; int index2 = -1;
for (int i = 0; i < pressures.length - 1; i++) {
if (pressures[i].getBar() <= P.getBar() && P.getBar() <= pressures[i+1].getBar()) {
index1 = i;
index2 = i + 1;
break;
}
}
/* Chemkin 4 theory manual specifies:
"If the rate of the reaction is desired for a pressure lower than
any of those provided, the rate parameters provided for the lowest
pressure are used. Likewise, if rate of the reaction is desired for
a pressure higher than any of those provided, the rate parameters
provided for the highest pressure are used."
We take the same approach here, but warn the user (so they can fix their input file).
*/
if (P.getPa() < pressures[0].getPa())
{
Logger.warning(String.format("Tried to evaluate rate coefficient at P=%.3g Atm, which is below minimum for this PLOG rate.",P.getAtm()));
Logger.warning(String.format("Using rate for minimum %s Atm instead", pressures[0].getAtm() ));
return kinetics[0].calculateRate(T);
}
if (P.getPa() > pressures[pressures.length-1].getPa())
{
Logger.warning(String.format("Tried to evaluate rate coefficient at P=%.3g Atm, which is above maximum for this PLOG rate.",P.getAtm()));
Logger.warning(String.format("Using rate for maximum %s Atm instead", pressures[pressures.length-1].getAtm() ));
return kinetics[pressures.length-1].calculateRate(T);
}
double logk1 = Math.log10(kinetics[index1].calculateRate(T));
double logk2 = Math.log10(kinetics[index2].calculateRate(T));
double logP0 = Math.log10(P.getBar());
double logP1 = Math.log10(pressures[index1].getBar());
double logP2 = Math.log10(pressures[index2].getBar());
// We can't take logarithms of k=0 and get meaningful interpolation, so we have to do something weird.
// The approach used here is arbitrary, but at least it gives a continuous k(P) function.
// If interpolating between k1=0 and k2=0, return k=0
if (logk1 == Double.NEGATIVE_INFINITY && logk2 == Double.NEGATIVE_INFINITY)
return 0.0;
// if interpolating between k1=0 and k2>0, set k1 to something small but nonzero.
else if (logk1 == Double.NEGATIVE_INFINITY)
logk1 = Math.min(0, logk2-1); // k1 is a small 1 cm3/mol/sec, or k2/10 if that's even smaller.
// if interpolating between k1>0 and k2=0, set k2 to something small but nonzero.
else if (logk2 == Double.NEGATIVE_INFINITY)
logk2 = Math.min(0, logk1-1); // k2 is a small 1 cm3/mol/sec, or k1/10 if that's even smaller.
double logk0 = logk1 + (logk2 - logk1) / (logP2 - logP1) * (logP0 - logP1);
return Math.pow(10, logk0);
}
public String toChemkinString() {
String result = "";
for (int i = 0; i < pressures.length; i++) {
double Ea_in_kcalmol = kinetics[i].getEValue();
double Ea = 0.0;
if (ArrheniusKinetics.getEaUnits().equals("kcal/mol")) Ea = Ea_in_kcalmol;
else if (ArrheniusKinetics.getEaUnits().equals("cal/mol")) Ea = Ea_in_kcalmol * 1000.0;
else if (ArrheniusKinetics.getEaUnits().equals("kJ/mol")) Ea = Ea_in_kcalmol * 4.184;
else if (ArrheniusKinetics.getEaUnits().equals("J/mol")) Ea = Ea_in_kcalmol * 4184.0;
else if (ArrheniusKinetics.getEaUnits().equals("Kelvins")) Ea = Ea_in_kcalmol / 1.987e-3;
result += String.format("PLOG / %10s %10.2e %10s %10s /\n",
pressures[i].getAtm(),
kinetics[i].getAValue(),
kinetics[i].getNValue(),
Ea);
}
return result;
}
public void setNumPressures(int numP) {
numPressures = numP;
}
public int getNumPressures() {
return numPressures;
}
public ArrheniusKinetics getKinetics(int i) {
return kinetics[i];
}
public void setPressures(Pressure[] ListOfPressures) {
pressures = ListOfPressures;
}
public void setRateCoefficients(ArrheniusKinetics[] ListOfKinetics) {
kinetics = ListOfKinetics;
}
public Pressure getPressure(int i) {
return pressures[i];
}
}
|
package org.helioviewer.jhv.layers.spaceobject;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import org.helioviewer.jhv.astronomy.Frame;
import org.helioviewer.jhv.astronomy.SpaceObject;
import org.helioviewer.jhv.astronomy.UpdateViewpoint;
import org.helioviewer.jhv.gui.components.base.JHVTableCellRenderer;
import org.json.JSONArray;
@SuppressWarnings("serial")
public class SpaceObjectContainer extends JScrollPane {
private static final int ICON_WIDTH = 12;
private static final int NUMBEROFVISIBLEROWS = 5;
private static final int SELECTED_COL = 0;
private static final int OBJECT_COL = 1;
private static final int STATUS_COL = 2;
private final UpdateViewpoint uv;
private final boolean exclusive;
private final SpaceObjectModel model = new SpaceObjectModel();
private Frame frame;
private long startTime;
private long endTime;
public SpaceObjectContainer(JSONArray ja, UpdateViewpoint _uv, Frame _frame, boolean _exclusive, long _startTime, long _endTime) {
uv = _uv;
exclusive = _exclusive;
frame = _frame;
startTime = _startTime;
endTime = _endTime;
JTable grid = new JTable(model);
grid.setTableHeader(null);
grid.setShowGrid(false);
grid.setRowSelectionAllowed(true);
grid.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
grid.setColumnSelectionAllowed(false);
grid.setIntercellSpacing(new Dimension(0, 0));
if (exclusive)
grid.getColumnModel().getColumn(SELECTED_COL).setCellRenderer(new SelectedExclusiveRenderer());
else
grid.getColumnModel().getColumn(SELECTED_COL).setCellRenderer(new SelectedRenderer());
grid.getColumnModel().getColumn(SELECTED_COL).setPreferredWidth(ICON_WIDTH + 8);
grid.getColumnModel().getColumn(SELECTED_COL).setMaxWidth(ICON_WIDTH + 8);
grid.getColumnModel().getColumn(OBJECT_COL).setCellRenderer(new ObjectRenderer());
grid.getColumnModel().getColumn(STATUS_COL).setCellRenderer(new StatusRenderer());
grid.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
Point pt = e.getPoint();
int row = grid.rowAtPoint(pt);
if (row < 0)
return;
int col = grid.columnAtPoint(pt);
if (col == SELECTED_COL)
selectElement((SpaceObjectElement) grid.getValueAt(row, col));
}
});
setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.LIGHT_GRAY));
setViewportView(grid);
getViewport().setBackground(grid.getBackground());
setPreferredSize(new Dimension(-1, getGridRowHeight(grid) * NUMBEROFVISIBLEROWS + 1));
grid.setRowHeight(getGridRowHeight(grid));
uv.clear();
int len = ja.length();
for (int i = 0; i < len; i++)
selectObject(SpaceObject.get(ja.optString(i, "Earth")));
}
private void selectObject(SpaceObject object) {
SpaceObjectElement element = model.elementOf(object);
if (element != null) // found
selectElement(element);
}
public void setFrame(Frame _frame) {
if (frame == _frame)
return;
frame = _frame;
for (SpaceObjectElement element : model.getSelected())
element.load(uv, frame, startTime, endTime);
}
public void setTime(long _startTime, long _endTime) {
if (startTime == _startTime && endTime == _endTime)
return;
startTime = _startTime;
endTime = _endTime;
for (SpaceObjectElement element : model.getSelected())
element.load(uv, frame, startTime, endTime);
}
public boolean isDownloading() {
for (SpaceObjectElement element : model.getSelected()) {
if (element.isDownloading())
return true;
}
return false;
}
private void selectElement(SpaceObjectElement element) {
if (exclusive) {
for (SpaceObjectElement e : model.getSelected())
e.unload(uv);
element.load(uv, frame, startTime, endTime);
} else {
if (element.isSelected())
element.unload(uv);
else
element.load(uv, frame, startTime, endTime);
}
}
private int rowHeight = -1;
private int getGridRowHeight(JTable grid) {
if (rowHeight == -1) {
rowHeight = grid.getRowHeight() + 4;
}
return rowHeight;
}
public JSONArray toJson() {
JSONArray ja = new JSONArray();
for (SpaceObjectElement element : model.getSelected())
ja.put(element);
return ja;
}
private static class ObjectRenderer extends JHVTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (value instanceof SpaceObjectElement) {
SpaceObjectElement element = (SpaceObjectElement) value;
label.setText(element.toString());
label.setBorder(((SpaceObjectElement) value).getObject().getBorder());
}
return label;
}
}
private static class SelectedRenderer extends JHVTableCellRenderer {
private final JCheckBox checkBox = new JCheckBox();
SelectedRenderer() {
setHorizontalAlignment(CENTER);
checkBox.putClientProperty("JComponent.sizeVariant", "small");
checkBox.setBorderPainted(true);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value instanceof SpaceObjectElement) {
SpaceObjectElement element = (SpaceObjectElement) value;
checkBox.setSelected(element.isSelected());
checkBox.setBorder(element.getObject().getBorder());
}
checkBox.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
return checkBox;
}
}
private static class SelectedExclusiveRenderer extends JHVTableCellRenderer {
private final JRadioButton radio = new JRadioButton();
SelectedExclusiveRenderer() {
setHorizontalAlignment(CENTER);
radio.putClientProperty("JComponent.sizeVariant", "small");
radio.setBorderPainted(true);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value instanceof SpaceObjectElement) {
SpaceObjectElement element = (SpaceObjectElement) value;
radio.setSelected(element.isSelected());
radio.setBorder(element.getObject().getBorder());
}
radio.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
return radio;
}
}
private static class StatusRenderer extends JHVTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (value instanceof SpaceObjectElement) {
SpaceObjectElement element = (SpaceObjectElement) value;
String status = element.getStatus();
label.setText(status);
label.setToolTipText(status);
label.setBorder(element.getObject().getBorder());
}
return label;
}
}
}
|
package org.pentaho.di.trans.steps.scriptvalues_mod;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Hashtable;
import java.util.Map;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.EvaluatorException;
import org.mozilla.javascript.Script;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.UniqueTag;
import org.pentaho.di.compatibility.Row;
import org.pentaho.di.compatibility.Value;
import org.pentaho.di.compatibility.ValueUsedListener;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
/**
* Executes a JavaScript on the values in the input stream.
* Selected calculated values can then be put on the output stream.
*
* @author Matt
* @since 5-April-2003
*/
public class ScriptValuesMod extends BaseStep implements StepInterface, ScriptValuesModInterface {
private ScriptValuesMetaMod meta;
private ScriptValuesModData data;
public final static int SKIP_TRANSFORMATION = 1;
public final static int ABORT_TRANSFORMATION = -1;
public final static int ERROR_TRANSFORMATION = -2;
public final static int CONTINUE_TRANSFORMATION = 0;
private static boolean bWithTransStat = false;
private static boolean bRC = false;
private static int iTranStat = CONTINUE_TRANSFORMATION;
private boolean bFirstRun = false;
private ScriptValuesScript[] jsScripts;
private String strTransformScript = "";
private String strStartScript = "";
private String strEndScript = "";
// public static Row insertRow;
public static Script script;
public ScriptValuesMod(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta,
Trans trans) {
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
}
private void determineUsedFields(RowMetaInterface row) {
int nr = 0;
// Count the occurrences of the values.
// Perhaps we find values in comments, but we take no risk!
for (int i = 0; i < row.size(); i++) {
String valname = row.getValueMeta(i).getName().toUpperCase();
if (strTransformScript.toUpperCase().indexOf(valname) >= 0) {
nr++;
}
}
// Allocate fields_used
data.fields_used = new int[nr];
data.values_used = new Value[nr];
nr = 0;
// Count the occurrences of the values.
// Perhaps we find values in comments, but we take no risk!
for (int i = 0; i < row.size(); i++) {
// Values are case-insensitive in JavaScript.
String valname = row.getValueMeta(i).getName();
if (strTransformScript.indexOf(valname) >= 0) {
if (log.isDetailed())
logDetailed(Messages.getString("ScriptValuesMod.Log.UsedValueName", String.valueOf(i), valname)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
data.fields_used[nr] = i;
nr++;
}
}
if (log.isDetailed())
logDetailed(Messages.getString("ScriptValuesMod.Log.UsingValuesFromInputStream", String.valueOf(data.fields_used.length))); //$NON-NLS-1$ //$NON-NLS-2$
}
private boolean addValues(RowMetaInterface rowMeta, Object[] row) throws KettleValueException {
if (first) {
first = false;
// What is the output row looking like?
data.outputRowMeta = getInputRowMeta().clone();
meta.getFields(data.outputRowMeta, getStepname(), null, null, this);
// Determine the indexes of the fields used!
determineUsedFields(rowMeta);
data.cx = Context.enter();
data.cx.setOptimizationLevel(9);
data.scope = data.cx.initStandardObjects(null, false);
bFirstRun = true;
Scriptable jsvalue = Context.toObject(this, data.scope);
data.scope.put("_step_", data.scope, jsvalue); //$NON-NLS-1$
// Adding the existing Scripts to the Context
for (int i = 0; i < meta.getNumberOfJSScripts(); i++) {
Scriptable jsR = Context.toObject(jsScripts[i].getScript(), data.scope);
data.scope.put(jsScripts[i].getScriptName(), data.scope, jsR);
}
// Adding the Name of the Transformation to the Context
data.scope.put("_TransformationName_", data.scope, this.getName());
try {
// add these now (they will be re-added later) to make compilation succeed
// Add the old style row object for compatibility reasons...
if (meta.isCompatible()) {
Row v2Row = RowMeta.createOriginalRow(rowMeta, row);
Scriptable jsV2Row = Context.toObject(v2Row, data.scope);
data.scope.put("row", data.scope, jsV2Row); //$NON-NLS-1$
} else {
Scriptable jsrow = Context.toObject(row, data.scope);
data.scope.put("row", data.scope, jsrow); //$NON-NLS-1$
}
// Add the used fields...
for (int i = 0; i < data.fields_used.length; i++) {
ValueMetaInterface valueMeta = rowMeta.getValueMeta(data.fields_used[i]);
Object valueData = row[data.fields_used[i]];
if (meta.isCompatible()) {
data.values_used[i] = valueMeta.createOriginalValue(valueData);
Scriptable jsarg = Context.toObject(data.values_used[i], data.scope);
data.scope.put(valueMeta.getName(), data.scope, jsarg);
} else {
Scriptable jsarg;
if (valueData != null) {
jsarg = Context.toObject(valueMeta.convertToNormalStorageType(valueData), data.scope);
} else {
jsarg = null;
}
data.scope.put(valueMeta.getName(), data.scope, jsarg);
}
}
// also add the meta information for the hole row
Scriptable jsrowMeta = Context.toObject(rowMeta, data.scope);
data.scope.put("rowMeta", data.scope, jsrowMeta); //$NON-NLS-1$
// Modification for Additional Script parsing
try {
if (meta.getAddClasses() != null) {
for (int i = 0; i < meta.getAddClasses().length; i++) {
Object jsOut = Context.javaToJS(meta.getAddClasses()[i].getAddObject(), data.scope);
ScriptableObject.putProperty(data.scope, meta.getAddClasses()[i].getJSName(), jsOut);
}
}
} catch (Exception e) {
throw new KettleValueException(Messages.getString("ScriptValuesMod.Log.CouldNotAttachAdditionalScripts"), e); //$NON-NLS-1$
}
// Adding some default JavaScriptFunctions to the System
try {
Context.javaToJS(ScriptValuesAddedFunctions.class, data.scope);
((ScriptableObject) data.scope).defineFunctionProperties(ScriptValuesAddedFunctions.jsFunctionList,
ScriptValuesAddedFunctions.class, ScriptableObject.DONTENUM);
} catch (Exception ex) {
// System.out.println(ex.toString());
throw new KettleValueException(Messages.getString("ScriptValuesMod.Log.CouldNotAddDefaultFunctions"), ex); //$NON-NLS-1$
}
;
// Adding some Constants to the JavaScript
try {
data.scope.put("SKIP_TRANSFORMATION", data.scope, Integer.valueOf(SKIP_TRANSFORMATION));
data.scope.put("ABORT_TRANSFORMATION", data.scope, Integer.valueOf(ABORT_TRANSFORMATION));
data.scope.put("ERROR_TRANSFORMATION", data.scope, Integer.valueOf(ERROR_TRANSFORMATION));
data.scope.put("CONTINUE_TRANSFORMATION", data.scope, Integer.valueOf(CONTINUE_TRANSFORMATION));
} catch (Exception ex) {
// System.out.println("Exception Adding the Constants " + ex.toString());
throw new KettleValueException(Messages.getString("ScriptValuesMod.Log.CouldNotAddDefaultConstants"), ex);
}
;
try {
// Checking for StartScript
if (strStartScript != null && strStartScript.length() > 0) {
Script startScript = data.cx.compileString(strStartScript, "trans_Start", 1, null);
startScript.exec(data.cx, data.scope);
if (log.isDetailed())
logDetailed(("Start Script found!"));
} else {
if (log.isDetailed())
logDetailed(("No starting Script found!"));
}
} catch (Exception es) {
// System.out.println("Exception processing StartScript " + es.toString());
throw new KettleValueException(Messages.getString("ScriptValuesMod.Log.ErrorProcessingStartScript"), es);
}
// Now Compile our Script
data.script = data.cx.compileString(strTransformScript, "script", 1, null);
} catch (Exception e) {
throw new KettleValueException(Messages.getString("ScriptValuesMod.Log.CouldNotCompileJavascript"), e);
}
}
// Filling the defined TranVars with the Values from the Row
Object[] outputRow = RowDataUtil.resizeArray(row, rowMeta.size() + meta.getName().length);
// Keep an index...
int outputIndex = rowMeta.size();
// Keep track of the changed values...
final Map<Integer, Value> usedRowValues;
if (meta.isCompatible()) {
usedRowValues = new Hashtable<Integer, Value>();
} else {
usedRowValues = null;
}
try {
try {
if (meta.isCompatible()) {
Row v2Row = RowMeta.createOriginalRow(rowMeta, row);
Scriptable jsV2Row = Context.toObject(v2Row, data.scope);
data.scope.put("row", data.scope, jsV2Row); //$NON-NLS-1$
v2Row.getUsedValueListeners().add(new ValueUsedListener() {
public void valueIsUsed(int index, Value value) {
usedRowValues.put(index, value);
}
});
} else {
Scriptable jsrow = Context.toObject(row, data.scope);
data.scope.put("row", data.scope, jsrow); //$NON-NLS-1$
}
for (int i = 0; i < data.fields_used.length; i++) {
ValueMetaInterface valueMeta = rowMeta.getValueMeta(data.fields_used[i]);
Object valueData = row[data.fields_used[i]];
if (meta.isCompatible()) {
data.values_used[i] = valueMeta.createOriginalValue(valueData);
Scriptable jsarg = Context.toObject(data.values_used[i], data.scope);
data.scope.put(valueMeta.getName(), data.scope, jsarg);
} else {
Scriptable jsarg;
if (valueData != null) {
jsarg = Context.toObject(valueMeta.convertToNormalStorageType(valueData), data.scope);
} else {
jsarg = null;
}
data.scope.put(valueMeta.getName(), data.scope, jsarg);
}
}
// also add the meta information for the hole row
Scriptable jsrowMeta = Context.toObject(rowMeta, data.scope);
data.scope.put("rowMeta", data.scope, jsrowMeta); //$NON-NLS-1$
} catch (Exception e) {
throw new KettleValueException(Messages.getString("ScriptValuesMod.Log.UnexpectedeError"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
// Executing our Script
data.script.exec(data.cx, data.scope);
if (bFirstRun) {
bFirstRun = false;
// Check if we had a Transformation Status
Object tran_stat = data.scope.get("trans_Status", data.scope);
if (tran_stat != ScriptableObject.NOT_FOUND) {
bWithTransStat = true;
if (log.isDetailed())
logDetailed(("tran_Status found. Checking transformation status while script execution.")); //$NON-NLS-1$ //$NON-NLS-2$
} else {
if (log.isDetailed())
logDetailed(("No tran_Status found. Transformation status checking not available.")); //$NON-NLS-1$ //$NON-NLS-2$
bWithTransStat = false;
}
}
if (bWithTransStat) {
iTranStat = (int) Context.toNumber(data.scope.get("trans_Status", data.scope));
} else {
iTranStat = CONTINUE_TRANSFORMATION;
}
if (iTranStat == CONTINUE_TRANSFORMATION) {
bRC = true;
for (int i = 0; i < meta.getName().length; i++) {
Object result = data.scope.get(meta.getName()[i], data.scope);
outputRow[outputIndex] = getValueFromJScript(result, i);
outputIndex++;
}
// Also modify the "in-place" value changes:
// --> the field.trim() type of changes...
// As such we overwrite all the used fields again.
if (meta.isCompatible()) {
for (int i = 0; i < data.values_used.length; i++) {
ValueMetaInterface valueMeta = rowMeta.getValueMeta(data.fields_used[i]);
outputRow[data.fields_used[i]] = valueMeta.getValueData(data.values_used[i]);
}
// Grab the variables in the "row" object too.
for (Integer index : usedRowValues.keySet()) {
Value value = usedRowValues.get(index);
ValueMetaInterface valueMeta = rowMeta.getValueMeta(index);
outputRow[index] = valueMeta.getValueData(value);
}
}
putRow(data.outputRowMeta, outputRow);
} else {
switch (iTranStat) {
case SKIP_TRANSFORMATION:
// eat this row.
bRC = true;
break;
case ABORT_TRANSFORMATION:
if (data.cx != null)
Context.exit();
stopAll();
setOutputDone();
bRC = false;
break;
case ERROR_TRANSFORMATION:
if (data.cx != null)
Context.exit();
setErrors(1);
stopAll();
bRC = false;
break;
}
// TODO: kick this "ERROR handling" junk out now that we have solid error handling in place.
}
} catch (Exception e) {
throw new KettleValueException(Messages.getString("ScriptValuesMod.Log.JavascriptError"), e); //$NON-NLS-1$
}
return bRC;
}
public Object getValueFromJScript(Object result, int i) throws KettleValueException {
if (meta.getName()[i] != null && meta.getName()[i].length() > 0) {
// res.setName(meta.getRename()[i]);
// res.setType(meta.getType()[i]);
try {
if (result != null) {
String classType = result.getClass().getName();
switch (meta.getType()[i]) {
case ValueMetaInterface.TYPE_NUMBER:
if (classType.equalsIgnoreCase("org.mozilla.javascript.Undefined")) {
return null;
} else if (classType.equalsIgnoreCase("org.mozilla.javascript.NativeJavaObject")) {
try {
// Is it a java Value class ?
Value v = (Value) Context.jsToJava(result, Value.class);
return v.getNumber();
} catch (Exception e) {
String string = Context.toString(result);
return new Double(Double.parseDouble(Const.trim(string)));
}
} else if (classType.equalsIgnoreCase("org.mozilla.javascript.NativeNumber")) {
Number nb = Context.toNumber(result);
return new Double(nb.doubleValue());
} else {
Number nb = (Number) result;
return new Double(nb.doubleValue());
}
case ValueMetaInterface.TYPE_INTEGER:
if (classType.equalsIgnoreCase("java.lang.Byte")) {
return new Long(((java.lang.Byte) result).longValue());
} else if (classType.equalsIgnoreCase("java.lang.Short")) {
return new Long(((Short) result).longValue());
} else if (classType.equalsIgnoreCase("java.lang.Integer")) {
return new Long(((Integer) result).longValue());
} else if (classType.equalsIgnoreCase("java.lang.Long")) {
return new Long(((Long) result).longValue());
} else if (classType.equalsIgnoreCase("java.lang.Double")) {
return new Long(((Double) result).longValue());
} else if (classType.equalsIgnoreCase("java.lang.String")) {
return new Long((new Long((String) result)).longValue());
} else if (classType.equalsIgnoreCase("org.mozilla.javascript.Undefined")) {
return null;
} else if (classType.equalsIgnoreCase("org.mozilla.javascript.NativeNumber")) {
Number nb = Context.toNumber(result);
return new Long(nb.longValue());
} else if (classType.equalsIgnoreCase("org.mozilla.javascript.NativeJavaObject")) {
// Is it a Value?
try {
Value value = (Value) Context.jsToJava(result, Value.class);
return value.getInteger();
} catch (Exception e2) {
String string = Context.toString(result);
return new Long(Long.parseLong(Const.trim(string)));
}
} else if (classType.equalsIgnoreCase("org.mozilla.javascript.UniqueTag")) {
return Long.valueOf(Long.parseLong(((UniqueTag) result).toString()));
} else {
return Long.valueOf(Long.parseLong(result.toString()));
}
case ValueMetaInterface.TYPE_STRING:
if (classType.equalsIgnoreCase("org.mozilla.javascript.NativeJavaObject") || //$NON-NLS-1$
classType.equalsIgnoreCase("org.mozilla.javascript.Undefined")) {
// Is it a java Value class ?
try {
Value v = (Value) Context.jsToJava(result, Value.class);
return v.toString();
} catch (Exception ev) {
// convert to a string should work in most cases...
String string = (String) Context.toString(result);
return string;
}
} else {
// A String perhaps?
String string = (String) Context.toString(result);
return string;
}
case ValueMetaInterface.TYPE_DATE:
double dbl = 0;
if (classType.equalsIgnoreCase("org.mozilla.javascript.Undefined")) {
return null;
} else {
if (classType.equalsIgnoreCase("org.mozilla.javascript.NativeDate")) {
dbl = Context.toNumber(result);
} else if (classType.equalsIgnoreCase("org.mozilla.javascript.NativeJavaObject")
|| classType.equalsIgnoreCase("java.util.Date")) {
// Is it a java Date() class ?
try {
Date dat = (Date) Context.jsToJava(result, java.util.Date.class);
dbl = dat.getTime();
} catch (Exception e) {
// Is it a Value?
try {
Value value = (Value) Context.jsToJava(result, Value.class);
return value.getDate();
} catch (Exception e2) {
try {
String string = (String) Context.toString(result);
return XMLHandler.stringToDate(string);
} catch (Exception e3) {
throw new KettleValueException("Can't convert a string to a date");
}
}
}
} else if (classType.equalsIgnoreCase("java.lang.Double")) {
dbl = ((Double) result).doubleValue();
} else {
String string = (String) Context.jsToJava(result, String.class);
dbl = Double.parseDouble(string);
}
long lng = Math.round(dbl);
Date dat = new Date(lng);
return dat;
}
case ValueMetaInterface.TYPE_BOOLEAN:
return (Boolean) result;
case ValueMetaInterface.TYPE_BIGNUMBER:
if (classType.equalsIgnoreCase("org.mozilla.javascript.Undefined")) {
return null;
} else if (classType.equalsIgnoreCase("org.mozilla.javascript.NativeNumber")) {
Number nb = Context.toNumber(result);
return new BigDecimal(nb.longValue());
} else if (classType.equalsIgnoreCase("org.mozilla.javascript.NativeJavaObject")) {
// Is it a BigDecimal class ?
try {
BigDecimal bd = (BigDecimal) Context.jsToJava(result, BigDecimal.class);
return bd;
} catch (Exception e) {
try {
Value v = (Value) Context.jsToJava(result, Value.class);
if (!v.isNull())
return v.getBigNumber();
else
return null;
} catch (Exception e2) {
String string = (String) Context.jsToJava(result, String.class);
return new BigDecimal(string);
}
}
} else if (classType.equalsIgnoreCase("java.lang.Byte")) {
return new BigDecimal(((java.lang.Byte) result).longValue());
} else if (classType.equalsIgnoreCase("java.lang.Short")) {
return new BigDecimal(((Short) result).longValue());
} else if (classType.equalsIgnoreCase("java.lang.Integer")) {
return new BigDecimal(((Integer) result).longValue());
} else if (classType.equalsIgnoreCase("java.lang.Long")) {
return new BigDecimal(((Long) result).longValue());
} else if (classType.equalsIgnoreCase("java.lang.Double")) {
return new BigDecimal(((Double) result).longValue());
} else if (classType.equalsIgnoreCase("java.lang.String")) {
return new BigDecimal((new Long((String) result)).longValue());
} else {
throw new RuntimeException("JavaScript conversion to BigNumber not implemented for " + classType);
}
case ValueMetaInterface.TYPE_BINARY: {
return Context.jsToJava(result, byte[].class);
}
case ValueMetaInterface.TYPE_NONE: {
throw new RuntimeException("No data output data type was specified for new field [" + meta.getName()[i]
+ "]");
}
default: {
throw new RuntimeException("JavaScript conversion not implemented for type " + meta.getType()[i] + " ("
+ ValueMeta.getTypeDesc(meta.getType()[i]) + ")");
}
}
} else {
return null;
}
} catch (Exception e) {
throw new KettleValueException(Messages.getString("ScriptValuesMod.Log.JavascriptError"), e); //$NON-NLS-1$
}
} else {
throw new KettleValueException("No name was specified for result value #" + (i + 1));
}
}
public RowMetaInterface getOutputRowMeta() {
return data.outputRowMeta;
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
meta = (ScriptValuesMetaMod) smi;
data = (ScriptValuesModData) sdi;
Object[] r = getRow(); // Get row from input rowset & set row busy!
if (r == null) {
//Modification for Additional End Function
try {
if (data.cx != null) {
// Checking for EndScript
if (strEndScript != null && strEndScript.length() > 0) {
Script endScript = data.cx.compileString(strEndScript, "trans_End", 1, null);
endScript.exec(data.cx, data.scope);
if (log.isDetailed())
logDetailed(("End Script found!"));
} else {
if (log.isDetailed())
logDetailed(("No end Script found!"));
}
}
} catch (Exception e) {
logError(Messages.getString("ScriptValuesMod.Log.UnexpectedeError") + " : " + e.toString()); //$NON-NLS-1$ //$NON-NLS-2$
logError(Messages.getString("ScriptValuesMod.Log.ErrorStackTrace") + Const.CR + Const.getStackTracker(e)); //$NON-NLS-1$
setErrors(1);
stopAll();
}
if (data.cx != null)
Context.exit();
setOutputDone();
return false;
}
// Getting the Row, with the Transformation Status
try {
addValues(getInputRowMeta(), r);
} catch (KettleValueException e) {
String location = null;
if (e.getCause() instanceof EvaluatorException) {
EvaluatorException ee = (EvaluatorException) e.getCause();
location = "--> " + ee.lineNumber() + ":" + ee.columnNumber(); // $NON-NLS-1$ $NON-NLS-2$
}
if (getStepMeta().isDoingErrorHandling()) {
putError(getInputRowMeta(), r, 1, e.getMessage() + Const.CR + location, null, "SCR-001");
} else {
throw (e);
}
}
if (checkFeedback(getLinesRead()))
logBasic(Messages.getString("ScriptValuesMod.Log.LineNumber") + getLinesRead()); //$NON-NLS-1$
return bRC;
}
public boolean init(StepMetaInterface smi, StepDataInterface sdi) {
meta = (ScriptValuesMetaMod) smi;
data = (ScriptValuesModData) sdi;
if (super.init(smi, sdi)) {
// Add init code here.
// Get the actual Scripts from our MetaData
jsScripts = meta.getJSScripts();
for (int j = 0; j < jsScripts.length; j++) {
switch (jsScripts[j].getScriptType()) {
case ScriptValuesScript.TRANSFORM_SCRIPT:
strTransformScript = jsScripts[j].getScript();
break;
case ScriptValuesScript.START_SCRIPT:
strStartScript = jsScripts[j].getScript();
break;
case ScriptValuesScript.END_SCRIPT:
strEndScript = jsScripts[j].getScript();
break;
}
}
return true;
}
return false;
}
public void dispose(StepMetaInterface smi, StepDataInterface sdi) {
try {
if (data.cx != null)
Context.exit();
} catch (Exception er) {
// Eat this error, it's typically : "Calling Context.exit without previous Context.enter"
// logError(Messages.getString("System.Log.UnexpectedError"), er);
}
;
super.dispose(smi, sdi);
}
// Run is were the action happens!
public void run() {
BaseStep.runStepThread(this, meta, data);
}
}
|
package org.usfirst.frc330.Beachbot2014Java.commands;
import edu.wpi.first.wpilibj.command.Command;
import org.usfirst.frc330.Beachbot2014Java.Robot;
/**
*
* @author Joe-XPS13-W7
*/
public abstract class MoveArmCommand extends Command {
double setpoint;
boolean started = false;
double outputRange = 0;
double startPosition = 0;
double accelDistance = 0;
double decelDistance = 0;
double maxSpeed = 0;
double minSpeed = 0;
public MoveArmCommand(double position) {
this(position, 1.0, 0.1, 0.1, 0.1);
}
//minSpeed | \
// accel decel
// Distance Distance
public MoveArmCommand(double position, double maxSpeed, double minSpeed, double accelDistance, double decelDistance) {
requires(Robot.arm);
requires(Robot.wings);
setpoint = position;
this.maxSpeed = maxSpeed;
this.minSpeed = minSpeed;
this.maxSpeed = maxSpeed;
this.accelDistance = accelDistance;
this.decelDistance = decelDistance;
}
// Called just before this Command runs the first time
protected void initialize() {
if (!Robot.arm.areWingsSafeToClose(setpoint))
Robot.wings.setWingsOpen();
started = false;
startPosition = Robot.arm.getArmPosition();
if (setpoint - startPosition < accelDistance+decelDistance)
decelDistance = setpoint - accelDistance - startPosition;
}
// Called repeatedly when this Command is scheduled to run
final protected void execute() {
double armPosition = Robot.arm.getArmPosition();
double x, y;
if ((Robot.wings.areWingsOpen() || Robot.arm.areWingsSafeToClose(setpoint)) && !started) {
Robot.arm.setArmSetPoint(setpoint);
Robot.arm.setPIDOutputRange(minSpeed);
outputRange = minSpeed;
Robot.arm.enable();
started = true;
System.out.println("outputRange: " + outputRange);
} else if (started) {
if (Robot.arm.getArmPosition() > setpoint) {
outputRange = minSpeed;
} else if (Robot.arm.getArmPosition() <= startPosition + accelDistance) {
x = (armPosition - startPosition)/accelDistance;
y = maxSpeed - minSpeed;
outputRange = y*x+minSpeed;
} else if (Robot.arm.getArmPosition() >= setpoint - decelDistance) {
x = (setpoint - armPosition)/decelDistance;
outputRange = x*maxSpeed;
} else {
outputRange = maxSpeed;
}
Robot.arm.setPIDOutputRange(outputRange);
System.out.println("outputRange: " + outputRange);
}
}
// Make this return true when this Command no longer needs to run execute()
final protected boolean isFinished() {
return Robot.arm.onTarget() && started;
}
// Called once after isFinished returns true
final protected void end() {
Robot.arm.setPIDOutputRangeDefault();
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
final protected void interrupted() {
end();
}
}
|
package org.eclipse.dawnsci.analysis.api.tree;
public class TreeUtils {
/**
* Get the path
* @param tree
* @param node
* @return path to node, return null if not found
*/
public static String getPath(Tree tree, Node node) {
GroupNode g = tree.getGroupNode();
if (g == node) {
return tree.getNodeLink().getFullName();
}
return getPathDepthFirst(tree.getGroupNode(), node);
}
private static String getPathDepthFirst(final GroupNode group, final Node node) {
for (NodeLink l : group) {
if (l.getDestination() == node) {
return l.getFullName();
} else if (l.isDestinationGroup()) {
String p = getPathDepthFirst((GroupNode) l.getDestination(), node);
if (p != null)
return p;
}
}
return null;
}
}
|
package org.eclipse.mylyn.context.tests.support;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.util.Properties;
import junit.framework.AssertionFailedError;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.mylyn.context.core.ContextCore;
import org.eclipse.mylyn.context.tests.ContextTestsPlugin;
import org.eclipse.mylyn.internal.monitor.ui.MonitorUiPlugin;
/**
* @author Steffen Pingel
*/
public class TestUtil {
private static boolean contextUiLazyStarted;
public static final String KEY_CREDENTIALS_FILE = "mylyn.credentials";
public enum PrivilegeLevel {
ANONYMOUS, GUEST, USER, ADMIN
};
public static class Credentials {
public final String username;
public final String password;
public Credentials(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public String toString() {
return getClass().getName() + " [username=" + username + ",password=" + password + "]";
}
}
public static Credentials readCredentials() {
return readCredentials(PrivilegeLevel.USER, null);
}
public static Credentials readCredentials(PrivilegeLevel level) {
return readCredentials(level, null);
}
public static Credentials readCredentials(PrivilegeLevel level, String realm) {
Properties properties = new Properties();
try {
String filename = System.getProperty(KEY_CREDENTIALS_FILE);
if (filename == null) {
if (ContextTestsPlugin.getDefault() != null) {
URL localURL = FileLocator.toFileURL(ContextTestsPlugin.getDefault().getBundle().getEntry(
"credentials.properties"));
filename = localURL.getFile();
} else {
URL localURL = TestUtil.class.getResource("");
filename = localURL.getFile() + "../../../../../../../credentials.properties";
}
}
properties.load(new FileInputStream(new File(filename)));
} catch (Exception e) {
throw new AssertionFailedError("must define credentials in <plug-in dir>/credentials.properties");
}
String defaultPassword = properties.getProperty("pass");
realm = (realm != null) ? realm + "." : "";
switch (level) {
case ANONYMOUS:
return createCredentials(properties, realm + "anon.", "", "");
case GUEST:
return createCredentials(properties, realm + "guest.", "guest@mylyn.eclipse.org", defaultPassword);
case USER:
return createCredentials(properties, realm, "tests@mylyn.eclipse.org", defaultPassword);
case ADMIN:
return createCredentials(properties, realm + "admin.", "admin@mylyn.eclipse.org", null);
}
throw new AssertionFailedError("invalid privilege level");
}
private static Credentials createCredentials(Properties properties, String prefix, String defaultUsername,
String defaultPassword) {
String username = properties.getProperty(prefix + "user");
String password = properties.getProperty(prefix + "pass");
if (username == null) {
username = defaultUsername;
}
if (password == null) {
password = defaultPassword;
}
if (username == null || password == null) {
throw new AssertionFailedError(
"username or password not found in <plug-in dir>/credentials.properties, make sure file is valid");
}
return new Credentials(username, password);
}
/**
* Test cases that rely on lazy startup of Context Ui (e.g. context bridges) need to invoke this method prior to
* running the test.
*/
public static void triggerContextUiLazyStart() {
if (contextUiLazyStarted) {
return;
}
contextUiLazyStarted = true;
// make sure monitor UI is started and logs the start interaction event
MonitorUiPlugin.getDefault();
ContextCore.getContextManager().activateContext("startup");
ContextCore.getContextManager().deactivateContext("startup");
}
}
|
package org.jasig.portal;
import org.jasig.portal.security.IPerson;
import org.jasig.portal.utils.XSLT;
import javax.servlet.*;
import javax.servlet.jsp.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.text.*;
import java.net.*;
import org.w3c.dom.*;
import org.apache.xalan.xpath.*;
import org.apache.xalan.xslt.*;
import org.apache.xml.serialize.*;
/**
* A multithreaded version of a UserInstance.
* @author Peter Kharchenko <a href="mailto:">pkharchenko@interactivebusiness.com</a>
* @version $Revision$
*/
public class GuestUserInstance extends UserInstance implements HttpSessionBindingListener {
// state class
private class IState {
private ChannelManager channelManager;
private StandaloneChannelRenderer p_browserMapper;
private Object p_rendering_lock;
public IState() {
channelManager=null;
p_rendering_lock=null;
p_browserMapper=null;
}
}
Map stateTable;
// manages layout and preferences
GuestUserLayoutManager uLayoutManager;
public GuestUserInstance(IPerson person) {
super(person);
// instantiate state table
stateTable=Collections.synchronizedMap(new HashMap());
uLayoutManager=new GuestUserLayoutManager(person);
}
/**
* Register arrival of a new session.
* Create and populate new state entry.
* @param req a <code>HttpServletRequest</code> value
*/
public void registerSession(HttpServletRequest req) {
IState newState=new IState();
newState.channelManager=new ChannelManager(new GuestUserLayoutManagerWrapper(uLayoutManager,req.getSession(false).getId()));
newState.p_rendering_lock=new Object();
uLayoutManager.registerSession(req);
stateTable.put(req.getSession(false).getId(),newState);
}
/**
* Unbinds a registered session.
* @param sessionId a <code>String</code> value
*/
public void unbindSession(String sessionId) {
IState state=(IState)stateTable.get(sessionId);
if(state==null) {
Logger.log(Logger.ERROR,"GuestUserInstance::unbindSession() : trying to envoke a method on a non-registered sessionId=\""+sessionId+"\".");
return;
}
state.channelManager.finishedSession();
uLayoutManager.unbindSession(sessionId);
stateTable.remove(sessionId);
}
/**
* This notifies UserInstance that it has been unbound from the session.
* Method triggers cleanup in ChannelManager.
*
* @param bindingEvent an <code>HttpSessionBindingEvent</code> value
*/
public void valueUnbound (HttpSessionBindingEvent bindingEvent) {
this.unbindSession(bindingEvent.getSession().getId());
Logger.log(Logger.DEBUG,"GuestUserInstance::valueUnbound() : unbinding session \""+bindingEvent.getSession().getId()+"\"");
}
/**
* Notifies UserInstance that it has been bound to a session.
*
* @param bindingEvent a <code>HttpSessionBindingEvent</code> value
*/
public void valueBound (HttpSessionBindingEvent bindingEvent) {
Logger.log(Logger.DEBUG,"GuestUserInstance::valueBound() : instance bound to a new session \""+bindingEvent.getSession().getId()+"\"");
}
/**
* Prepares for and initates the rendering cycle.
* @param the servlet request object
* @param the servlet response object
* @param the JspWriter object
*/
public void writeContent (HttpServletRequest req, HttpServletResponse res, java.io.PrintWriter out) {
String sessionId=req.getSession(false).getId();
IState state=(IState)stateTable.get(sessionId);
if(state==null) {
Logger.log(Logger.ERROR,"GuestUserInstance::writeContent() : trying to envoke a method on a non-registered sessionId=\""+sessionId+"\".");
return;
}
try {
// instantiate user layout manager and check to see if the profile mapping has been established
if (state.p_browserMapper != null) {
state.p_browserMapper.prepare(req);
}
if (uLayoutManager.isUserAgentUnmapped(sessionId)) {
uLayoutManager.unbindSession(sessionId);
uLayoutManager.registerSession(req);
} else {
// p_browserMapper is no longer needed
state.p_browserMapper = null;
}
if (uLayoutManager.isUserAgentUnmapped(sessionId)) {
// unmapped browser
if (state.p_browserMapper== null) {
state.p_browserMapper = new org.jasig.portal.channels.CSelectSystemProfile();
state.p_browserMapper.initialize(new Hashtable(), "CSelectSystemProfile", true, true, false, 10000, getPerson());
}
try {
state.p_browserMapper.render(req, res);
} catch (Exception e) {
// something went wrong trying to show CSelectSystemProfileChannel
Logger.log(Logger.ERROR,"GuestUserInstance::writeContent() : unable caught an exception while trying to display CSelectSystemProfileChannel! Exception:"+e);
}
// don't go any further!
return;
}
// call layout manager to process all user-preferences-related request parameters
// this will update UserPreference object contained by UserLayoutManager, so that
// appropriate attribute incorporation filters and parameter tables can be constructed.
uLayoutManager.processUserPreferencesParameters(req);
renderState (req, res, out, state.channelManager, uLayoutManager.getUserLayout(sessionId), uLayoutManager.getUserPreferences(sessionId), uLayoutManager.getStructureStylesheetDescription(sessionId),uLayoutManager.getThemeStylesheetDescription(sessionId),state.p_rendering_lock);
} catch (Exception e) {
StringWriter sw=new StringWriter();
e.printStackTrace(new PrintWriter(sw));
sw.flush();
Logger.log(Logger.ERROR,"UserInstance::writeContent() : an unknown exception occurred : "+sw.toString());
}
}
}
|
package org.jasig.portal;
import org.jasig.portal.services.LogService;
import org.jasig.portal.security.IPerson;
import org.jasig.portal.jndi.JNDIManager;
import org.jasig.portal.jndi.PortalNamingException;
import org.jasig.portal.utils.BooleanLock;
import org.jasig.portal.utils.XML;
import org.jasig.portal.utils.PropsMatcher;
import org.w3c.dom.Node;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javax.servlet.http.HttpServletRequest;
import java.net.URL;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* UserLayoutManager is responsible for keeping: user id, user layout, user preferences
* and stylesheet descriptions.
* For method descriptions please see {@link IUserLayoutManager}.
* @author Peter Kharchenko <a href="mailto:">pkharchenko@interactivebusiness.com</a>
* @version $Revision$
*/
public class UserLayoutManager implements IUserLayoutManager {
// user agent mapper for guessing the profile
static PropsMatcher uaMatcher;
private Document uLayoutXML;
private UserPreferences complete_up;
// caching of stylesheet descriptions is recommended
// if they'll take up too much space, we can take them
// out, but cache stylesheet URIs, mime type and serializer name.
// Those are used in every rendering cycle.
private ThemeStylesheetDescription tsd;
private StructureStylesheetDescription ssd;
private boolean unmapped_user_agent = false;
IPerson m_person;
IUserLayoutStore ulsdb = null;
BooleanLock layout_write_lock=new BooleanLock(true);
/**
* Constructor does the following
* 1. Read layout.properties
* 2. read userLayout from the database
* @param the servlet request object
* @param person object
*/
public UserLayoutManager (HttpServletRequest req, IPerson person) throws PortalException {
uLayoutXML = null;
try {
m_person = person;
// load user preferences
// Should obtain implementation in a different way!!
ulsdb = UserLayoutStoreFactory.getUserLayoutStoreImpl();
// determine user profile
String userAgent = req.getHeader("User-Agent");
UserProfile upl = ulsdb.getUserProfile(m_person, userAgent);
if (upl == null) {
upl = ulsdb.getSystemProfile(userAgent);
}
if(upl==null) {
// try guessing the profile through pattern matching
if(uaMatcher==null) {
// init user agent matcher
URL url = null;
try {
url = this.getClass().getResource("/properties/browser.mappings");
if (url != null) {
uaMatcher = new PropsMatcher(url.openStream());
}
} catch (IOException ioe) {
LogService.instance().log(LogService.ERROR, "UserLayoutManager::UserLayoutManager() : Exception occurred while loading browser mapping file: " + url + ". " + ioe);
}
}
if(uaMatcher!=null) {
// try matching
String profileId=uaMatcher.match(userAgent);
if(profileId!=null) {
// user agent has been matched
upl=ulsdb.getSystemProfileById(Integer.parseInt(profileId));
}
}
}
if (upl != null) {
// read uLayoutXML
uLayoutXML = UserLayoutStoreFactory.getUserLayoutStoreImpl().getUserLayout(m_person, upl.getProfileId());
if (uLayoutXML == null) {
throw new PortalException("UserLayoutManager::UserLayoutManager() : unable to retreive userLayout for user=\"" + m_person.getID() + "\", profile=\"" + upl.getProfileName() + "\".");
}
try {
complete_up=ulsdb.getUserPreferences(m_person, upl);
} catch (Exception e) {
LogService.instance().log(LogService.ERROR, "UserLayoutManager(): caught an exception trying to retreive user preferences for user=\"" + m_person.getID() + "\", profile=\"" + upl.getProfileName() + "\".", e);
complete_up=new UserPreferences(upl);
}
try {
// Initialize the JNDI context for this user
JNDIManager.initializeSessionContext(req.getSession(),Integer.toString(m_person.getID()),Integer.toString(upl.getLayoutId()),uLayoutXML);
} catch(InternalPortalException ipe) {
LogService.instance().log(LogService.ERROR, "UserLayoutManager(): Could not properly initialize user context", ipe);
}
// set dirty flag on the layout
layout_write_lock.setValue(true);
} else {
// there is no user-defined mapping for this particular browser.
// user should be redirected to a browser-registration page.
unmapped_user_agent = true;
LogService.instance().log(LogService.DEBUG, "UserLayoutManager::UserLayoutManager() : unable to find a profile for user \"" + m_person.getID()+"\" and userAgent=\""+ userAgent + "\".");
}
} catch (PortalException pe) {
throw pe;
} catch (Exception e) {
LogService.instance().log(LogService.ERROR, e);
}
}
/**
* A simpler constructor, that only initialises the person object.
* Needed for ancestors.
* @param person an <code>IPerson</code> object.
*/
public UserLayoutManager(IPerson person) {
m_person=person;
}
/* This function processes request parameters related to
* setting Structure/Theme stylesheet parameters and attributes.
* (uP_sparam, uP_tparam, uP_sfattr, uP_scattr uP_tcattr)
* It also processes layout root requests (uP_root)
* @param req current <code>HttpServletRequest</code>
*/
public void processUserPreferencesParameters (HttpServletRequest req) {
// layout root setting
String root;
if ((root = req.getParameter("uP_root")) != null) {
// If a channel specifies "me" as its root, set the root
// to the channel's instance Id
if (root.equals("me")) {
// get uPFile spec and search for "channel" clause
root=null;
String servletPath = req.getServletPath();
String uPFile = servletPath.substring(servletPath.lastIndexOf('/')+1, servletPath.length());
StringTokenizer uPTokenizer=new StringTokenizer(uPFile,PortalSessionManager.PORTAL_URL_SEPARATOR);
while(uPTokenizer.hasMoreTokens()) {
String nextToken=uPTokenizer.nextToken();
if(nextToken.equals(PortalSessionManager.CHANNEL_URL_ELEMENT)) {
if(uPTokenizer.hasMoreTokens()) {
root=uPTokenizer.nextToken();
} else {
// abrupt end after channel element
LogService.instance().log(LogService.ERROR, "UserLayoutManager::processUserPreferencesParameters() : unable to extract channel ID. uPFile=\""+uPFile+"\".");
}
}
}
}
if(root!=null) {
complete_up.getStructureStylesheetUserPreferences().putParameterValue("userLayoutRoot", root);
} else {
LogService.instance().log(LogService.ERROR, "UserLayoutManager::processUserPreferencesParameters() : unable to extract channel ID. servletPath=\""+req.getServletPath()+"\".");
}
}
// other params
String[] sparams = req.getParameterValues("uP_sparam");
if (sparams != null) {
for (int i = 0; i < sparams.length; i++) {
String pValue = req.getParameter(sparams[i]);
complete_up.getStructureStylesheetUserPreferences().putParameterValue(sparams[i], pValue);
LogService.instance().log(LogService.DEBUG, "UserLayoutManager::processUserPreferencesParameters() : setting sparam \"" + sparams[i]
+ "\"=\"" + pValue + "\".");
}
}
String[] tparams = req.getParameterValues("uP_tparam");
if (tparams != null) {
for (int i = 0; i < tparams.length; i++) {
String pValue = req.getParameter(tparams[i]);
complete_up.getThemeStylesheetUserPreferences().putParameterValue(tparams[i], pValue);
LogService.instance().log(LogService.DEBUG, "UserLayoutManager::processUserPreferencesParameters() : setting tparam \"" + tparams[i]
+ "\"=\"" + pValue + "\".");
}
}
// attribute processing
// structure transformation
String[] sfattrs = req.getParameterValues("uP_sfattr");
if (sfattrs != null) {
for (int i = 0; i < sfattrs.length; i++) {
String aName = sfattrs[i];
String[] aNode = req.getParameterValues(aName + "_folderId");
if (aNode != null && aNode.length > 0) {
for (int j = 0; j < aNode.length; j++) {
String aValue = req.getParameter(aName + "_" + aNode[j] + "_value");
complete_up.getStructureStylesheetUserPreferences().setFolderAttributeValue(aNode[j], aName, aValue);
LogService.instance().log(LogService.DEBUG, "UserLayoutManager::processUserPreferencesParameters() : setting sfattr \"" + aName
+ "\" of \"" + aNode[j] + "\" to \"" + aValue + "\".");
}
}
}
}
String[] scattrs = req.getParameterValues("uP_scattr");
if (scattrs != null) {
for (int i = 0; i < scattrs.length; i++) {
String aName = scattrs[i];
String[] aNode = req.getParameterValues(aName + "_channelId");
if (aNode != null && aNode.length > 0) {
for (int j = 0; j < aNode.length; j++) {
String aValue = req.getParameter(aName + "_" + aNode[j] + "_value");
complete_up.getStructureStylesheetUserPreferences().setChannelAttributeValue(aNode[j], aName, aValue);
LogService.instance().log(LogService.DEBUG, "UserLayoutManager::processUserPreferencesParameters() : setting scattr \"" + aName
+ "\" of \"" + aNode[j] + "\" to \"" + aValue + "\".");
}
}
}
}
// theme stylesheet attributes
String[] tcattrs = req.getParameterValues("uP_tcattr");
if (tcattrs != null) {
for (int i = 0; i < tcattrs.length; i++) {
String aName = tcattrs[i];
String[] aNode = req.getParameterValues(aName + "_channelId");
if (aNode != null && aNode.length > 0) {
for (int j = 0; j < aNode.length; j++) {
String aValue = req.getParameter(aName + "_" + aNode[j] + "_value");
complete_up.getThemeStylesheetUserPreferences().setChannelAttributeValue(aNode[j], aName, aValue);
LogService.instance().log(LogService.DEBUG, "UserLayoutManager::processUserPreferencesParameters() : setting tcattr \"" + aName
+ "\" of \"" + aNode[j] + "\" to \"" + aValue + "\".");
}
}
}
}
}
/**
* Returns current person object
* @return current <code>IPerson</code>
*/
public IPerson getPerson () {
return (m_person);
}
/**
* Returns a global channel Id given a channel instance Id
* @param channelInstanceId instance id of a channel
* @return channel global id
*/
public String getChannelGlobalId (String channelInstanceId) {
// Get the channel node from the user's layout
Node channelNode = getUserLayoutNode(channelInstanceId);
if (channelNode == null) {
return (null);
}
// Get the global channel Id from the channel node
Node channelIdNode = channelNode.getAttributes().getNamedItem("chanID");
if (channelIdNode == null) {
return (null);
}
// Return the channel's global Id
return (channelIdNode.getNodeValue());
}
/**
* put your documentation comment here
* @return boolean
*/
public boolean isUserAgentUnmapped () {
return unmapped_user_agent;
}
/*
* Resets both user layout and user preferences.
* Note that if any of the two are "null", old values will be used.
*/
public void setNewUserLayoutAndUserPreferences (Document newLayout, UserPreferences newPreferences, boolean channelsAdded) throws PortalException {
try {
if (newPreferences != null) {
ulsdb.putUserPreferences(m_person, newPreferences);
complete_up=newPreferences;
}
synchronized(layout_write_lock) {
if (newLayout != null) {
uLayoutXML = newLayout;
layout_write_lock.setValue(true);
ulsdb.setUserLayout(m_person, complete_up.getProfile().getProfileId(), uLayoutXML, channelsAdded);
}
}
} catch (Exception e) {
LogService.instance().log(LogService.ERROR, e);
throw new GeneralRenderingException(e.getMessage());
}
}
/**
* Gets a cloned copy of the user layout
* @return a clone of the user layout document
*/
public Document getUserLayoutCopy() {
return XML.cloneDocument((org.apache.xerces.dom.DocumentImpl)uLayoutXML);
}
public UserPreferences getUserPreferencesCopy () {
return new UserPreferences(this.getUserPreferences());
}
public UserProfile getCurrentProfile () {
return this.getUserPreferences().getProfile();
}
public ThemeStylesheetDescription getThemeStylesheetDescription () throws Exception {
if (this.tsd == null) {
tsd = ulsdb.getThemeStylesheetDescription(this.getCurrentProfile().getThemeStylesheetId());
}
return tsd;
}
public StructureStylesheetDescription getStructureStylesheetDescription () throws Exception {
if (this.ssd == null) {
ssd = ulsdb.getStructureStylesheetDescription(this.getCurrentProfile().getStructureStylesheetId());
}
return ssd;
}
public Node getUserLayoutNode (String elementId) {
return uLayoutXML.getElementById(elementId);
}
public Document getUserLayout () {
return uLayoutXML;
}
public UserPreferences getUserPreferences() {
return complete_up;
}
/**
* helper function that allows to determine the name of a channel or
* folder in the current user layout given their Id.
* @param nodeId
* @return node name
*/
public String getNodeName (String nodeId) {
Element node = uLayoutXML.getElementById(nodeId);
if (node != null) {
return node.getAttribute("name");
}
else
return null;
}
public boolean removeChannel (String channelId) throws PortalException {
// warning .. the channel should also be removed from uLayoutXML
Element channel = uLayoutXML.getElementById(channelId);
if (channel != null) {
boolean rval=true;
synchronized(layout_write_lock) {
if(!this.deleteNode(channel)) {
// unable to remove channel due to unremovable/immutable restrictionsn
LogService.instance().log(LogService.INFO,"UserLayoutManager::removeChannlel() : unable to remove a channel \""+channelId+"\"");
rval=false;
} else {
layout_write_lock.setValue(true);
// channel has been removed from the userLayoutXML .. persist the layout ?
// NOTE: this shouldn't be done every time a channel is removed. A separate portal event should initiate save
// (or, alternatively, an incremental update should be done on the UserLayoutStore())
try {
/*
The following patch has been kindly contributed by Neil Blake <nd_blake@NICKEL.LAURENTIAN.CA>.
*/
ulsdb.setUserLayout(m_person, complete_up.getProfile().getProfileId(), uLayoutXML, false);
/* end of patch */
} catch (Exception e) {
LogService.instance().log(LogService.ERROR,"UserLayoutManager::removeChannle() : database operation resulted in an exception "+e);
throw new GeneralRenderingException("Unable to save layout changes.");
}
// LogService.instance().log(LogService.INFO,"UserLayoutManager::removeChannlel() : removed a channel \""+channelId+"\"");
}
}
return rval;
} else {
LogService.instance().log(LogService.ERROR, "UserLayoutManager::removeChannel() : unable to find a channel with Id=" + channelId);
return false;
}
}
/**
* Returns user layout write lock
*
* @return an <code>Object</code> lock
*/
public BooleanLock getUserLayoutWriteLock() {
return layout_write_lock;
}
/**
* Returns a child with a particular tagname
* @param node parent node
* @param tagName child's tag name
* @return child that matches the tag name
*/
private static Element getChildByTagName (Node node, String tagName) {
if (node == null)
return null;
NodeList children = node.getChildNodes();
for (int i = children.getLength() - 1; i >= 0; i
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element)child;
if ((el.getTagName()).equals(tagName))
return el;
}
}
return null;
}
/**
* Determines if the node or any of it's parents are marked
* as "unremovable".
* @param node the node to be tested
*/
public static boolean isUnremovable (Node node) {
if (getUnremovableParent(node) != null)
return true;
else
return false;
}
/**
* Determines if the node or any of it's parents are marked as immutables
* @param node the node to be tested
* @param root the root node of the layout tree
*/
public static boolean isImmutable (Node node) {
if (getImmutableParent(node) != null)
return true;
else
return false;
}
/**
* Returns first parent of the node (or the node itself) that's marked
* as "unremovable". Note that if the node itself is marked as
* "unremovable", the method will return the node itself.
* @param node node from which to move up the tree
*/
public static Node getUnremovableParent (Node node) {
if (node == null)
return null;
if (node.getNodeType() == Node.ELEMENT_NODE) {
String r = ((Element)node).getAttribute("unremovable");
if (r != null) {
if (r.equals("true"))
return node;
}
}
return getUnremovableParent(node.getParentNode());
}
/**
* Returns first parent of the node (or the node itself) that's marked
* as "immutable". Note that if the node itself is marked as
* "ummutable", the method will return the node itself.
* @param node node from which to move up the tree
*/
public static Node getImmutableParent (Node node) {
if (node == null)
return null;
if (node.getNodeType() == Node.ELEMENT_NODE) {
String r = ((Element)node).getAttribute("immutable");
if (r != null) {
if (r.equals("true"))
return node;
}
}
return getUnremovableParent(node.getParentNode());
}
/**
* Returns true if a node has any unremovable children.
* This function does a depth-first traversal down the user layout, so it's rather expensive.
*
* @param node a <code>Node</code> current node
* @return a <code>boolean</code> true if there are any unremovable children of this node
*/
public static boolean hasUnremovableChildren (Node node) {
NodeList nl = node.getChildNodes();
if (nl != null)
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
String r = ((Element)n).getAttribute("unremovable");
if (r != null) {
if (r.equals("true")) {
return true;
}
}
if (hasUnremovableChildren(n))
return true;
}
}
return false;
}
/**
* Removes a channel or a folder from the userLayout structure
* @param node the node to be removed
* @return removal has been successfull
*/
public static boolean deleteNode (Node node) {
// first of all check if this is an Element node
if (node == null || node.getNodeType() != Node.ELEMENT_NODE)
return false;
// check if the node is removable
if (isUnremovable(node))
return false;
// see if any of the parent nodes marked as immutable
if (isImmutable(node.getParentNode()))
return false;
// see if any of the node children are marked as unremovable
if (hasUnremovableChildren(node))
return false;
// all checks out, delete the node
if (node.getParentNode() != null) {
(node.getParentNode()).removeChild(node);
return true;
} else {
LogService.instance().log(LogService.ERROR,"UserLayoutManager::deleteNode() : trying to remove a root node ?!?");
return false;
}
}
/**
* Checks if a particular node is a descendent of some other node.
* Note that if both ancestor and node point at the same node, true
* will be returned.
* @param node the node to be checked
* @param ancestor potential ancestor
* @return true if node is an descendent of ancestor
*/
private static boolean isDescendentOf (Node ancestor, Node node) {
if (node == null)
return false;
if (node == ancestor)
return true;
else
return isDescendentOf(ancestor, node.getParentNode());
}
/**
* Moves node from one location in the userLayout tree to another
* @param node the node to be moved
* @param target the node to which it should be appended.
* @param sibiling a sibiling before which the node should be inserted under the target node (can be null)
* @return move has been successfull
*/
public static boolean moveNode (Node node, Node target, Node sibiling) {
// make sure this is an element node
if (node == null || node.getNodeType() != Node.ELEMENT_NODE)
return false;
if (target == null || target.getNodeType() != Node.ELEMENT_NODE)
return false;
// source node checks
// see if the source is a descendent of an immutable node
if (isImmutable(node.getParentNode()))
return false;
// see if the source is a descendent of some unremovable node
Node unrp = getUnremovableParent(node.getParentNode());
if (unrp != null) {
// make sure the target node is a descendent of the same unremovable
// node as well.
if (!isDescendentOf(unrp, target))
return false;
}
// target node checks
// check if the target is unremovable or immutable
if (isUnremovable(target) || isImmutable(target))
return false;
// everything checks out, do the move
if (sibiling != null && sibiling.getParentNode() == target) {
target.insertBefore(node, sibiling);
}
else {
target.appendChild(node);
}
return true;
}
}
|
package org.jfree.chart;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Paint;
import java.awt.Stroke;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.PeriodAxis;
import org.jfree.chart.axis.PeriodAxisLabelInfo;
import org.jfree.chart.axis.SymbolAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.block.Block;
import org.jfree.chart.block.BlockContainer;
import org.jfree.chart.block.LabelBlock;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.CombinedDomainCategoryPlot;
import org.jfree.chart.plot.CombinedDomainXYPlot;
import org.jfree.chart.plot.CombinedRangeCategoryPlot;
import org.jfree.chart.plot.CombinedRangeXYPlot;
import org.jfree.chart.plot.DefaultDrawingSupplier;
import org.jfree.chart.plot.DrawingSupplier;
import org.jfree.chart.plot.FastScatterPlot;
import org.jfree.chart.plot.MeterPlot;
import org.jfree.chart.plot.MultiplePiePlot;
import org.jfree.chart.plot.PieLabelLinkStyle;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PolarPlot;
import org.jfree.chart.plot.SpiderWebPlot;
import org.jfree.chart.plot.ThermometerPlot;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.AbstractRenderer;
import org.jfree.chart.renderer.category.BarPainter;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.chart.renderer.category.GradientBarPainter;
import org.jfree.chart.renderer.category.LineRenderer3D;
import org.jfree.chart.renderer.category.MinMaxCategoryRenderer;
import org.jfree.chart.renderer.category.StatisticalBarRenderer;
import org.jfree.chart.renderer.xy.GradientXYBarPainter;
import org.jfree.chart.renderer.xy.XYBarPainter;
import org.jfree.chart.renderer.xy.XYBarRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.title.CompositeTitle;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.PaintScaleLegend;
import org.jfree.chart.title.TextTitle;
import org.jfree.chart.title.Title;
import org.jfree.io.SerialUtilities;
import org.jfree.ui.RectangleInsets;
import org.jfree.util.PaintUtilities;
import org.jfree.util.PublicCloneable;
/**
* A default implementation of the {@link ChartTheme} interface. This
* implementation just collects a whole bunch of chart attributes and mimics
* the manual process of applying each attribute to the right sub-object
* within the JFreeChart instance. It's not elegant code, but it works.
*
* @since 1.0.11
*/
public class StandardChartTheme implements ChartTheme, Cloneable,
PublicCloneable, Serializable {
/** The name of this theme. */
private String name;
/**
* The largest font size. Use for the main chart title.
*/
private Font extraLargeFont;
/**
* A large font. Used for subtitles.
*/
private Font largeFont;
/**
* The regular font size. Used for axis tick labels, legend items etc.
*/
private Font regularFont;
/** The paint used to display the main chart title. */
private transient Paint titlePaint;
/** The paint used to display subtitles. */
private transient Paint subtitlePaint;
/** The background paint for the chart. */
private transient Paint chartBackgroundPaint;
/** The legend background paint. */
private transient Paint legendBackgroundPaint;
/** The legend item paint. */
private transient Paint legendItemPaint;
/** The drawing supplier. */
private DrawingSupplier drawingSupplier;
/** The background paint for the plot. */
private transient Paint plotBackgroundPaint;
/** The plot outline paint. */
private transient Paint plotOutlinePaint;
/** The label link style for pie charts. */
private PieLabelLinkStyle labelLinkStyle;
/** The label link paint for pie charts. */
private transient Paint labelLinkPaint;
/** The domain grid line paint. */
private transient Paint domainGridlinePaint;
/** The range grid line paint. */
private transient Paint rangeGridlinePaint;
/** The axis offsets. */
private RectangleInsets axisOffset;
/** The axis label paint. */
private transient Paint axisLabelPaint;
/** The tick label paint. */
private transient Paint tickLabelPaint;
/** The item label paint. */
private transient Paint itemLabelPaint;
/**
* A flag that controls whether or not shadows are visible (for example,
* in a bar renderer).
*/
private boolean shadowVisible;
/** The shadow paint. */
private transient Paint shadowPaint;
/** The bar painter. */
private BarPainter barPainter;
/** The XY bar painter. */
private XYBarPainter xyBarPainter;
/** The thermometer paint. */
private transient Paint thermometerPaint;
/**
* The paint used to fill the interior of the 'walls' in the background
* of a plot with a 3D effect. Applied to BarRenderer3D.
*/
private transient Paint wallPaint;
/** The error indicator paint for the {@link StatisticalBarRenderer}. */
private transient Paint errorIndicatorPaint;
/** The grid band paint for a {@link SymbolAxis}. */
private transient Paint gridBandPaint = SymbolAxis.DEFAULT_GRID_BAND_PAINT;
/** The grid band alternate paint for a {@link SymbolAxis}. */
private transient Paint gridBandAlternatePaint
= SymbolAxis.DEFAULT_GRID_BAND_ALTERNATE_PAINT;
/**
* Creates and returns the default 'JFree' chart theme.
*
* @return A chart theme.
*/
public static ChartTheme createJFreeTheme() {
return new StandardChartTheme("JFree");
}
/**
* Creates and returns a theme called "Darkness". In this theme, the
* charts have a black background.
*
* @return The "Darkness" theme.
*/
public static ChartTheme createDarknessTheme() {
StandardChartTheme theme = new StandardChartTheme("Darkness");
theme.titlePaint = Color.white;
theme.subtitlePaint = Color.white;
theme.legendBackgroundPaint = Color.black;
theme.legendItemPaint = Color.white;
theme.chartBackgroundPaint = Color.black;
theme.plotBackgroundPaint = Color.black;
theme.plotOutlinePaint = Color.yellow;
theme.labelLinkPaint = Color.lightGray;
theme.tickLabelPaint = Color.white;
theme.axisLabelPaint = Color.white;
theme.shadowPaint = Color.darkGray;
theme.itemLabelPaint = Color.white;
theme.drawingSupplier = new DefaultDrawingSupplier(
new Paint[] { Color.decode("0xFFFF00"),
Color.decode("0x0036CC"), Color.decode("0xFF0000"),
Color.decode("0xFFFF7F"), Color.decode("0x6681CC"),
Color.decode("0xFF7F7F"), Color.decode("0xFFFFBF"),
Color.decode("0x99A6CC"), Color.decode("0xFFBFBF"),
Color.decode("0xA9A938"), Color.decode("0x2D4587")},
new Paint[] { Color.decode("0xFFFF00"),
Color.decode("0x0036CC")},
new Stroke[] { new BasicStroke(2.0f)},
new Stroke[] { new BasicStroke(0.5f)},
DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE);
theme.wallPaint = Color.darkGray;
theme.errorIndicatorPaint = Color.lightGray;
theme.gridBandPaint = new Color(255, 255, 255, 20);
theme.gridBandAlternatePaint = new Color(255, 255, 255, 40);
return theme;
}
/**
* Creates and returns a {@link ChartTheme} that doesn't apply any changes
* to the JFreeChart defaults. This produces the "legacy" look for
* JFreeChart.
*
* @return A legacy theme.
*/
public static ChartTheme createLegacyTheme() {
StandardChartTheme theme = new StandardChartTheme("Legacy") {
public void apply(JFreeChart chart) {
// do nothing at all
}
};
return theme;
}
/**
* Creates a new default instance.
*
* @param name the name of the theme (<code>null</code> not permitted).
*/
public StandardChartTheme(String name) {
if (name == null) {
throw new IllegalArgumentException("Null 'name' argument.");
}
this.name = name;
this.extraLargeFont = new Font("Tahoma", Font.BOLD, 20);
this.largeFont = new Font("Tahoma", Font.BOLD, 14);
this.regularFont = new Font("Tahoma", Font.PLAIN, 12);
this.titlePaint = Color.black;
this.subtitlePaint = Color.black;
this.legendBackgroundPaint = Color.white;
this.legendItemPaint = Color.darkGray;
this.chartBackgroundPaint = Color.white;
this.drawingSupplier = new DefaultDrawingSupplier();
this.plotBackgroundPaint = Color.lightGray;
this.plotOutlinePaint = Color.black;
this.labelLinkPaint = Color.black;
this.labelLinkStyle = PieLabelLinkStyle.CUBIC_CURVE;
this.axisOffset = new RectangleInsets(4, 4, 4, 4);
this.domainGridlinePaint = Color.white;
this.rangeGridlinePaint = Color.white;
this.axisLabelPaint = Color.darkGray;
this.tickLabelPaint = Color.darkGray;
this.barPainter = new GradientBarPainter();
this.xyBarPainter = new GradientXYBarPainter();
this.shadowVisible = true;
this.shadowPaint = Color.gray;
this.itemLabelPaint = Color.black;
this.thermometerPaint = Color.white;
this.wallPaint = BarRenderer3D.DEFAULT_WALL_PAINT;
this.errorIndicatorPaint = Color.black;
}
/**
* Returns the largest font for this theme.
*
* @return The largest font for this theme.
*
* @see #setExtraLargeFont(Font)
*/
public Font getExtraLargeFont() {
return this.extraLargeFont;
}
/**
* Sets the largest font for this theme.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getExtraLargeFont()
*/
public void setExtraLargeFont(Font font) {
if (font == null) {
throw new IllegalArgumentException("Null 'font' argument.");
}
this.extraLargeFont = font;
}
/**
* Returns the large font for this theme.
*
* @return The large font (never <code>null</code>).
*
* @see #setLargeFont(Font)
*/
public Font getLargeFont() {
return this.largeFont;
}
/**
* Sets the large font for this theme.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getLargeFont()
*/
public void setLargeFont(Font font) {
this.largeFont = font;
}
/**
* Returns the regular font.
*
* @return The regular font (never <code>null</code>).
*
* @see #setRegularFont(Font)
*/
public Font getRegularFont() {
return this.regularFont;
}
/**
* Sets the regular font for this theme.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getRegularFont()
*/
public void setRegularFont(Font font) {
this.regularFont = font;
}
/**
* Returns the title paint.
*
* @return The title paint (never <code>null</code>).
*
* @see #setTitlePaint(Paint)
*/
public Paint getTitlePaint() {
return this.titlePaint;
}
/**
* Sets the title paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getTitlePaint()
*/
public void setTitlePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.titlePaint = paint;
}
/**
* Returns the subtitle paint.
*
* @return The subtitle paint (never <code>null</code>).
*
* @see #setSubtitlePaint(Paint)
*/
public Paint getSubtitlePaint() {
return this.subtitlePaint;
}
/**
* Sets the subtitle paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getSubtitlePaint()
*/
public void setSubtitlePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.subtitlePaint = paint;
}
/**
* Returns the chart background paint.
*
* @return The chart background paint (never <code>null</code>).
*
* @see #setChartBackgroundPaint(Paint)
*/
public Paint getChartBackgroundPaint() {
return this.chartBackgroundPaint;
}
/**
* Sets the chart background paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getChartBackgroundPaint()
*/
public void setChartBackgroundPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.chartBackgroundPaint = paint;
}
/**
* Returns the legend background paint.
*
* @return The legend background paint (never <code>null</code>).
*
* @see #setLegendBackgroundPaint(Paint)
*/
public Paint getLegendBackgroundPaint() {
return this.legendBackgroundPaint;
}
/**
* Sets the legend background paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getLegendBackgroundPaint()
*/
public void setLegendBackgroundPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.legendBackgroundPaint = paint;
}
/**
* Returns the legend item paint.
*
* @return The legend item paint (never <code>null</code>).
*
* @see #setLegendItemPaint(Paint)
*/
public Paint getLegendItemPaint() {
return this.legendItemPaint;
}
/**
* Sets the legend item paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getLegendItemPaint()
*/
public void setLegendItemPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.legendItemPaint = paint;
}
/**
* Returns the plot background paint.
*
* @return The plot background paint (never <code>null</code>).
*
* @see #setPlotBackgroundPaint(Paint)
*/
public Paint getPlotBackgroundPaint() {
return this.plotBackgroundPaint;
}
/**
* Sets the plot background paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getPlotBackgroundPaint()
*/
public void setPlotBackgroundPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.plotBackgroundPaint = paint;
}
/**
* Returns the plot outline paint.
*
* @return The plot outline paint (never <code>null</code>).
*
* @see #setPlotOutlinePaint(Paint)
*/
public Paint getPlotOutlinePaint() {
return this.plotOutlinePaint;
}
/**
* Sets the plot outline paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getPlotOutlinePaint()
*/
public void setPlotOutlinePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.plotOutlinePaint = paint;
}
/**
* Returns the label link style for pie charts.
*
* @return The label link style (never <code>null</code>).
*
* @see #setLabelLinkStyle(PieLabelLinkStyle)
*/
public PieLabelLinkStyle getLabelLinkStyle() {
return this.labelLinkStyle;
}
/**
* Sets the label link style for pie charts.
*
* @param style the style (<code>null</code> not permitted).
*
* @see #getLabelLinkStyle()
*/
public void setLabelLinkStyle(PieLabelLinkStyle style) {
if (style == null) {
throw new IllegalArgumentException("Null 'style' argument.");
}
this.labelLinkStyle = style;
}
/**
* Returns the label link paint for pie charts.
*
* @return The label link paint (never <code>null</code>).
*
* @see #setLabelLinkPaint(Paint)
*/
public Paint getLabelLinkPaint() {
return this.labelLinkPaint;
}
/**
* Sets the label link paint for pie charts.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getLabelLinkPaint()
*/
public void setLabelLinkPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.labelLinkPaint = paint;
}
/**
* Returns the domain grid line paint.
*
* @return The domain grid line paint (never <code>null<code>).
*
* @see #setDomainGridlinePaint(Paint)
*/
public Paint getDomainGridlinePaint() {
return this.domainGridlinePaint;
}
/**
* Sets the domain grid line paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getDomainGridlinePaint()
*/
public void setDomainGridlinePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.domainGridlinePaint = paint;
}
/**
* Returns the range grid line paint.
*
* @return The range grid line paint (never <code>null</code>).
*
* @see #setRangeGridlinePaint(Paint)
*/
public Paint getRangeGridlinePaint() {
return this.rangeGridlinePaint;
}
/**
* Sets the range grid line paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getRangeGridlinePaint()
*/
public void setRangeGridlinePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.rangeGridlinePaint = paint;
}
/**
* Returns the axis offsets.
*
* @return The axis offsets (never <code>null</code>).
*
* @see #setAxisOffset(RectangleInsets)
*/
public RectangleInsets getAxisOffset() {
return this.axisOffset;
}
/**
* Sets the axis offset.
*
* @param offset the offset (<code>null</code> not permitted).
*
* @see #getAxisOffset()
*/
public void setAxisOffset(RectangleInsets offset) {
if (offset == null) {
throw new IllegalArgumentException("Null 'offset' argument.");
}
this.axisOffset = offset;
}
/**
* Returns the axis label paint.
*
* @return The axis label paint (never <code>null</code>).
*
* @see #setAxisLabelPaint(Paint)
*/
public Paint getAxisLabelPaint() {
return this.axisLabelPaint;
}
/**
* Sets the axis label paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getAxisLabelPaint()
*/
public void setAxisLabelPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.axisLabelPaint = paint;
}
/**
* Returns the tick label paint.
*
* @return The tick label paint (never <code>null</code>).
*
* @see #setTickLabelPaint(Paint)
*/
public Paint getTickLabelPaint() {
return this.tickLabelPaint;
}
/**
* Sets the tick label paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getTickLabelPaint()
*/
public void setTickLabelPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.tickLabelPaint = paint;
}
/**
* Returns the item label paint.
*
* @return The item label paint (never <code>null</code>).
*
* @see #setItemLabelPaint(Paint)
*/
public Paint getItemLabelPaint() {
return this.itemLabelPaint;
}
/**
* Sets the item label paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getItemLabelPaint()
*/
public void setItemLabelPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.itemLabelPaint = paint;
}
/**
* Returns the shadow visibility flag.
*
* @return The shadow visibility flag.
*
* @see #setShadowVisible(boolean)
*/
public boolean isShadowVisible() {
return this.shadowVisible;
}
/**
* Sets the shadow visibility flag.
*
* @param visible the flag.
*
* @see #isShadowVisible()
*/
public void setShadowVisible(boolean visible) {
this.shadowVisible = visible;
}
/**
* Returns the shadow paint.
*
* @return The shadow paint (never <code>null</code>).
*
* @see #setShadowPaint(Paint)
*/
public Paint getShadowPaint() {
return this.shadowPaint;
}
/**
* Sets the shadow paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getShadowPaint()
*/
public void setShadowPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.shadowPaint = paint;
}
/**
* Returns the bar painter.
*
* @return The bar painter (never <code>null</code>).
*
* @see #setBarPainter(BarPainter)
*/
public BarPainter getBarPainter() {
return this.barPainter;
}
/**
* Sets the bar painter.
*
* @param painter the painter (<code>null</code> not permitted).
*
* @see #getBarPainter()
*/
public void setBarPainter(BarPainter painter) {
if (painter == null) {
throw new IllegalArgumentException("Null 'painter' argument.");
}
this.barPainter = painter;
}
/**
* Returns the XY bar painter.
*
* @return The XY bar painter (never <code>null</code>).
*
* @see #setXYBarPainter(XYBarPainter)
*/
public XYBarPainter getXYBarPainter() {
return this.xyBarPainter;
}
/**
* Sets the XY bar painter.
*
* @param painter the painter (<code>null</code> not permitted).
*
* @see #getXYBarPainter()
*/
public void setXYBarPainter(XYBarPainter painter) {
if (painter == null) {
throw new IllegalArgumentException("Null 'painter' argument.");
}
this.xyBarPainter = painter;
}
/**
* Returns the thermometer paint.
*
* @return The thermometer paint (never <code>null</code>).
*
* @see #setThermometerPaint(Paint)
*/
public Paint getThermometerPaint() {
return this.thermometerPaint;
}
/**
* Sets the thermometer paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getThermometerPaint()
*/
public void setThermometerPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.thermometerPaint = paint;
}
/**
* Returns the wall paint for charts with a 3D effect.
*
* @return The wall paint (never <code>null</code>).
*
* @see #setWallPaint(Paint)
*/
public Paint getWallPaint() {
return this.wallPaint;
}
/**
* Sets the wall paint for charts with a 3D effect.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getWallPaint()
*/
public void setWallPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.wallPaint = paint;
}
/**
* Returns the error indicator paint.
*
* @return The error indicator paint (never <code>null</code>).
*
* @see #setErrorIndicatorPaint(Paint)
*/
public Paint getErrorIndicatorPaint() {
return this.errorIndicatorPaint;
}
/**
* Sets the error indicator paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getErrorIndicatorPaint()
*/
public void setErrorIndicatorPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.errorIndicatorPaint = paint;
}
/**
* Returns the grid band paint.
*
* @return The grid band paint (never <code>null</code>).
*
* @see #setGridBandPaint(Paint)
*/
public Paint getGridBandPaint() {
return this.gridBandPaint;
}
/**
* Sets the grid band paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getGridBandPaint()
*/
public void setGridBandPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.gridBandPaint = paint;
}
/**
* Returns the grid band alternate paint (used for a {@link SymbolAxis}).
*
* @return The paint (never <code>null</code>).
*
* @see #setGridBandAlternatePaint(Paint)
*/
public Paint getGridBandAlternatePaint() {
return this.gridBandAlternatePaint;
}
/**
* Sets the grid band alternate paint (used for a {@link SymbolAxis}).
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getGridBandAlternatePaint()
*/
public void setGridBandAlternatePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.gridBandAlternatePaint = paint;
}
/**
* Returns the name of this theme.
*
* @return The name of this theme.
*/
public String getName() {
return this.name;
}
/**
* Returns a clone of the drawing supplier for this theme.
*
* @return A clone of the drawing supplier.
*/
public DrawingSupplier getDrawingSupplier() {
DrawingSupplier result = null;
if (this.drawingSupplier instanceof PublicCloneable) {
PublicCloneable pc = (PublicCloneable) this.drawingSupplier;
try {
result = (DrawingSupplier) pc.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
return result;
}
/**
* Sets the drawing supplier for this theme.
*
* @param supplier the supplier (<code>null</code> not permitted).
*
* @see #getDrawingSupplier()
*/
public void setDrawingSupplier(DrawingSupplier supplier) {
if (supplier == null) {
throw new IllegalArgumentException("Null 'supplier' argument.");
}
this.drawingSupplier = supplier;
}
/**
* Applies this theme to the supplied chart.
*
* @param chart the chart (<code>null</code> not permitted).
*/
public void apply(JFreeChart chart) {
if (chart == null) {
throw new IllegalArgumentException("Null 'chart' argument.");
}
TextTitle title = chart.getTitle();
if (title != null) {
title.setFont(this.extraLargeFont);
title.setPaint(this.titlePaint);
}
int subtitleCount = chart.getSubtitleCount();
for (int i = 0; i < subtitleCount; i++) {
applyToTitle(chart.getSubtitle(i));
}
chart.setBackgroundPaint(this.chartBackgroundPaint);
// now process the plot if there is one
Plot plot = chart.getPlot();
if (plot != null) {
applyToPlot(plot);
}
}
/**
* Applies the attributes of this theme to the specified title.
*
* @param title the title.
*/
protected void applyToTitle(Title title) {
if (title instanceof TextTitle) {
TextTitle tt = (TextTitle) title;
tt.setFont(this.largeFont);
tt.setPaint(this.subtitlePaint);
}
else if (title instanceof LegendTitle) {
LegendTitle lt = (LegendTitle) title;
if (lt.getBackgroundPaint() != null) {
lt.setBackgroundPaint(this.legendBackgroundPaint);
}
lt.setItemFont(this.regularFont);
lt.setItemPaint(this.legendItemPaint);
if (lt.getWrapper() != null) {
applyToBlockContainer(lt.getWrapper());
}
}
else if (title instanceof PaintScaleLegend) {
PaintScaleLegend psl = (PaintScaleLegend) title;
psl.setBackgroundPaint(this.legendBackgroundPaint);
ValueAxis axis = psl.getAxis();
if (axis != null) {
applyToValueAxis(axis);
}
}
else if (title instanceof CompositeTitle) {
CompositeTitle ct = (CompositeTitle) title;
BlockContainer bc = ct.getContainer();
List blocks = bc.getBlocks();
Iterator iterator = blocks.iterator();
while (iterator.hasNext()) {
Block b = (Block) iterator.next();
if (b instanceof Title) {
applyToTitle((Title) b);
}
}
}
}
/**
* Applies the attributes of this theme to the specified container.
*
* @param bc a block container (<code>null</code> not permitted).
*/
protected void applyToBlockContainer(BlockContainer bc) {
Iterator iterator = bc.getBlocks().iterator();
while (iterator.hasNext()) {
Block b = (Block) iterator.next();
applyToBlock(b);
}
}
/**
* Applies the attributes of this theme to the specified block.
*
* @param b the block.
*/
protected void applyToBlock(Block b) {
if (b instanceof Title) {
applyToTitle((Title) b);
}
else if (b instanceof LabelBlock) {
LabelBlock lb = (LabelBlock) b;
lb.setFont(this.regularFont);
lb.setPaint(this.legendItemPaint);
}
}
/**
* Applies the attributes of this theme to a plot.
*
* @param plot the plot (<code>null</code>).
*/
protected void applyToPlot(Plot plot) {
if (plot == null) {
throw new IllegalArgumentException("Null 'plot' argument.");
}
if (plot.getDrawingSupplier() != null) {
plot.setDrawingSupplier(getDrawingSupplier());
}
if (plot.getBackgroundPaint() != null) {
plot.setBackgroundPaint(this.plotBackgroundPaint);
}
plot.setOutlinePaint(this.plotOutlinePaint);
// now handle specific plot types (and yes, I know this is some
// really ugly code that has to be manually updated any time a new
// plot type is added - I should have written something much cooler,
// but I didn't and neither did anyone else).
if (plot instanceof PiePlot) {
applyToPiePlot((PiePlot) plot);
}
else if (plot instanceof MultiplePiePlot) {
applyToMultiplePiePlot((MultiplePiePlot) plot);
}
else if (plot instanceof CategoryPlot) {
applyToCategoryPlot((CategoryPlot) plot);
}
else if (plot instanceof XYPlot) {
applyToXYPlot((XYPlot) plot);
}
else if (plot instanceof FastScatterPlot) {
applyToFastScatterPlot((FastScatterPlot) plot);
}
else if (plot instanceof MeterPlot) {
applyToMeterPlot((MeterPlot) plot);
}
else if (plot instanceof ThermometerPlot) {
applyToThermometerPlot((ThermometerPlot) plot);
}
else if (plot instanceof SpiderWebPlot) {
applyToSpiderWebPlot((SpiderWebPlot) plot);
}
else if (plot instanceof PolarPlot) {
applyToPolarPlot((PolarPlot) plot);
}
}
/**
* Applies the attributes of this theme to a {@link PiePlot} instance.
* This method also clears any set values for the section paint, outline
* etc, so that the theme's {@link DrawingSupplier} will be used.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToPiePlot(PiePlot plot) {
plot.setLabelLinkPaint(this.labelLinkPaint);
plot.setLabelLinkStyle(this.labelLinkStyle);
plot.setLabelFont(this.regularFont);
// clear the section attributes so that the theme's DrawingSupplier
// will be used
if (plot.getAutoPopulateSectionPaint()) {
plot.clearSectionPaints(false);
}
if (plot.getAutoPopulateSectionOutlinePaint()) {
plot.clearSectionOutlinePaints(false);
}
if (plot.getAutoPopulateSectionOutlineStroke()) {
plot.clearSectionOutlineStrokes(false);
}
}
/**
* Applies the attributes of this theme to a {@link MultiplePiePlot}.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToMultiplePiePlot(MultiplePiePlot plot) {
apply(plot.getPieChart());
}
/**
* Applies the attributes of this theme to a {@link CategoryPlot}.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToCategoryPlot(CategoryPlot plot) {
plot.setAxisOffset(this.axisOffset);
plot.setDomainGridlinePaint(this.domainGridlinePaint);
plot.setRangeGridlinePaint(this.rangeGridlinePaint);
// process all domain axes
int domainAxisCount = plot.getDomainAxisCount();
for (int i = 0; i < domainAxisCount; i++) {
CategoryAxis axis = (CategoryAxis) plot.getDomainAxis(i);
if (axis != null) {
applyToCategoryAxis(axis);
}
}
// process all range axes
int rangeAxisCount = plot.getRangeAxisCount();
for (int i = 0; i < rangeAxisCount; i++) {
ValueAxis axis = (ValueAxis) plot.getRangeAxis(i);
if (axis != null) {
applyToValueAxis(axis);
}
}
// process all renderers
int rendererCount = plot.getRendererCount();
for (int i = 0; i < rendererCount; i++) {
CategoryItemRenderer r = plot.getRenderer(i);
if (r != null) {
applyToCategoryItemRenderer(r);
}
}
if (plot instanceof CombinedDomainCategoryPlot) {
CombinedDomainCategoryPlot cp = (CombinedDomainCategoryPlot) plot;
Iterator iterator = cp.getSubplots().iterator();
while (iterator.hasNext()) {
CategoryPlot subplot = (CategoryPlot) iterator.next();
if (subplot != null) {
applyToPlot(subplot);
}
}
}
if (plot instanceof CombinedRangeCategoryPlot) {
CombinedRangeCategoryPlot cp = (CombinedRangeCategoryPlot) plot;
Iterator iterator = cp.getSubplots().iterator();
while (iterator.hasNext()) {
CategoryPlot subplot = (CategoryPlot) iterator.next();
if (subplot != null) {
applyToPlot(subplot);
}
}
}
}
/**
* Applies the attributes of this theme to a {@link XYPlot}.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToXYPlot(XYPlot plot) {
plot.setAxisOffset(this.axisOffset);
plot.setDomainGridlinePaint(this.domainGridlinePaint);
plot.setRangeGridlinePaint(this.rangeGridlinePaint);
// process all domain axes
int domainAxisCount = plot.getDomainAxisCount();
for (int i = 0; i < domainAxisCount; i++) {
ValueAxis axis = (ValueAxis) plot.getDomainAxis(i);
if (axis != null) {
applyToValueAxis(axis);
}
}
// process all range axes
int rangeAxisCount = plot.getRangeAxisCount();
for (int i = 0; i < rangeAxisCount; i++) {
ValueAxis axis = (ValueAxis) plot.getRangeAxis(i);
if (axis != null) {
applyToValueAxis(axis);
}
}
// process all renderers
int rendererCount = plot.getRendererCount();
for (int i = 0; i < rendererCount; i++) {
XYItemRenderer r = plot.getRenderer(i);
if (r != null) {
applyToXYItemRenderer(r);
}
}
if (plot instanceof CombinedDomainXYPlot) {
CombinedDomainXYPlot cp = (CombinedDomainXYPlot) plot;
Iterator iterator = cp.getSubplots().iterator();
while (iterator.hasNext()) {
XYPlot subplot = (XYPlot) iterator.next();
if (subplot != null) {
applyToPlot(subplot);
}
}
}
if (plot instanceof CombinedRangeXYPlot) {
CombinedRangeXYPlot cp = (CombinedRangeXYPlot) plot;
Iterator iterator = cp.getSubplots().iterator();
while (iterator.hasNext()) {
XYPlot subplot = (XYPlot) iterator.next();
if (subplot != null) {
applyToPlot(subplot);
}
}
}
}
/**
* Applies the attributes of this theme to a {@link FastScatterPlot}.
* @param plot
*/
protected void applyToFastScatterPlot(FastScatterPlot plot) {
plot.setDomainGridlinePaint(this.domainGridlinePaint);
plot.setRangeGridlinePaint(this.rangeGridlinePaint);
ValueAxis xAxis = plot.getDomainAxis();
if (xAxis != null) {
applyToValueAxis(xAxis);
}
ValueAxis yAxis = plot.getRangeAxis();
if (yAxis != null) {
applyToValueAxis(yAxis);
}
}
/**
* Applies the attributes of this theme to a {@link PolarPlot}. This
* method is called from the {@link #applyToPlot(Plot)} method.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToPolarPlot(PolarPlot plot) {
plot.setAngleLabelFont(this.regularFont);
plot.setAngleLabelPaint(this.tickLabelPaint);
plot.setAngleGridlinePaint(this.domainGridlinePaint);
plot.setRadiusGridlinePaint(this.rangeGridlinePaint);
ValueAxis axis = plot.getAxis();
if (axis != null) {
applyToValueAxis(axis);
}
}
/**
* Applies the attributes of this theme to a {@link SpiderWebPlot}.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToSpiderWebPlot(SpiderWebPlot plot) {
plot.setLabelFont(this.regularFont);
plot.setLabelPaint(this.axisLabelPaint);
plot.setAxisLinePaint(this.axisLabelPaint);
}
/**
* Applies the attributes of this theme to a {@link MeterPlot}.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToMeterPlot(MeterPlot plot) {
plot.setDialBackgroundPaint(this.plotBackgroundPaint);
plot.setValueFont(this.largeFont);
plot.setValuePaint(this.axisLabelPaint);
plot.setDialOutlinePaint(this.plotOutlinePaint);
plot.setNeedlePaint(this.thermometerPaint);
plot.setTickLabelFont(this.regularFont);
plot.setTickLabelPaint(this.tickLabelPaint);
}
/**
* Applies the attributes for this theme to a {@link ThermometerPlot}.
* This method is called from the {@link #applyToPlot(Plot)} method.
*
* @param plot the plot.
*/
protected void applyToThermometerPlot(ThermometerPlot plot) {
plot.setValueFont(this.largeFont);
plot.setThermometerPaint(this.thermometerPaint);
ValueAxis axis = plot.getRangeAxis();
if (axis != null) {
applyToValueAxis(axis);
}
}
/**
* Applies the attributes for this theme to a {@link CategoryAxis}.
*
* @param axis the axis (<code>null</code> not permitted).
*/
protected void applyToCategoryAxis(CategoryAxis axis) {
axis.setLabelFont(this.largeFont);
axis.setLabelPaint(this.axisLabelPaint);
axis.setTickLabelFont(this.regularFont);
axis.setTickLabelPaint(this.tickLabelPaint);
}
/**
* Applies the attributes for this theme to a {@link ValueAxis}.
*
* @param axis the axis (<code>null</code> not permitted).
*/
protected void applyToValueAxis(ValueAxis axis) {
axis.setLabelFont(this.largeFont);
axis.setLabelPaint(this.axisLabelPaint);
axis.setTickLabelFont(this.regularFont);
axis.setTickLabelPaint(this.tickLabelPaint);
if (axis instanceof SymbolAxis) {
applyToSymbolAxis((SymbolAxis) axis);
}
if (axis instanceof PeriodAxis) {
applyToPeriodAxis((PeriodAxis) axis);
}
}
/**
* Applies the attributes for this theme to a {@link SymbolAxis}.
*
* @param axis the axis (<code>null</code> not permitted).
*/
protected void applyToSymbolAxis(SymbolAxis axis) {
axis.setGridBandPaint(this.gridBandPaint);
axis.setGridBandAlternatePaint(this.gridBandAlternatePaint);
}
/**
* Applies the attributes for this theme to a {@link PeriodAxis}.
*
* @param axis the axis (<code>null</code> not permitted).
*/
protected void applyToPeriodAxis(PeriodAxis axis) {
PeriodAxisLabelInfo[] info = axis.getLabelInfo();
for (int i = 0; i < info.length; i++) {
PeriodAxisLabelInfo e = info[i];
PeriodAxisLabelInfo n = new PeriodAxisLabelInfo(e.getPeriodClass(),
e.getDateFormat(), e.getPadding(), this.regularFont,
this.tickLabelPaint, e.getDrawDividers(),
e.getDividerStroke(), e.getDividerPaint());
info[i] = n;
}
axis.setLabelInfo(info);
}
/**
* Applies the attributes for this theme to an {@link AbstractRenderer}.
*
* @param renderer the renderer (<code>null</code> not permitted).
*/
protected void applyToAbstractRenderer(AbstractRenderer renderer) {
if (renderer.getAutoPopulateSeriesPaint()) {
renderer.clearSeriesPaints(false);
}
if (renderer.getAutoPopulateSeriesStroke()) {
renderer.clearSeriesStrokes(false);
}
}
/**
* Applies the settings of this theme to the specified renderer.
*
* @param renderer the renderer (<code>null</code> not permitted).
*/
protected void applyToCategoryItemRenderer(CategoryItemRenderer renderer) {
if (renderer == null) {
throw new IllegalArgumentException("Null 'renderer' argument.");
}
if (renderer instanceof AbstractRenderer) {
applyToAbstractRenderer((AbstractRenderer) renderer);
}
renderer.setBaseItemLabelFont(this.regularFont);
renderer.setBaseItemLabelPaint(this.itemLabelPaint);
// now we handle some special cases - yes, UGLY code alert!
// BarRenderer
if (renderer instanceof BarRenderer) {
BarRenderer br = (BarRenderer) renderer;
br.setBarPainter(this.barPainter);
br.setShadowVisible(this.shadowVisible);
br.setShadowPaint(this.shadowPaint);
}
// BarRenderer3D
if (renderer instanceof BarRenderer3D) {
BarRenderer3D br3d = (BarRenderer3D) renderer;
br3d.setWallPaint(this.wallPaint);
}
// LineRenderer3D
if (renderer instanceof LineRenderer3D) {
LineRenderer3D lr3d = (LineRenderer3D) renderer;
lr3d.setWallPaint(this.wallPaint);
}
// StatisticalBarRenderer
if (renderer instanceof StatisticalBarRenderer) {
StatisticalBarRenderer sbr = (StatisticalBarRenderer) renderer;
sbr.setErrorIndicatorPaint(this.errorIndicatorPaint);
}
// MinMaxCategoryRenderer
if (renderer instanceof MinMaxCategoryRenderer) {
MinMaxCategoryRenderer mmcr = (MinMaxCategoryRenderer) renderer;
mmcr.setGroupPaint(this.errorIndicatorPaint);
}
}
/**
* Applies the settings of this theme to the specified renderer.
*
* @param renderer the renderer (<code>null</code> not permitted).
*/
protected void applyToXYItemRenderer(XYItemRenderer renderer) {
if (renderer == null) {
throw new IllegalArgumentException("Null 'renderer' argument.");
}
if (renderer instanceof AbstractRenderer) {
applyToAbstractRenderer((AbstractRenderer) renderer);
}
renderer.setBaseItemLabelFont(this.regularFont);
renderer.setBaseItemLabelPaint(this.itemLabelPaint);
if (renderer instanceof XYBarRenderer) {
XYBarRenderer br = (XYBarRenderer) renderer;
br.setBarPainter(this.xyBarPainter);
br.setShadowVisible(this.shadowVisible);
}
}
/**
* Tests this theme for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof StandardChartTheme)) {
return false;
}
StandardChartTheme that = (StandardChartTheme) obj;
if (!this.name.equals(that.name)) {
return false;
}
if (!this.extraLargeFont.equals(that.extraLargeFont)) {
return false;
}
if (!this.largeFont.equals(that.largeFont)) {
return false;
}
if (!this.regularFont.equals(that.regularFont)) {
return false;
}
if (!PaintUtilities.equal(this.titlePaint, that.titlePaint)) {
return false;
}
if (!PaintUtilities.equal(this.subtitlePaint, that.subtitlePaint)) {
return false;
}
if (!PaintUtilities.equal(this.chartBackgroundPaint,
that.chartBackgroundPaint)) {
return false;
}
if (!PaintUtilities.equal(this.legendBackgroundPaint,
that.legendBackgroundPaint)) {
return false;
}
if (!PaintUtilities.equal(this.legendItemPaint, that.legendItemPaint)) {
return false;
}
if (!this.drawingSupplier.equals(that.drawingSupplier)) {
return false;
}
if (!PaintUtilities.equal(this.plotBackgroundPaint,
that.plotBackgroundPaint)) {
return false;
}
if (!PaintUtilities.equal(this.plotOutlinePaint,
that.plotOutlinePaint)) {
return false;
}
if (!this.labelLinkStyle.equals(that.labelLinkStyle)) {
return false;
}
if (!PaintUtilities.equal(this.labelLinkPaint, that.labelLinkPaint)) {
return false;
}
if (!PaintUtilities.equal(this.domainGridlinePaint,
that.domainGridlinePaint)) {
return false;
}
if (!PaintUtilities.equal(this.rangeGridlinePaint,
that.rangeGridlinePaint)) {
return false;
}
if (!this.axisOffset.equals(that.axisOffset)) {
return false;
}
if (!PaintUtilities.equal(this.axisLabelPaint, that.axisLabelPaint)) {
return false;
}
if (!PaintUtilities.equal(this.tickLabelPaint, that.tickLabelPaint)) {
return false;
}
if (!PaintUtilities.equal(this.itemLabelPaint, that.itemLabelPaint)) {
return false;
}
if (this.shadowVisible != that.shadowVisible) {
return false;
}
if (!PaintUtilities.equal(this.shadowPaint, that.shadowPaint)) {
return false;
}
if (!this.barPainter.equals(that.barPainter)) {
return false;
}
if (!this.xyBarPainter.equals(that.xyBarPainter)) {
return false;
}
if (!PaintUtilities.equal(this.thermometerPaint,
that.thermometerPaint)) {
return false;
}
if (!PaintUtilities.equal(this.wallPaint, that.wallPaint)) {
return false;
}
if (!PaintUtilities.equal(this.errorIndicatorPaint,
that.errorIndicatorPaint)) {
return false;
}
if (!PaintUtilities.equal(this.gridBandPaint, that.gridBandPaint)) {
return false;
}
if (!PaintUtilities.equal(this.gridBandAlternatePaint,
that.gridBandAlternatePaint)) {
return false;
}
return true;
}
/**
* Returns a clone of this theme.
*
* @return A clone.
*
* @throws CloneNotSupportedException if the theme cannot be cloned.
*/
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
/**
* Provides serialization support.
*
* @param stream the output stream (<code>null</code> not permitted).
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writePaint(this.titlePaint, stream);
SerialUtilities.writePaint(this.subtitlePaint, stream);
SerialUtilities.writePaint(this.chartBackgroundPaint, stream);
SerialUtilities.writePaint(this.legendBackgroundPaint, stream);
SerialUtilities.writePaint(this.legendItemPaint, stream);
SerialUtilities.writePaint(this.plotBackgroundPaint, stream);
SerialUtilities.writePaint(this.plotOutlinePaint, stream);
SerialUtilities.writePaint(this.labelLinkPaint, stream);
SerialUtilities.writePaint(this.domainGridlinePaint, stream);
SerialUtilities.writePaint(this.rangeGridlinePaint, stream);
SerialUtilities.writePaint(this.axisLabelPaint, stream);
SerialUtilities.writePaint(this.tickLabelPaint, stream);
SerialUtilities.writePaint(this.itemLabelPaint, stream);
SerialUtilities.writePaint(this.shadowPaint, stream);
SerialUtilities.writePaint(this.thermometerPaint, stream);
SerialUtilities.writePaint(this.wallPaint, stream);
SerialUtilities.writePaint(this.errorIndicatorPaint, stream);
SerialUtilities.writePaint(this.gridBandPaint, stream);
SerialUtilities.writePaint(this.gridBandAlternatePaint, stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream (<code>null</code> not permitted).
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.titlePaint = SerialUtilities.readPaint(stream);
this.subtitlePaint = SerialUtilities.readPaint(stream);
this.chartBackgroundPaint = SerialUtilities.readPaint(stream);
this.legendBackgroundPaint = SerialUtilities.readPaint(stream);
this.legendItemPaint = SerialUtilities.readPaint(stream);
this.plotBackgroundPaint = SerialUtilities.readPaint(stream);
this.plotOutlinePaint = SerialUtilities.readPaint(stream);
this.labelLinkPaint = SerialUtilities.readPaint(stream);
this.domainGridlinePaint = SerialUtilities.readPaint(stream);
this.rangeGridlinePaint = SerialUtilities.readPaint(stream);
this.axisLabelPaint = SerialUtilities.readPaint(stream);
this.tickLabelPaint = SerialUtilities.readPaint(stream);
this.itemLabelPaint = SerialUtilities.readPaint(stream);
this.shadowPaint = SerialUtilities.readPaint(stream);
this.thermometerPaint = SerialUtilities.readPaint(stream);
this.wallPaint = SerialUtilities.readPaint(stream);
this.errorIndicatorPaint = SerialUtilities.readPaint(stream);
this.gridBandPaint = SerialUtilities.readPaint(stream);
this.gridBandAlternatePaint = SerialUtilities.readPaint(stream);
}
}
|
package protocolsupport.zplatform.impl.glowstone;
import java.security.KeyPair;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.stream.Collectors;
import org.bukkit.Achievement;
import org.bukkit.Bukkit;
import org.bukkit.Statistic;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.CachedServerIcon;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import net.glowstone.GlowServer;
import net.glowstone.constants.GlowAchievement;
import net.glowstone.constants.GlowStatistic;
import net.glowstone.entity.meta.profile.PlayerProfile;
import net.glowstone.entity.meta.profile.PlayerProperty;
import net.glowstone.io.nbt.NbtSerialization;
import net.glowstone.net.protocol.ProtocolType;
import net.glowstone.util.GlowServerIcon;
import protocolsupport.protocol.pipeline.IPacketPrepender;
import protocolsupport.protocol.pipeline.IPacketSplitter;
import protocolsupport.protocol.utils.authlib.GameProfile;
import protocolsupport.zplatform.PlatformUtils;
import protocolsupport.zplatform.impl.glowstone.itemstack.GlowStoneNBTTagCompoundWrapper;
import protocolsupport.zplatform.impl.glowstone.network.GlowStoneChannelHandlers;
import protocolsupport.zplatform.impl.glowstone.network.GlowStoneNetworkManagerWrapper;
import protocolsupport.zplatform.impl.glowstone.network.pipeline.GlowStoneFramingHandler;
import protocolsupport.zplatform.itemstack.NBTTagCompoundWrapper;
import protocolsupport.zplatform.network.NetworkManagerWrapper;
import protocolsupport.zplatform.network.NetworkState;
public class GlowStoneMiscUtils implements PlatformUtils {
public static GlowServer getServer() {
return ((GlowServer) Bukkit.getServer());
}
public static PlayerProfile toGlowStoneGameProfile(GameProfile profile) {
return new PlayerProfile(
profile.getName(), profile.getUUID(),
profile.getProperties().values()
.stream()
.map(property -> new PlayerProperty(property.getName(), property.getValue(), property.getSignature()))
.collect(Collectors.toList())
);
}
public static ProtocolType netStateToProtocol(NetworkState type) {
switch (type) {
case HANDSHAKING: {
return ProtocolType.HANDSHAKE;
}
case PLAY: {
return ProtocolType.PLAY;
}
case LOGIN: {
return ProtocolType.LOGIN;
}
case STATUS: {
return ProtocolType.STATUS;
}
default: {
throw new IllegalArgumentException(MessageFormat.format("Unknown state {0}", type));
}
}
}
public static NetworkState protocolToNetState(ProtocolType type) {
switch (type) {
case HANDSHAKE: {
return NetworkState.HANDSHAKING;
}
case LOGIN: {
return NetworkState.LOGIN;
}
case STATUS: {
return NetworkState.STATUS;
}
case PLAY: {
return NetworkState.PLAY;
}
default: {
throw new IllegalArgumentException(MessageFormat.format("Unknown protocol {0}", type));
}
}
}
@Override
public String localize(String key, Object... args) {
// TODO Auto-generated method stub
return null;
}
@Override
public ItemStack createItemStackFromNBTTag(NBTTagCompoundWrapper tag) {
return NbtSerialization.readItem(((GlowStoneNBTTagCompoundWrapper) tag).unwrap());
}
@Override
public NBTTagCompoundWrapper createNBTTagFromItemStack(ItemStack itemstack) {
return GlowStoneNBTTagCompoundWrapper.wrap(NbtSerialization.writeItem(itemstack, 0));
}
@Override
public String getOutdatedServerMessage() {
return "Outdated server! I\'m running {0}";
}
@Override
public boolean isBungeeEnabled() {
return getServer().getProxySupport();
}
private boolean debug = false;
@Override
public boolean isDebugging() {
return debug == true;
}
@Override
public void enableDebug() {
debug = true;
}
@Override
public void disableDebug() {
debug = false;
}
@Override
public int getCompressionThreshold() {
return getServer().getCompressionThreshold();
}
@Override
public KeyPair getEncryptionKeyPair() {
return getServer().getKeyPair();
}
@Override
public <V> FutureTask<V> callSyncTask(Callable<V> call) {
FutureTask<V> task = new FutureTask<>(call);
Bukkit.getScheduler().scheduleSyncDelayedTask(null, task);
return task;
}
@Override
public String getModName() {
return "GlowStone";
}
@Override
public String getVersionName() {
return GlowServer.GAME_VERSION;
}
private static final Map<String, Statistic> statByName = Arrays.stream(Statistic.values())
.collect(Collectors.toMap(stat -> GlowStatistic.getName(stat), stat -> stat));
private static final Map<String, Achievement> achByName = Arrays.stream(Achievement.values())
.collect(Collectors.toMap(ach -> GlowAchievement.getName(ach), ach -> ach));
@Override
public Statistic getStatisticByName(String value) {
return statByName.get(value);
}
@Override
public String getStatisticName(Statistic stat) {
return GlowStatistic.getName(stat);
}
@Override
public Achievement getAchievmentByName(String value) {
return achByName.get(value);
}
@Override
public String getAchievmentName(Achievement achievement) {
return GlowAchievement.getName(achievement);
}
@Override
public String convertBukkitIconToBase64(CachedServerIcon icon) {
return ((GlowServerIcon) icon).getData();
}
@Override
public NetworkState getNetworkStateFromChannel(Channel channel) {
return GlowStoneNetworkManagerWrapper.getFromChannel(channel).getProtocol();
}
@Override
public NetworkManagerWrapper getNetworkManagerFromChannel(Channel channel) {
return GlowStoneNetworkManagerWrapper.getFromChannel(channel);
}
@Override
public String getReadTimeoutHandlerName() {
return GlowStoneChannelHandlers.READ_TIMEOUT;
}
@Override
public String getSplitterHandlerName() {
return GlowStoneChannelHandlers.FRAMING;
}
@Override
public String getPrependerHandlerName() {
return GlowStoneChannelHandlers.FRAMING;
}
@Override
public void setFraming(ChannelPipeline pipeline, IPacketSplitter splitter, IPacketPrepender prepender) {
((GlowStoneFramingHandler) pipeline.get(GlowStoneChannelHandlers.FRAMING)).setRealFraming(prepender, splitter);
}
}
|
package org.jfree.chart.plot.dial;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Iterator;
import java.util.List;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.event.PlotChangeEvent;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.PlotState;
import org.jfree.data.general.DatasetChangeEvent;
import org.jfree.data.general.ValueDataset;
import org.jfree.util.ObjectList;
import org.jfree.util.ObjectUtilities;
/**
* A dial plot composed of user-definable layers.
*
* @since 1.0.7
*/
public class DialPlot extends Plot implements DialLayerChangeListener {
/**
* The background layer (optional).
*/
private DialLayer background;
/**
* The needle cap (optional).
*/
private DialLayer cap;
/**
* The dial frame.
*/
private DialFrame dialFrame;
/**
* The dataset(s) for the dial plot.
*/
private ObjectList datasets;
/**
* The scale(s) for the dial plot.
*/
private ObjectList scales;
/** Storage for keys that map datasets to scales. */
private ObjectList datasetToScaleMap;
/**
* The drawing layers for the dial plot.
*/
private List layers;
/**
* The pointer(s) for the dial.
*/
private List pointers;
/**
* The x-coordinate for the view window.
*/
private double viewX;
/**
* The y-coordinate for the view window.
*/
private double viewY;
/**
* The width of the view window, expressed as a percentage.
*/
private double viewW;
/**
* The height of the view window, expressed as a percentage.
*/
private double viewH;
/**
* Creates a new instance of <code>DialPlot</code>.
*/
public DialPlot() {
this(null);
}
/**
* Creates a new instance of <code>DialPlot</code>.
*
* @param dataset the dataset (<code>null</code> permitted).
*/
public DialPlot(ValueDataset dataset) {
this.background = null;
this.cap = null;
this.dialFrame = new ArcDialFrame();
this.datasets = new ObjectList();
if (dataset != null) {
this.setDataset(dataset);
}
this.scales = new ObjectList();
this.datasetToScaleMap = new ObjectList();
this.layers = new java.util.ArrayList();
this.pointers = new java.util.ArrayList();
this.viewX = 0.0;
this.viewY = 0.0;
this.viewW = 1.0;
this.viewH = 1.0;
}
/**
* Returns the background.
*
* @return The background (possibly <code>null</code>).
*
* @see #setBackground(DialLayer)
*/
public DialLayer getBackground() {
return this.background;
}
/**
* Sets the background layer and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param background the background layer (<code>null</code> permitted).
*
* @see #getBackground()
*/
public void setBackground(DialLayer background) {
if (this.background != null) {
this.background.removeChangeListener(this);
}
this.background = background;
if (background != null) {
background.addChangeListener(this);
}
fireChangeEvent();
}
/**
* Returns the cap.
*
* @return The cap (possibly <code>null</code>).
*
* @see #setCap(DialLayer)
*/
public DialLayer getCap() {
return this.cap;
}
/**
* Sets the cap and sends a {@link PlotChangeEvent} to all registered
* listeners.
*
* @param cap the cap (<code>null</code> permitted).
*
* @see #getCap()
*/
public void setCap(DialLayer cap) {
if (this.cap != null) {
this.cap.removeChangeListener(this);
}
this.cap = cap;
if (cap != null) {
cap.addChangeListener(this);
}
fireChangeEvent();
}
/**
* Returns the dial's frame.
*
* @return The dial's frame (never <code>null</code>).
*
* @see #setDialFrame(DialFrame)
*/
public DialFrame getDialFrame() {
return this.dialFrame;
}
/**
* Sets the dial's frame and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param frame the frame (<code>null</code> not permitted).
*
* @see #getDialFrame()
*/
public void setDialFrame(DialFrame frame) {
if (frame == null) {
throw new IllegalArgumentException("Null 'frame' argument.");
}
this.dialFrame.removeChangeListener(this);
this.dialFrame = frame;
frame.addChangeListener(this);
fireChangeEvent();
}
/**
* Returns the x-coordinate of the viewing rectangle. This is specified
* in the range 0.0 to 1.0, relative to the dial's framing rectangle.
*
* @return The x-coordinate of the viewing rectangle.
*
* @see #setView(double, double, double, double)
*/
public double getViewX() {
return this.viewX;
}
/**
* Returns the y-coordinate of the viewing rectangle. This is specified
* in the range 0.0 to 1.0, relative to the dial's framing rectangle.
*
* @return The y-coordinate of the viewing rectangle.
*
* @see #setView(double, double, double, double)
*/
public double getViewY() {
return this.viewY;
}
/**
* Returns the width of the viewing rectangle. This is specified
* in the range 0.0 to 1.0, relative to the dial's framing rectangle.
*
* @return The width of the viewing rectangle.
*
* @see #setView(double, double, double, double)
*/
public double getViewWidth() {
return this.viewW;
}
/**
* Returns the height of the viewing rectangle. This is specified
* in the range 0.0 to 1.0, relative to the dial's framing rectangle.
*
* @return The height of the viewing rectangle.
*
* @see #setView(double, double, double, double)
*/
public double getViewHeight() {
return this.viewH;
}
/**
* Sets the viewing rectangle, relative to the dial's framing rectangle,
* and sends a {@link PlotChangeEvent} to all registered listeners.
*
* @param x the x-coordinate (in the range 0.0 to 1.0).
* @param y the y-coordinate (in the range 0.0 to 1.0).
* @param w the width (in the range 0.0 to 1.0).
* @param h the height (in the range 0.0 to 1.0).
*
* @see #getViewX()
* @see #getViewY()
* @see #getViewWidth()
* @see #getViewHeight()
*/
public void setView(double x, double y, double w, double h) {
this.viewX = x;
this.viewY = y;
this.viewW = w;
this.viewH = h;
fireChangeEvent();
}
/**
* Adds a layer to the plot and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param layer the layer (<code>null</code> not permitted).
*/
public void addLayer(DialLayer layer) {
if (layer == null) {
throw new IllegalArgumentException("Null 'layer' argument.");
}
this.layers.add(layer);
layer.addChangeListener(this);
fireChangeEvent();
}
/**
* Returns the index for the specified layer.
*
* @param layer the layer (<code>null</code> not permitted).
*
* @return The layer index.
*/
public int getLayerIndex(DialLayer layer) {
if (layer == null) {
throw new IllegalArgumentException("Null 'layer' argument.");
}
return this.layers.indexOf(layer);
}
/**
* Removes the layer at the specified index and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param index the index.
*/
public void removeLayer(int index) {
DialLayer layer = (DialLayer) this.layers.get(index);
if (layer != null) {
layer.removeChangeListener(this);
}
this.layers.remove(index);
fireChangeEvent();
}
/**
* Removes the specified layer and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param layer the layer (<code>null</code> not permitted).
*/
public void removeLayer(DialLayer layer) {
// defer argument checking
removeLayer(getLayerIndex(layer));
}
/**
* Adds a pointer to the plot and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param pointer the pointer (<code>null</code> not permitted).
*/
public void addPointer(DialPointer pointer) {
if (pointer == null) {
throw new IllegalArgumentException("Null 'pointer' argument.");
}
this.pointers.add(pointer);
pointer.addChangeListener(this);
fireChangeEvent();
}
/**
* Returns the index for the specified pointer.
*
* @param pointer the pointer (<code>null</code> not permitted).
*
* @return The pointer index.
*/
public int getPointerIndex(DialPointer pointer) {
if (pointer == null) {
throw new IllegalArgumentException("Null 'pointer' argument.");
}
return this.pointers.indexOf(pointer);
}
/**
* Removes the pointer at the specified index and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param index the index.
*/
public void removePointer(int index) {
DialPointer pointer = (DialPointer) this.pointers.get(index);
if (pointer != null) {
pointer.removeChangeListener(this);
}
this.pointers.remove(index);
fireChangeEvent();
}
/**
* Removes the specified pointer and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param pointer the pointer (<code>null</code> not permitted).
*/
public void removePointer(DialPointer pointer) {
// defer argument checking
removeLayer(getPointerIndex(pointer));
}
/**
* Returns the dial pointer that is associated with the specified
* dataset, or <code>null</code>.
*
* @param datasetIndex the dataset index.
*
* @return The pointer.
*/
public DialPointer getPointerForDataset(int datasetIndex) {
DialPointer result = null;
Iterator iterator = this.pointers.iterator();
while (iterator.hasNext()) {
DialPointer p = (DialPointer) iterator.next();
if (p.getDatasetIndex() == datasetIndex) {
return p;
}
}
return result;
}
/**
* Returns the primary dataset for the plot.
*
* @return The primary dataset (possibly <code>null</code>).
*/
public ValueDataset getDataset() {
return getDataset(0);
}
/**
* Returns the dataset at the given index.
*
* @param index the dataset index.
*
* @return The dataset (possibly <code>null</code>).
*/
public ValueDataset getDataset(int index) {
ValueDataset result = null;
if (this.datasets.size() > index) {
result = (ValueDataset) this.datasets.get(index);
}
return result;
}
/**
* Sets the dataset for the plot, replacing the existing dataset, if there
* is one, and sends a {@link PlotChangeEvent} to all registered
* listeners.
*
* @param dataset the dataset (<code>null</code> permitted).
*/
public void setDataset(ValueDataset dataset) {
setDataset(0, dataset);
}
/**
* Sets a dataset for the plot.
*
* @param index the dataset index.
* @param dataset the dataset (<code>null</code> permitted).
*/
public void setDataset(int index, ValueDataset dataset) {
ValueDataset existing = (ValueDataset) this.datasets.get(index);
if (existing != null) {
existing.removeChangeListener(this);
}
this.datasets.set(index, dataset);
if (dataset != null) {
dataset.addChangeListener(this);
}
// send a dataset change event to self...
DatasetChangeEvent event = new DatasetChangeEvent(this, dataset);
datasetChanged(event);
}
/**
* Returns the number of datasets.
*
* @return The number of datasets.
*/
public int getDatasetCount() {
return this.datasets.size();
}
/**
* Draws the plot. This method is usually called by the {@link JFreeChart}
* instance that manages the plot.
*
* @param g2 the graphics target.
* @param area the area in which the plot should be drawn.
* @param anchor the anchor point (typically the last point that the
* mouse clicked on, <code>null</code> is permitted).
* @param parentState the state for the parent plot (if any).
* @param info used to collect plot rendering info (<code>null</code>
* permitted).
*/
public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor,
PlotState parentState, PlotRenderingInfo info) {
Shape origClip = g2.getClip();
g2.setClip(area);
// first, expand the viewing area into a drawing frame
Rectangle2D frame = viewToFrame(area);
// draw the background if there is one...
if (this.background != null && this.background.isVisible()) {
if (this.background.isClippedToWindow()) {
Shape savedClip = g2.getClip();
g2.clip(this.dialFrame.getWindow(frame));
this.background.draw(g2, this, frame, area);
g2.setClip(savedClip);
}
else {
this.background.draw(g2, this, frame, area);
}
}
Iterator iterator = this.layers.iterator();
while (iterator.hasNext()) {
DialLayer current = (DialLayer) iterator.next();
if (current.isVisible()) {
if (current.isClippedToWindow()) {
Shape savedClip = g2.getClip();
g2.clip(this.dialFrame.getWindow(frame));
current.draw(g2, this, frame, area);
g2.setClip(savedClip);
}
else {
current.draw(g2, this, frame, area);
}
}
}
// draw the pointers
iterator = this.pointers.iterator();
while (iterator.hasNext()) {
DialPointer current = (DialPointer) iterator.next();
if (current.isVisible()) {
if (current.isClippedToWindow()) {
Shape savedClip = g2.getClip();
g2.clip(this.dialFrame.getWindow(frame));
current.draw(g2, this, frame, area);
g2.setClip(savedClip);
}
else {
current.draw(g2, this, frame, area);
}
}
}
// draw the cap if there is one...
if (this.cap != null && this.cap.isVisible()) {
if (this.cap.isClippedToWindow()) {
Shape savedClip = g2.getClip();
g2.clip(this.dialFrame.getWindow(frame));
this.cap.draw(g2, this, frame, area);
g2.setClip(savedClip);
}
else {
this.cap.draw(g2, this, frame, area);
}
}
if (this.dialFrame.isVisible()) {
this.dialFrame.draw(g2, this, frame, area);
}
g2.setClip(origClip);
}
/**
* Returns the frame surrounding the specified view rectangle.
*
* @param view the view rectangle (<code>null</code> not permitted).
*
* @return The frame rectangle.
*/
private Rectangle2D viewToFrame(Rectangle2D view) {
double width = view.getWidth() / this.viewW;
double height = view.getHeight() / this.viewH;
double x = view.getX() - (width * this.viewX);
double y = view.getY() - (height * this.viewY);
return new Rectangle2D.Double(x, y, width, height);
}
/**
* Returns the value from the specified dataset.
*
* @param datasetIndex the dataset index.
*
* @return The data value.
*/
public double getValue(int datasetIndex) {
double result = Double.NaN;
ValueDataset dataset = getDataset(datasetIndex);
if (dataset != null) {
Number n = dataset.getValue();
if (n != null) {
result = n.doubleValue();
}
}
return result;
}
/**
* Adds a dial scale to the plot and sends a {@link PlotChangeEvent} to
* all registered listeners.
*
* @param index the scale index.
* @param scale the scale (<code>null</code> not permitted).
*/
public void addScale(int index, DialScale scale) {
if (scale == null) {
throw new IllegalArgumentException("Null 'scale' argument.");
}
DialScale existing = (DialScale) this.scales.get(index);
if (existing != null) {
removeLayer(existing);
}
this.layers.add(scale);
this.scales.set(index, scale);
scale.addChangeListener(this);
fireChangeEvent();
}
/**
* Returns the scale at the given index.
*
* @param index the scale index.
*
* @return The scale (possibly <code>null</code>).
*/
public DialScale getScale(int index) {
DialScale result = null;
if (this.scales.size() > index) {
result = (DialScale) this.scales.get(index);
}
return result;
}
/**
* Maps a dataset to a particular scale.
*
* @param index the dataset index (zero-based).
* @param scaleIndex the scale index (zero-based).
*/
public void mapDatasetToScale(int index, int scaleIndex) {
this.datasetToScaleMap.set(index, new Integer(scaleIndex));
fireChangeEvent();
}
/**
* Returns the dial scale for a specific dataset.
*
* @param datasetIndex the dataset index.
*
* @return The dial scale.
*/
public DialScale getScaleForDataset(int datasetIndex) {
DialScale result = (DialScale) this.scales.get(0);
Integer scaleIndex = (Integer) this.datasetToScaleMap.get(datasetIndex);
if (scaleIndex != null) {
result = getScale(scaleIndex.intValue());
}
return result;
}
/**
* A utility method that computes a rectangle using relative radius values.
*
* @param rect the reference rectangle (<code>null</code> not permitted).
* @param radiusW the width radius (must be > 0.0)
* @param radiusH the height radius.
*
* @return A new rectangle.
*/
public static Rectangle2D rectangleByRadius(Rectangle2D rect,
double radiusW, double radiusH) {
if (rect == null) {
throw new IllegalArgumentException("Null 'rect' argument.");
}
double x = rect.getCenterX();
double y = rect.getCenterY();
double w = rect.getWidth() * radiusW;
double h = rect.getHeight() * radiusH;
return new Rectangle2D.Double(x - w / 2.0, y - h / 2.0, w, h);
}
/**
* Receives notification when a layer has changed, and responds by
* forwarding a {@link PlotChangeEvent} to all registered listeners.
*
* @param event the event.
*/
public void dialLayerChanged(DialLayerChangeEvent event) {
fireChangeEvent();
}
/**
* Tests this <code>DialPlot</code> instance for equality with an
* arbitrary object. The plot's dataset(s) is (are) not included in
* the test.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof DialPlot)) {
return false;
}
DialPlot that = (DialPlot) obj;
if (!ObjectUtilities.equal(this.background, that.background)) {
return false;
}
if (!ObjectUtilities.equal(this.cap, that.cap)) {
return false;
}
if (!this.dialFrame.equals(that.dialFrame)) {
return false;
}
if (this.viewX != that.viewX) {
return false;
}
if (this.viewY != that.viewY) {
return false;
}
if (this.viewW != that.viewW) {
return false;
}
if (this.viewH != that.viewH) {
return false;
}
if (!this.layers.equals(that.layers)) {
return false;
}
if (!this.pointers.equals(that.pointers)) {
return false;
}
return super.equals(obj);
}
/**
* Returns a hash code for this instance.
*
* @return The hash code.
*/
public int hashCode() {
int result = 193;
result = 37 * result + ObjectUtilities.hashCode(this.background);
result = 37 * result + ObjectUtilities.hashCode(this.cap);
result = 37 * result + this.dialFrame.hashCode();
long temp = Double.doubleToLongBits(this.viewX);
result = 37 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(this.viewY);
result = 37 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(this.viewW);
result = 37 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(this.viewH);
result = 37 * result + (int) (temp ^ (temp >>> 32));
return result;
}
/**
* Returns the plot type.
*
* @return <code>"DialPlot"</code>
*/
public String getPlotType() {
return "DialPlot";
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
}
/**
* Provides serialization support.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
}
}
|
package com.dumontierlab.pdb2rdf.parser;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import com.dumontierlab.pdb2rdf.model.PdbRdfModel;
import com.dumontierlab.pdb2rdf.parser.vocabulary.PdbOwlVocabulary;
import com.dumontierlab.pdb2rdf.parser.vocabulary.PdbXmlVocabulary;
import com.dumontierlab.pdb2rdf.parser.vocabulary.uri.UriBuilder;
import com.dumontierlab.pdb2rdf.parser.vocabulary.uri.UriPattern;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.XSD;
import com.hp.hpl.jena.rdf.model.Statement;
/**
* @author Alexander De Leon
* @author Jose Cruz-Toledo
*/
public class ContentHandlerState implements ContentHandler {
private ContentHandlerState state;
private final PdbRdfModel rdfModel;
private final UriBuilder uriBuilder;
protected StringBuilder buffer;
private DetailLevel detailLevel = DetailLevel.DEFAULT;
public ContentHandlerState(PdbRdfModel rdfModel, UriBuilder uriBuilder) {
this.uriBuilder = uriBuilder;
this.rdfModel = rdfModel;
}
public void characters(char[] ch, int start, int length) throws SAXException {
if (isBuffering()) {
buffer.append(ch, start, length);
}
if (state != null) {
state.characters(ch, start, length);
}
}
public void endDocument() throws SAXException {
if (state != null) {
state.endDocument();
}
}
public void endElement(String uri, String localName, String name) throws SAXException {
if (state != null) {
state.endElement(uri, localName, name);
}
}
public void endPrefixMapping(String prefix) throws SAXException {
if (state != null) {
state.endPrefixMapping(prefix);
}
}
public void error(SAXParseException e) throws SAXException {
if (state != null) {
state.error(e);
}
}
public void fatalError(SAXParseException e) throws SAXException {
if (state != null) {
state.fatalError(e);
}
}
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
if (state != null) {
state.ignorableWhitespace(ch, start, length);
}
}
public void notationDecl(String name, String publicId, String systemId) throws SAXException {
if (state != null) {
state.notationDecl(name, publicId, systemId);
}
}
public void processingInstruction(String target, String data) throws SAXException {
if (state != null) {
state.processingInstruction(target, data);
}
}
public InputSource resolveEntity(String publicId, String systemId) throws IOException, SAXException {
if (state != null) {
return state.resolveEntity(publicId, systemId);
}
return null;
}
public void setDocumentLocator(Locator locator) {
if (state != null) {
state.setDocumentLocator(locator);
}
}
public void skippedEntity(String name) throws SAXException {
if (state != null) {
state.skippedEntity(name);
}
}
public void startDocument() throws SAXException {
if (state != null) {
state.startDocument();
}
}
public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
if (state != null) {
state.startElement(uri, localName, name, attributes);
}
}
public void startPrefixMapping(String prefix, String uri) throws SAXException {
if (state != null) {
state.startPrefixMapping(prefix, uri);
}
}
public void unparsedEntityDecl(String name, String publicId, String systemId, String notationName)
throws SAXException {
if (state != null) {
state.unparsedEntityDecl(name, publicId, systemId, notationName);
}
}
public void warning(SAXParseException e) throws SAXException {
if (state != null) {
state.warning(e);
}
}
public void setDetailLevel(DetailLevel detailLevel) {
this.detailLevel = detailLevel;
}
public DetailLevel getDetailLevel() {
return detailLevel;
}
protected void setState(ContentHandlerState state) {
if (state != null) {
state.setDetailLevel(getDetailLevel());
}
this.state = state;
}
protected PdbRdfModel getRdfModel() {
return rdfModel;
}
protected UriBuilder getUriBuilder() {
return uriBuilder;
}
protected void startBuffering() {
buffer = new StringBuilder();
}
protected void stopBuffering() {
buffer = null;
}
protected boolean isBuffering() {
return buffer != null;
}
protected boolean isNil(Attributes attributes) {
return attributes.getValue(PdbXmlVocabulary.NIL_ATT) != null;
}
protected Resource createResource(UriPattern pattern, String... params) {
Resource rm = getRdfModel().createResource(getUriBuilder().buildUri(pattern, params));
Statement x = getRdfModel().createStatement(rm, RDF.type, PdbOwlVocabulary.Class.Resource.resource());
getRdfModel().add(x);
return rm;
}
protected String getBufferContent() {
if (!isBuffering()) {
return null;
}
return buffer.toString();
}
protected void clear() {
for (Field field : this.getClass().getDeclaredFields()) {
try {
if (Modifier.isFinal(field.getModifiers())) {
continue;
}
if (!Modifier.isPublic(field.getModifiers())) {
field.setAccessible(true);
resetField(field);
field.setAccessible(false);
} else {
resetField(field);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
protected RDFNode createLiteral(String value, String xsdType) {
return getRdfModel().createTypedLiteral(value, xsdType);
}
protected RDFNode createDecimalLiteral(String value) {
return createLiteral(value, XSD.decimal.getURI());
}
private void resetField(Field field) throws IllegalArgumentException, IllegalAccessException {
if (field.getType() == boolean.class) {
field.set(this, false);
} else if (!field.getType().isPrimitive()) {
field.set(this, null);
} else {
field.set(this, 0);
}
}
}
|
package com.wirelust.personalapi.api.v1.resources;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.transaction.Transactional;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import com.wirelust.personalapi.api.v1.representations.AccountType;
import com.wirelust.personalapi.api.v1.representations.AuthType;
import com.wirelust.personalapi.api.v1.representations.EnumErrorCode;
import com.wirelust.personalapi.data.model.Account;
import com.wirelust.personalapi.data.model.ApiApplication;
import com.wirelust.personalapi.data.model.Authorization;
import com.wirelust.personalapi.api.exceptions.ApplicationException;
import com.wirelust.personalapi.data.model.RestrictedUsername;
import com.wirelust.personalapi.helpers.AccountHelper;
import com.wirelust.personalapi.services.AccountService;
import com.wirelust.personalapi.services.AuthorizationService;
import com.wirelust.personalapi.services.Configuration;
import com.wirelust.personalapi.util.StringUtils;
import org.hibernate.validator.constraints.Email;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Path("/accounts")
@Named
public class AccountResource {
/* PASSWORD_BYPASS_STRING is used in the case that we need to call register service without passing in a valid password.
It will get past validation but not set the password to the user's account.
This is a UX edge case because of how we are implementing various oAuth providers.
*/
public static final String PASSWORD_BYPASS_STRING = "8fkjd6jXG392knd927ur98oijljKHjhjj66kjhkSDSWEXF";
private static final Logger LOGGER = LoggerFactory.getLogger(AccountResource.class);
@Inject
transient EntityManager em;
@Inject
Configuration configuration;
@Inject
AccountService accountService;
@Inject
AuthorizationService authorizationService;
/**
* [ restricted, working ]
* <p/>
* Registers a new account with the site.
*
* @param inAccessCode restricted API access code
* @param inClientId application id
* @param inUsername the requested username
* @param inEmail the user's email address.
* @param inPassword a password that conforms to the password policy
* @param inFullName the user's full name, or what ever they want displayed as their full name
* @return AuthType
*/
@Path("/register")
@POST
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Transactional
public AuthType register(
@NotNull
@FormParam("accessCode")
final String inAccessCode,
@NotNull
@FormParam("client_id")
final String inClientId,
@NotNull
@Size(min = 3, max = 20)
@Pattern(regexp = "^[A-Za-z0-9_]+$")
@FormParam("username")
final String inUsername,
@NotNull
@Email
@FormParam("email")
final String inEmail,
@NotNull
@Size(min = 5, max = 20)
@Pattern(regexp = "^[A-Za-z0-9_\\!\\@\\
@FormParam("password")
final String inPassword,
@NotNull
@Size(min = 5)
@FormParam("fullName")
final String inFullName,
@FormParam("inviteCode")
final String inInviteCode
) {
LOGGER.debug("register()");
String testingAccessCode = configuration.getSetting("accesscode.testing", "");
// TODO: re-implement access codes
//if (!testingAccessCode.equals(inAccessCode)
// && !sessionService.getAccessCode().equals(inAccessCode)) {
// throw new ApplicationException(EnumErrorCode.ACCESS_CODE_INVALID);
ApiApplication apiApplication = em.find(ApiApplication.class, inClientId);
if (apiApplication == null) {
throw new ApplicationException(EnumErrorCode.CLIENT_ID_INVALID);
}
// don't allow all numeric usernames
if (inUsername.matches("^[0-9]+$")) {
throw new ApplicationException(EnumErrorCode.USERNAME_INVALID);
}
// Make sure the username isn't taken
String usernameNormalized = StringUtils.normalizeUsername(inUsername);
TypedQuery<Account> usernameCheckQuery = em.createNamedQuery(Account.QUERY_BY_USERNAME_NORMALIZED, Account.class);
usernameCheckQuery.setParameter("username", usernameNormalized);
List<Account> usernameCheckResults = usernameCheckQuery.getResultList();
if (usernameCheckResults != null && usernameCheckResults.size() > 0) {
throw new ApplicationException(EnumErrorCode.USERNAME_EXISTS);
}
// Make sure the username isn't restricted
TypedQuery<RestrictedUsername> restrictedCheckQuery = em.createNamedQuery(RestrictedUsername.QUERY_BY_USERNAME_NORMALIZED, RestrictedUsername.class);
restrictedCheckQuery.setParameter("username", usernameNormalized);
List<RestrictedUsername> restrictedCheckResults = restrictedCheckQuery.getResultList();
if (restrictedCheckResults != null && restrictedCheckResults.size() > 0) {
throw new ApplicationException(EnumErrorCode.USERNAME_EXISTS, "username exists", null);
}
// Check for an account by email address to make sure it doesn't already exist
TypedQuery<Account> emailQuery = em.createNamedQuery(Account.QUERY_BY_EMAIL, Account.class);
emailQuery.setParameter("email", inUsername);
List<Account> emailResults = emailQuery.getResultList();
if (emailResults != null && emailResults.size() > 0) {
throw new ApplicationException(EnumErrorCode.EMAIL_EXISTS);
}
Account account = new Account();
account.setUsername(inUsername);
account.setUsernameNormalized(usernameNormalized);
account.setEmail(inEmail);
account.setFullName(inFullName);
if (!inPassword.equals(AccountResource.PASSWORD_BYPASS_STRING)) {
accountService.setPassword(account, inPassword);
}
// save the account
em.persist(account);
// create a new login session for this app/user
Authorization authorization = authorizationService.getNewSession(null, account);
AuthType authType = new AuthType();
authType.setToken(authorization.getToken());
authType.setCreated(authorization.getDateCreated());
authType.setAccount(AccountHelper.toRepresentation(account, true));
return authType;
}
/**
* [ working ] Checks to see if a username currently exists or not.
* Returns 204 on success, error if account exists.
*
* @param inUsername username
*/
@Path("/checkUsername")
@POST
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public void checkUsername(
@NotNull
@Size(min = 3, max = 20)
@Pattern(regexp = "^[A-Za-z0-9_]+$")
@FormParam("username")
final String inUsername) {
// Normalize the username
String usernameNormalized = StringUtils.normalizeUsername(inUsername);
TypedQuery<Account> usernameCheckQuery = em.createNamedQuery(Account.QUERY_BY_USERNAME_NORMALIZED, Account.class);
usernameCheckQuery.setParameter("username", usernameNormalized);
List<Account> usernameCheckResults = usernameCheckQuery.getResultList();
if (usernameCheckResults != null && usernameCheckResults.size() > 0) {
throw new ApplicationException(EnumErrorCode.USERNAME_EXISTS, "username exists", null);
}
TypedQuery<RestrictedUsername> restrictedCheckQuery = em.createNamedQuery(RestrictedUsername.QUERY_BY_USERNAME_NORMALIZED, RestrictedUsername.class);
restrictedCheckQuery.setParameter("username", usernameNormalized);
List<RestrictedUsername> restrictedCheckResults = restrictedCheckQuery.getResultList();
if (restrictedCheckResults != null && restrictedCheckResults.size() > 0) {
// we're throwing username_exists because we don't want the end user to know that this username is restricted.
throw new ApplicationException(EnumErrorCode.USERNAME_EXISTS, "username exists", null);
}
// don't allow all numeric usernames
if (inUsername.matches("^[0-9]+$")) {
// TODO: determine if we need to do anything special here for the front end to tell the user the exact problem.
throw new ApplicationException(EnumErrorCode.USERNAME_INVALID);
}
}
/**
* [ restricted ]
*
* @param inAccessCode access code
* @param inClientId application id
* @param inUsername Username or email address of account
* @param inPassword password
* @return AuthType
*/
@Path("/login")
@POST
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public AuthType login(
@NotNull
@FormParam("accessCode")
final String inAccessCode,
@NotNull
@FormParam("client_id")
final String inClientId,
@NotNull
@FormParam("username")
final String inUsername,
@NotNull
@FormParam("password")
final String inPassword) {
return null;
}
/**
* [ working ]
*
* @param inOauthToken OAuth token
*/
@Path("/logout")
@POST
public void logout(
@NotNull
@FormParam("oauth_token")
String inOauthToken) {
}
/**
*
* @param inOauthToken oauth_token
* @param inFullName user's full name
* @param inLocation user's location
* @param inBio user's bio
* @param inEmail email address
* @param inPassword password
* @param inBackground URL of background image for the site (may be removed later)
* @param inTimezone timezone
*/
@Path("/update")
@POST
public void update(
@NotNull
@FormParam("oauth_token")
String inOauthToken,
@NotNull
@FormParam("fullName")
String inFullName,
@FormParam("location")
String inLocation,
@FormParam("bio")
String inBio,
@FormParam("email")
String inEmail,
@Size(min = 5, max = 20)
@Pattern(regexp = "^[A-Za-z0-9_\\!\\@\\
@FormParam("password")
String inPassword,
@FormParam("background")
String inBackground,
@FormParam("timezone")
Integer inTimezone) {
}
/**
* Updates a single attribute of an account
*
* @param inOauthToken oauth_token
* @param inField name of field to be updated
* @param inValue value to be updated
*/
@Path("/updatesingle")
@POST
public void updateSingle(
@NotNull
@FormParam("client_id")
final String inClientId,
@NotNull
@FormParam("oauth_token")
String inOauthToken,
@FormParam("field") String inField,
@FormParam("value") String inValue) {
// TODO: Implement
}
/**
* Gets information about an account. if account specified is same as logged in account, more information will be provided.
* <p/>
* accountId can be either the numberic id or a username. if 'self' is passed as account id it will return data for the user of the oauth_token.
*
* @param inOauthToken oauth_token
* @param inAccountId id of account to get info about
* @return accountType
*/
@Path("/{accountId}")
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public AccountType info(
@NotNull
@QueryParam("oauth_token")
final String inOauthToken,
@NotNull
@PathParam("accountId")
final String inAccountId
) {
Authorization auth = authorizationService.getAuthorization(inOauthToken);
if (auth == null) {
throw new ApplicationException(EnumErrorCode.SESSION_INVALID);
}
Account authAccount = auth.getAccount();
if (authAccount == null) {
// this should never happen
throw new ApplicationException(EnumErrorCode.SESSION_INVALID);
}
Account account;
if ("self".equalsIgnoreCase(inAccountId) || "me".equalsIgnoreCase(inAccountId)) {
account = authAccount;
} else {
account = accountService.find(inAccountId);
if (account == null) {
throw new ApplicationException(EnumErrorCode.ACCOUNT_NOT_FOUND);
}
}
AccountType at = AccountHelper.toRepresentation(account, true);
if (account.getId().equals(authAccount.getId())) {
at.setEmail(account.getEmail());
}
return at;
}
}
|
package sk.henrichg.phoneprofilesplus;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
class ApplicationPreferences {
static SharedPreferences preferences = null;
static final String PREF_APPLICATION_START_ON_BOOT = "applicationStartOnBoot";
private static final String PREF_APPLICATION_ACTIVATE = "applicationActivate";
private static final String PREF_APPLICATION_START_EVENTS = "applicationStartEvents";
static final String PREF_APPLICATION_ALERT = "applicationAlert";
static final String PREF_APPLICATION_CLOSE = "applicationClose";
static final String PREF_APPLICATION_LONG_PRESS_ACTIVATION = "applicationLongClickActivation";
static final String PREF_APPLICATION_LANGUAGE = "applicationLanguage";
static final String PREF_APPLICATION_THEME = "applicationTheme";
static final String PREF_APPLICATION_ACTIVATOR_PREF_INDICATOR = "applicationActivatorPrefIndicator";
static final String PREF_APPLICATION_EDITOR_PREF_INDICATOR = "applicationEditorPrefIndicator";
static final String PREF_APPLICATION_ACTIVATOR_HEADER = "applicationActivatorHeader";
static final String PREF_APPLICATION_EDITOR_HEADER = "applicationEditorHeader";
static final String PREF_NOTIFICATION_TOAST = "notificationsToast";
static final String PREF_NOTIFICATION_STATUS_BAR = "notificationStatusBar";
static final String PREF_NOTIFICATION_STATUS_BAR_STYLE = "notificationStatusBarStyle";
static final String PREF_NOTIFICATION_STATUS_BAR_PERMANENT = "notificationStatusBarPermanent";
private static final String PREF_NOTIFICATION_STATUS_BAR_CANCEL = "notificationStatusBarCancel";
static final String PREF_NOTIFICATION_SHOW_IN_STATUS_BAR = "notificationShowInStatusBar";
static final String PREF_NOTIFICATION_TEXT_COLOR = "notificationTextColor";
static final String PREF_APPLICATION_WIDGET_LIST_PREF_INDICATOR = "applicationWidgetListPrefIndicator";
static final String PREF_APPLICATION_WIDGET_LIST_HEADER = "applicationWidgetListHeader";
static final String PREF_APPLICATION_WIDGET_LIST_BACKGROUND = "applicationWidgetListBackground";
static final String PREF_APPLICATION_WIDGET_LIST_LIGHTNESS_B = "applicationWidgetListLightnessB";
static final String PREF_APPLICATION_WIDGET_LIST_LIGHTNESS_T = "applicationWidgetListLightnessT";
static final String PREF_APPLICATION_WIDGET_ICON_COLOR = "applicationWidgetIconColor";
static final String PREF_APPLICATION_WIDGET_ICON_LIGHTNESS = "applicationWidgetIconLightness";
static final String PREF_APPLICATION_WIDGET_LIST_ICON_COLOR = "applicationWidgetListIconColor";
static final String PREF_APPLICATION_WIDGET_LIST_ICON_LIGHTNESS = "applicationWidgetListIconLightness";
private static final String PREF_APPLICATION_EDITOR_AUTO_CLOSE_DRAWER = "applicationEditorAutoCloseDrawer";
static final String PREF_APPLICATION_EDITOR_SAVE_EDITOR_STATE = "applicationEditorSaveEditorState";
private static final String PREF_NOTIFICATION_PREF_INDICATOR = "notificationPrefIndicator";
static final String PREF_APPLICATION_HOME_LAUNCHER = "applicationHomeLauncher";
static final String PREF_APPLICATION_WIDGET_LAUNCHER = "applicationWidgetLauncher";
static final String PREF_APPLICATION_NOTIFICATION_LAUNCHER = "applicationNotificationLauncher";
static final String PREF_APPLICATION_EVENT_WIFI_SCAN_INTERVAL = "applicationEventWifiScanInterval";
static final String PREF_APPLICATION_EVENT_WIFI_ENABLE_WIFI = "applicationEventWifiEnableWifi";
static final String PREF_APPLICATION_BACKGROUND_PROFILE = "applicationBackgroundProfile";
static final String PREF_APPLICATION_BACKGROUND_PROFILE_NOTIFICATION_SOUND = "applicationBackgroundProfileNotificationSound";
static final String PREF_APPLICATION_BACKGROUND_PROFILE_NOTIFICATION_VIBRATE = "applicationBackgroundProfileNotificationVibrate";
static final String PREF_APPLICATION_ACTIVATOR_GRID_LAYOUT= "applicationActivatorGridLayout";
static final String PREF_APPLICATION_WIDGET_LIST_GRID_LAYOUT= "applicationWidgetListGridLayout";
static final String PREF_APPLICATION_EVENT_BLUETOOTH_SCAN_INTERVAL = "applicationEventBluetoothScanInterval";
static final String PREF_APPLICATION_EVENT_BLUETOOTH_ENABLE_BLUETOOTH = "applicationEventBluetoothEnableBluetooth";
static final String PREF_APPLICATION_EVENT_WIFI_RESCAN = "applicationEventWifiRescan";
static final String PREF_APPLICATION_EVENT_BLUETOOTH_RESCAN = "applicationEventBluetoothRescan";
static final String PREF_APPLICATION_WIDGET_ICON_HIDE_PROFILE_NAME = "applicationWidgetIconHideProfileName";
static final String PREF_APPLICATION_UNLINK_RINGER_NOTIFICATION_VOLUMES = "applicationUnlinkRingerNotificationVolumes";
static final String PREF_APPLICATION_RINGER_NOTIFICATION_VOLUMES_UNLINKED_INFO = "applicationRingerNotificationVolumesUnlinkedInfo";
private static final String PREF_APPLICATION_SHORTCUT_EMBLEM = "applicationShortcutEmblem";
static final String PREF_APPLICATION_EVENT_WIFI_SCAN_IN_POWER_SAVE_MODE = "applicationEventWifiScanInPowerSaveMode";
static final String PREF_APPLICATION_EVENT_BLUETOOTH_SCAN_IN_POWER_SAVE_MODE = "applicationEventBluetoothScanInPowerSaveMode";
static final String PREF_APPLICATION_POWER_SAVE_MODE_INTERNAL = "applicationPowerSaveModeInternal";
static final String PREF_APPLICATION_EVENT_BLUETOOTH_LE_SCAN_DURATION = "applicationEventBluetoothLEScanDuration";
static final String PREF_APPLICATION_EVENT_LOCATION_UPDATE_INTERVAL = "applicationEventLocationUpdateInterval";
static final String PREF_APPLICATION_EVENT_LOCATION_UPDATE_IN_POWER_SAVE_MODE = "applicationEventLocationUpdateInPowerSaveMode";
private static final String PREF_APPLICATION_EVENT_LOCATION_USE_GPS = "applicationEventLocationUseGPS";
static final String PREF_APPLICATION_EVENT_LOCATION_RESCAN = "applicationEventLocationRescan";
static final String PREF_APPLICATION_EVENT_ORIENTATION_SCAN_INTERVAL = "applicationEventOrientationScanInterval";
static final String PREF_APPLICATION_EVENT_ORIENTATION_SCAN_IN_POWER_SAVE_MODE = "applicationEventOrientationScanInPowerSaveMode";
static final String PREF_APPLICATION_EVENT_MOBILE_CELLS_SCAN_IN_POWER_SAVE_MODE = "applicationEventMobileCellScanInPowerSaveMode";
static final String PREF_APPLICATION_EVENT_MOBILE_CELLS_RESCAN = "applicationEventMobileCellsRescan";
static final String PREF_NOTIFICATION_HIDE_IN_LOCKSCREEN = "notificationHideInLockscreen";
static final String PREF_APPLICATION_DELETE_OLD_ACTIVITY_LOGS = "applicationDeleteOldActivityLogs";
static final String PREF_APPLICATION_WIDGET_ICON_BACKGROUND = "applicationWidgetIconBackground";
static final String PREF_APPLICATION_WIDGET_ICON_LIGHTNESS_B = "applicationWidgetIconLightnessB";
static final String PREF_APPLICATION_WIDGET_ICON_LIGHTNESS_T = "applicationWidgetIconLightnessT";
static final String PREF_APPLICATION_EVENT_USE_PRIORITY = "applicationEventUsePriority";
static final String PREF_NOTIFICATION_THEME = "notificationTheme";
static final String PREF_APPLICATION_FORCE_SET_MERGE_RINGER_NOTIFICATION_VOLUMES = "applicationForceSetMergeRingNotificationVolumes";
//private static final String PREF_APPLICATION_SAMSUNG_EDGE_PREF_INDICATOR = "applicationSamsungEdgePrefIndicator";
static final String PREF_APPLICATION_SAMSUNG_EDGE_HEADER = "applicationSamsungEdgeHeader";
static final String PREF_APPLICATION_SAMSUNG_EDGE_BACKGROUND = "applicationSamsungEdgeBackground";
static final String PREF_APPLICATION_SAMSUNG_EDGE_LIGHTNESS_B = "applicationSamsungEdgeLightnessB";
static final String PREF_APPLICATION_SAMSUNG_EDGE_LIGHTNESS_T = "applicationSamsungEdgeLightnessT";
static final String PREF_APPLICATION_SAMSUNG_EDGE_ICON_COLOR = "applicationSamsungEdgeIconColor";
static final String PREF_APPLICATION_SAMSUNG_EDGE_ICON_LIGHTNESS = "applicationSamsungEdgeIconLightness";
//private static final String PREF_APPLICATION_SAMSUNG_EDGE_GRID_LAYOUT= "applicationSamsungEdgeGridLayout";
private static final String PREF_APPLICATION_EVENT_LOCATION_SCAN_ONLY_WHEN_SCREEN_IS_ON = "applicationEventLocationScanOnlyWhenScreenIsOn";
private static final String PREF_APPLICATION_EVENT_WIFI_SCAN_ONLY_WHEN_SCREEN_IS_ON = "applicationEventWifiScanOnlyWhenScreenIsOn";
private static final String PREF_APPLICATION_EVENT_BLUETOOTH_SCAN_ONLY_WHEN_SCREEN_IS_ON = "applicationEventBluetoothScanOnlyWhenScreenIsOn";
private static final String PREF_APPLICATION_EVENT_MOBILE_CELL_SCAN_ONLY_WHEN_SCREEN_IS_ON = "applicationEventMobileCellScanOnlyWhenScreenIsOn";
private static final String PREF_APPLICATION_EVENT_ORIENTATION_SCAN_ONLY_WHEN_SCREEN_IS_ON = "applicationEventOrientationScanOnlyWhenScreenIsOn";
static final String PREF_APPLICATION_RESTART_EVENTS_ALERT = "applicationRestartEventsAlert";
private static final String PREF_APPLICATION_WIDGET_LIST_ROUNDED_CORNERS = "applicationWidgetListRoundedCorners";
private static final String PREF_APPLICATION_WIDGET_ICON_ROUNDED_CORNERS = "applicationWidgetIconRoundedCorners";
static final String PREF_APPLICATION_WIDGET_LIST_BACKGROUND_TYPE = "applicationWidgetListBackgroundType";
static final String PREF_APPLICATION_WIDGET_LIST_BACKGROUND_COLOR = "applicationWidgetListBackgroundColor";
static final String PREF_APPLICATION_WIDGET_ICON_BACKGROUND_TYPE = "applicationWidgetIconBackgroundType";
static final String PREF_APPLICATION_WIDGET_ICON_BACKGROUND_COLOR = "applicationWidgetIconBackgroundColor";
static SharedPreferences getSharedPreferences(Context context) {
if (preferences == null)
preferences = context.getApplicationContext().getSharedPreferences(PPApplication.APPLICATION_PREFS_NAME, Context.MODE_PRIVATE);
return preferences;
}
static boolean applicationStartOnBoot(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_START_ON_BOOT, true);
}
static boolean applicationActivate(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_ACTIVATE, true);
}
static boolean applicationStartEvents(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_START_EVENTS, true);
}
static boolean applicationActivateWithAlert(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_ALERT, true);
}
static boolean applicationClose(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_CLOSE, true);
}
static boolean applicationLongClickActivation(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_LONG_PRESS_ACTIVATION, false);
}
static String applicationLanguage(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_LANGUAGE, "system");
}
static public String applicationTheme(Context context) {
String applicationTheme = getSharedPreferences(context).getString(PREF_APPLICATION_THEME, "material");
if (applicationTheme.equals("light")){
applicationTheme = "material";
SharedPreferences.Editor editor = getSharedPreferences(context).edit();
editor.putString(PREF_APPLICATION_THEME, applicationTheme);
editor.apply();
}
return applicationTheme;
}
static boolean applicationActivatorPrefIndicator(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_ACTIVATOR_PREF_INDICATOR, true);
}
static public boolean applicationEditorPrefIndicator(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_EDITOR_PREF_INDICATOR, true);
}
static boolean applicationActivatorHeader(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_ACTIVATOR_HEADER, true);
}
static boolean applicationEditorHeader(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_EDITOR_HEADER, true);
}
static boolean notificationsToast(Context context) {
return getSharedPreferences(context).getBoolean(PREF_NOTIFICATION_TOAST, true);
}
static boolean notificationStatusBar(Context context) {
return getSharedPreferences(context).getBoolean(PREF_NOTIFICATION_STATUS_BAR, true);
}
static boolean notificationStatusBarPermanent(Context context) {
return getSharedPreferences(context).getBoolean(PREF_NOTIFICATION_STATUS_BAR_PERMANENT, true);
}
static String notificationStatusBarCancel(Context context) {
return getSharedPreferences(context).getString(PREF_NOTIFICATION_STATUS_BAR_CANCEL, "10");
}
static String notificationStatusBarStyle(Context context) {
return getSharedPreferences(context).getString(PREF_NOTIFICATION_STATUS_BAR_STYLE, "1");
}
static boolean notificationShowInStatusBar(Context context) {
return getSharedPreferences(context).getBoolean(PREF_NOTIFICATION_SHOW_IN_STATUS_BAR, true);
}
static String notificationTextColor(Context context) {
return getSharedPreferences(context).getString(PREF_NOTIFICATION_TEXT_COLOR, "0");
}
static boolean notificationHideInLockScreen(Context context) {
return getSharedPreferences(context).getBoolean(PREF_NOTIFICATION_HIDE_IN_LOCKSCREEN, false);
}
static String notificationTheme(Context context) {
return getSharedPreferences(context).getString(PREF_NOTIFICATION_THEME, "0");
}
static boolean applicationWidgetListPrefIndicator(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_WIDGET_LIST_PREF_INDICATOR, true);
}
static boolean applicationWidgetListHeader(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_WIDGET_LIST_HEADER, true);
}
static String applicationWidgetListBackground(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_WIDGET_LIST_BACKGROUND, "25");
}
static String applicationWidgetListLightnessB(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_WIDGET_LIST_LIGHTNESS_B, "0");
}
static String applicationWidgetListLightnessT(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_WIDGET_LIST_LIGHTNESS_T, "100");
}
static String applicationWidgetIconColor(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_WIDGET_ICON_COLOR, "0");
}
static String applicationWidgetIconLightness(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_WIDGET_ICON_LIGHTNESS, "100");
}
static String applicationWidgetListIconColor(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_WIDGET_LIST_ICON_COLOR, "0");
}
static String applicationWidgetListIconLightness(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_WIDGET_LIST_ICON_LIGHTNESS, "100");
}
static boolean applicationEditorAutoCloseDrawer(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_EDITOR_AUTO_CLOSE_DRAWER, true);
}
static boolean applicationEditorSaveEditorState(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_EDITOR_SAVE_EDITOR_STATE, true);
}
static boolean notificationPrefIndicator(Context context) {
return getSharedPreferences(context).getBoolean(PREF_NOTIFICATION_PREF_INDICATOR, true);
}
static String applicationHomeLauncher(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_HOME_LAUNCHER, "activator");
}
static String applicationWidgetLauncher(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_WIDGET_LAUNCHER, "activator");
}
static String applicationNotificationLauncher(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_NOTIFICATION_LAUNCHER, "activator");
}
static int applicationEventWifiScanInterval(Context context) {
return Integer.valueOf(getSharedPreferences(context).getString(PREF_APPLICATION_EVENT_WIFI_SCAN_INTERVAL, "15"));
}
static boolean applicationEventWifiEnableWifi(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_EVENT_WIFI_ENABLE_WIFI, true);
}
static String applicationBackgroundProfile(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_BACKGROUND_PROFILE, "-999");
}
static String applicationBackgroundProfileNotificationSound(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_BACKGROUND_PROFILE_NOTIFICATION_SOUND, "");
}
static boolean applicationBackgroundProfileNotificationVibrate(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_BACKGROUND_PROFILE_NOTIFICATION_VIBRATE, false);
}
static boolean applicationActivatorGridLayout(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_ACTIVATOR_GRID_LAYOUT, true);
}
static boolean applicationWidgetListGridLayout(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_WIDGET_LIST_GRID_LAYOUT, true);
}
static int applicationEventBluetoothScanInterval(Context context) {
return Integer.valueOf(getSharedPreferences(context).getString(PREF_APPLICATION_EVENT_BLUETOOTH_SCAN_INTERVAL, "15"));
}
static boolean applicationEventBluetoothEnableBluetooth(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_EVENT_BLUETOOTH_ENABLE_BLUETOOTH, true);
}
static String applicationEventWifiRescan(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_EVENT_WIFI_RESCAN, "1");
}
static String applicationEventBluetoothRescan(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_EVENT_BLUETOOTH_RESCAN, "1");
}
static boolean applicationWidgetIconHideProfileName(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_WIDGET_ICON_HIDE_PROFILE_NAME, false);
}
static boolean applicationUnlinkRingerNotificationVolumes(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_UNLINK_RINGER_NOTIFICATION_VOLUMES, false);
}
static boolean applicationShortcutEmblem(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_SHORTCUT_EMBLEM, true);
}
static String applicationEventWifiScanInPowerSaveMode(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_EVENT_WIFI_SCAN_IN_POWER_SAVE_MODE, "1");
}
static String applicationEventBluetoothScanInPowerSaveMode(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_EVENT_BLUETOOTH_SCAN_IN_POWER_SAVE_MODE, "1");
}
static String applicationPowerSaveModeInternal(Context context) {
if (Build.VERSION.SDK_INT >= 21)
return getSharedPreferences(context).getString(PREF_APPLICATION_POWER_SAVE_MODE_INTERNAL, "3");
else
return getSharedPreferences(context).getString(PREF_APPLICATION_POWER_SAVE_MODE_INTERNAL, "0");
}
static int applicationEventBluetoothLEScanDuration(Context context) {
return Integer.valueOf(getSharedPreferences(context).getString(PREF_APPLICATION_EVENT_BLUETOOTH_LE_SCAN_DURATION, "10"));
}
static int applicationEventLocationUpdateInterval(Context context) {
return Integer.valueOf(getSharedPreferences(context).getString(PREF_APPLICATION_EVENT_LOCATION_UPDATE_INTERVAL, "15"));
}
static String applicationEventLocationUpdateInPowerSaveMode(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_EVENT_LOCATION_UPDATE_IN_POWER_SAVE_MODE, "1");
}
static boolean applicationEventLocationUseGPS(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_EVENT_LOCATION_USE_GPS, false);
}
static String applicationEventLocationRescan(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_EVENT_LOCATION_RESCAN, "1");
}
static int applicationEventOrientationScanInterval(Context context) {
return Integer.valueOf(getSharedPreferences(context).getString(PREF_APPLICATION_EVENT_ORIENTATION_SCAN_INTERVAL, "10"));
}
static String applicationEventOrientationScanInPowerSaveMode(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_EVENT_ORIENTATION_SCAN_IN_POWER_SAVE_MODE, "1");
}
static String applicationEventMobileCellsScanInPowerSaveMode(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_EVENT_MOBILE_CELLS_SCAN_IN_POWER_SAVE_MODE, "1");
}
static String applicationEventMobileCellsRescan(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_EVENT_MOBILE_CELLS_RESCAN, "1");
}
static int applicationDeleteOldActivityLogs(Context context) {
return Integer.valueOf(getSharedPreferences(context).getString(PREF_APPLICATION_DELETE_OLD_ACTIVITY_LOGS, "7"));
}
static String applicationWidgetIconBackground(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_WIDGET_ICON_BACKGROUND, "0");
}
static String applicationWidgetIconLightnessB(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_WIDGET_ICON_LIGHTNESS_B, "0");
}
static String applicationWidgetIconLightnessT(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_WIDGET_ICON_LIGHTNESS_T, "100");
}
static boolean applicationEventUsePriority(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_EVENT_USE_PRIORITY, false);
}
static int applicationForceSetMergeRingNotificationVolumes(Context context) {
return Integer.valueOf(getSharedPreferences(context).getString(PREF_APPLICATION_FORCE_SET_MERGE_RINGER_NOTIFICATION_VOLUMES, "0"));
}
/*
static boolean applicationSamsungEdgePrefIndicator(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_SAMSUNG_EDGE_PREF_INDICATOR, false);
}
*/
static boolean applicationSamsungEdgeHeader(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_SAMSUNG_EDGE_HEADER, true);
}
static String applicationSamsungEdgeBackground(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_SAMSUNG_EDGE_BACKGROUND, "25");
}
static String applicationSamsungEdgeLightnessB(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_SAMSUNG_EDGE_LIGHTNESS_B, "0");
}
static String applicationSamsungEdgeLightnessT(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_SAMSUNG_EDGE_LIGHTNESS_T, "100");
}
static String applicationSamsungEdgeIconColor(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_SAMSUNG_EDGE_ICON_COLOR, "0");
}
static String applicationSamsungEdgeIconLightness(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_SAMSUNG_EDGE_ICON_LIGHTNESS, "100");
}
/*
static boolean applicationSamsungEdgeGridLayout(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_SAMSUNG_EDGE_GRID_LAYOUT, true);
}
*/
static boolean applicationEventLocationScanOnlyWhenScreenIsOn(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_EVENT_LOCATION_SCAN_ONLY_WHEN_SCREEN_IS_ON, false);
}
static boolean applicationEventWifiScanOnlyWhenScreenIsOn(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_EVENT_WIFI_SCAN_ONLY_WHEN_SCREEN_IS_ON, false);
}
static boolean applicationEventBluetoothScanOnlyWhenScreenIsOn(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_EVENT_BLUETOOTH_SCAN_ONLY_WHEN_SCREEN_IS_ON, false);
}
static boolean applicationEventMobileCellScanOnlyWhenScreenIsOn(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_EVENT_MOBILE_CELL_SCAN_ONLY_WHEN_SCREEN_IS_ON, false);
}
static boolean applicationEventOrientationScanOnlyWhenScreenIsOn(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_EVENT_ORIENTATION_SCAN_ONLY_WHEN_SCREEN_IS_ON, true);
}
static boolean applicationRestartEventsWithAlert(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_RESTART_EVENTS_ALERT, true);
}
static boolean applicationWidgetListRoundedCorners(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_WIDGET_LIST_ROUNDED_CORNERS, true);
}
static boolean applicationWidgetIconRoundedCorners(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_WIDGET_ICON_ROUNDED_CORNERS, true);
}
static boolean applicationWidgetListBackgroundType(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_WIDGET_LIST_BACKGROUND_TYPE, false);
}
static String applicationWidgetListBackgroundColor(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_WIDGET_LIST_BACKGROUND_COLOR, "-1"); // white color
}
static boolean applicationWidgetIconBackgroundType(Context context) {
return getSharedPreferences(context).getBoolean(PREF_APPLICATION_WIDGET_ICON_BACKGROUND_TYPE, false);
}
static String applicationWidgetIconBackgroundColor(Context context) {
return getSharedPreferences(context).getString(PREF_APPLICATION_WIDGET_ICON_BACKGROUND_COLOR, "-1"); // white color
}
}
|
package ua.com.fielden.platform.test;
import static java.lang.String.format;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import ua.com.fielden.platform.dao.IEntityDao;
import ua.com.fielden.platform.dao.PersistedEntityMetadata;
import ua.com.fielden.platform.data.IDomainDrivenData;
import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.entity.DynamicEntityKey;
import ua.com.fielden.platform.entity.factory.EntityFactory;
import ua.com.fielden.platform.entity.factory.ICompanionObjectFinder;
/**
* This is a base class for all test cases in TG based applications. Each application module should provide file <b>src/test/resources/test.properties</b> with property
* <code>config-domain</code> assigned an application specific class implementing contract {@link IDomainDrivenTestCaseConfiguration}.
*
* @author TG Team
*
*/
public abstract class AbstractDomainDrivenTestCase implements IDomainDrivenData {
transient private final Logger logger = Logger.getLogger(this.getClass());
private static final List<String> dataScript = new ArrayList<String>();
private static final List<String> truncateScript = new ArrayList<String>();
public final static IDomainDrivenTestCaseConfiguration config = createConfig();
private final ICompanionObjectFinder provider = config.getInstance(ICompanionObjectFinder.class);
private final EntityFactory factory = config.getEntityFactory();
private final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
private final Collection<PersistedEntityMetadata> entityMetadatas = config.getDomainMetadata().getPersistedEntityMetadatas();
private static boolean domainPopulated = false;
private static IDomainDrivenTestCaseConfiguration createConfig() {
final long startTime = System.currentTimeMillis();
System.out.println(format("Started createConfig() at %s...", new DateTime(startTime)));
try {
final Properties testProps = new Properties();
final FileInputStream in = new FileInputStream("src/test/resources/test.properties");
testProps.load(in);
in.close();
// TODO Due to incorrect generation of constraints by Hibernate, at this stage simply disable REFERENTIAL_INTEGRITY by rewriting URL
IDomainDrivenTestCaseConfiguration.hbc.setProperty("hibernate.connection.url", "jdbc:h2:./src/test/resources/db/test_domain_db;INIT=SET REFERENTIAL_INTEGRITY FALSE");
IDomainDrivenTestCaseConfiguration.hbc.setProperty("hibernate.connection.driver_class", "org.h2.Driver");
IDomainDrivenTestCaseConfiguration.hbc.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
IDomainDrivenTestCaseConfiguration.hbc.setProperty("hibernate.connection.username", "sa");
IDomainDrivenTestCaseConfiguration.hbc.setProperty("hibernate.connection.password", "");
IDomainDrivenTestCaseConfiguration.hbc.setProperty("hibernate.show_sql", "false");
IDomainDrivenTestCaseConfiguration.hbc.setProperty("hibernate.format_sql", "true");
IDomainDrivenTestCaseConfiguration.hbc.setProperty("hibernate.hbm2ddl.auto", "create");
final String configClassName = testProps.getProperty("config-domain");
final Class<IDomainDrivenTestCaseConfiguration> type = (Class<IDomainDrivenTestCaseConfiguration>) Class.forName(configClassName);
final long mach1Time = System.currentTimeMillis();
System.out.println(format("\tbefore instantiating %s ... %s", type.getName(), new Duration(startTime, mach1Time).getStandardSeconds()));
return type.newInstance();
} catch (final Exception e) {
throw new IllegalStateException(e);
} finally {
final long finishTime = System.currentTimeMillis();
System.out.println(format("Finished createConfig() at %s with total duration of %s", new DateTime(finishTime), new Duration(startTime, finishTime).getStandardSeconds()));
}
}
/**
* Should be implemented in order to provide domain driven data population.
*/
protected abstract void populateDomain();
/**
* Should return a complete list of domain entity types.
*
* @return
*/
protected abstract List<Class<? extends AbstractEntity<?>>> domainEntityTypes();
@AfterClass
public final static void removeDbSchema() {
domainPopulated = false;
dataScript.clear();
truncateScript.clear();
}
@Before
public final void beforeTest() throws Exception {
final long startTime = System.currentTimeMillis();
System.out.println(format("Started beforeTest() at %s...", new DateTime(startTime)));
final Connection conn = createConnection();
Optional<Exception> raisedEx = Optional.empty();
if (domainPopulated) {
// apply data population script
logger.debug("Executing data population script.");
exec(dataScript, conn);
} else {
try {
populateDomain();
} catch (final Exception ex) {
raisedEx = Optional.of(ex);
ex.printStackTrace();
}
// record data population statements
final Statement st = conn.createStatement();
final ResultSet set = st.executeQuery("SCRIPT");
while (set.next()) {
final String result = set.getString(1).trim();
final String upperCasedResult = result.toUpperCase();
if (!upperCasedResult.startsWith("INSERT INTO PUBLIC.UNIQUE_ID")
&& (upperCasedResult.startsWith("INSERT") || upperCasedResult.startsWith("UPDATE") || upperCasedResult.startsWith("DELETE"))) {
// resultant script should NOT be UPPERCASED in order not to upperCase for e.g. values,
// that was perhaps lover cased while populateDomain() invocation was performed
dataScript.add(result);
}
}
set.close();
st.close();
// create truncate statements
for (final PersistedEntityMetadata<?> entry : entityMetadatas) {
truncateScript.add(format("TRUNCATE TABLE %s;", entry.getTable()));
}
domainPopulated = true;
}
conn.close();
if (raisedEx.isPresent()) {
domainPopulated = false;
throw new IllegalStateException("Population of the test data has failed.", raisedEx.get());
}
final long finishTime = System.currentTimeMillis();
System.out.println(format("Finished beforeTest() at %s with total duration of %s", new DateTime(finishTime), new Duration(startTime, finishTime).getStandardSeconds()));
}
private void exec(final List<String> statements, final Connection conn) throws SQLException {
final Statement st = conn.createStatement();
for (final String stmt : statements) {
st.execute(stmt);
}
st.close();
}
@After
public final void afterTest() throws Exception {
exec(truncateScript, createConnection());
logger.debug("Executing tables truncation script.");
}
private static Connection createConnection() {
final String url = IDomainDrivenTestCaseConfiguration.hbc.getProperty("hibernate.connection.url");
final String jdbcDriver = IDomainDrivenTestCaseConfiguration.hbc.getProperty("hibernate.connection.driver_class");
final String user = IDomainDrivenTestCaseConfiguration.hbc.getProperty("hibernate.connection.username");
final String passwd = IDomainDrivenTestCaseConfiguration.hbc.getProperty("hibernate.connection.password");
try {
Class.forName(jdbcDriver);
return DriverManager.getConnection(url, user, passwd);
} catch (final Exception e) {
throw new IllegalStateException(e);
}
}
@Override
public final <T> T getInstance(final Class<T> type) {
return config.getInstance(type);
}
@Override
public <T extends AbstractEntity<?>> T save(final T instance) {
@SuppressWarnings("unchecked")
final IEntityDao<T> pp = provider.find((Class<T>) instance.getType());
return pp.save(instance);
}
@Override
@SuppressWarnings("unchecked")
public <T extends IEntityDao<E>, E extends AbstractEntity<?>> T co(final Class<E> type) {
return (T) provider.find(type);
}
@Override
public final Date date(final String dateTime) {
return formatter.parseDateTime(dateTime).toDate();
}
@Override
public final DateTime dateTime(final String dateTime) {
return formatter.parseDateTime(dateTime);
}
/**
* Instantiates a new entity with a non-composite key, the value for which is provided as the second argument, and description -- provided as the value for the third argument.
*
* @param entityClass
* @param key
* @param desc
* @return
*/
@Override
public <T extends AbstractEntity<K>, K extends Comparable> T new_(final Class<T> entityClass, final K key, final String desc) {
return factory.newEntity(entityClass, key, desc);
}
/**
* Instantiates a new entity with a non-composite key, the value for which is provided as the second argument.
*
* @param entityClass
* @param key
* @return
*/
@Override
public <T extends AbstractEntity<K>, K extends Comparable> T new_(final Class<T> entityClass, final K key) {
return factory.newByKey(entityClass, key);
}
/**
* Instantiates a new entity with composite key, where composite key members are assigned based on the provide value. The order of values must match the order specified in key
* member definitions. An empty list of key values is permitted.
*
* @param entityClass
* @param keys
* @return
*/
@Override
public <T extends AbstractEntity<DynamicEntityKey>> T new_composite(final Class<T> entityClass, final Object... keys) {
return keys.length == 0 ? new_(entityClass) : factory.newByKey(entityClass, keys);
}
/**
* Instantiates a new entity based on the provided type only, which leads to creation of a completely empty instance without any of entity properties assigned.
*
* @param entityClass
* @return
*/
@Override
public <T extends AbstractEntity<K>, K extends Comparable> T new_(final Class<T> entityClass) {
return factory.newEntity(entityClass);
}
}
|
package com.intellij.ide.ui.search;
import com.intellij.codeStyle.CodeStyleFacade;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.plugins.PluginManagerConfigurable;
import com.intellij.ide.plugins.PluginManagerCore;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ex.ApplicationInfoEx;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurableGroup;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Couple;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.CollectConsumer;
import com.intellij.util.ObjectUtils;
import com.intellij.util.ResourceUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.io.URLUtil;
import com.intellij.util.text.ByteArrayCharSequence;
import com.intellij.util.text.CharSequenceHashingStrategy;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.event.DocumentEvent;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.*;
import java.util.function.Consumer;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Pattern;
@SuppressWarnings("Duplicates")
public class SearchableOptionsRegistrarImpl extends SearchableOptionsRegistrar {
// option => array of packed OptionDescriptor
private final Map<CharSequence, long[]> myStorage = new THashMap<>(20, 0.9f, CharSequenceHashingStrategy.CASE_SENSITIVE);
private final Set<String> myStopWords = Collections.synchronizedSet(new THashSet<>());
private volatile MultiMap<String, String> myOptionsTopHit;
@NotNull
private volatile Map<Couple<String>, Set<String>> myHighlightOptionToSynonym = Collections.emptyMap();
private volatile boolean allTheseHugeFilesAreLoaded;
private final IndexedCharsInterner myIdentifierTable = new IndexedCharsInterner() {
@Override
public synchronized int toId(@NotNull String name) {
return super.toId(name);
}
@NotNull
@Override
public synchronized CharSequence fromId(int id) {
return super.fromId(id);
}
};
private static final Logger LOG = Logger.getInstance("#com.intellij.ide.ui.search.SearchableOptionsRegistrarImpl");
@NonNls
private static final Pattern REG_EXP = Pattern.compile("[\\W&&[^-]]+");
public SearchableOptionsRegistrarImpl() {
if (ApplicationManager.getApplication().isCommandLine() ||
ApplicationManager.getApplication().isUnitTestMode()) return;
try {
//stop words
InputStream stream = ResourceUtil.getResourceAsStream(SearchableOptionsRegistrarImpl.class, "/search/", "ignore.txt");
if (stream == null) throw new IOException("Broken installation: IDE does not provide /search/ignore.txt");
String text = ResourceUtil.loadText(stream);
final String[] stopWords = text.split("[\\W]");
ContainerUtil.addAll(myStopWords, stopWords);
}
catch (IOException e) {
LOG.error(e);
}
}
private void loadHugeFilesIfNecessary() {
if (allTheseHugeFilesAreLoaded) {
return;
}
allTheseHugeFilesAreLoaded = true;
try {
//index
final Set<URL> searchableOptions = findSearchableOptions();
if (searchableOptions.isEmpty()) {
LOG.info("No /search/searchableOptions.xml found, settings search won't work!");
return;
}
SearchableOptionIndexLoader loader = new SearchableOptionIndexLoader(this, myStorage);
loader.load(searchableOptions);
myOptionsTopHit = loader.getOptionsTopHit();
myHighlightOptionToSynonym = loader.getHighlightOptionToSynonym();
}
catch (Exception e) {
LOG.error(e);
}
ApplicationInfoEx applicationInfo = ApplicationInfoEx.getInstanceEx();
for (IdeaPluginDescriptor plugin : PluginManagerCore.getPlugins()) {
if (applicationInfo.isEssentialPlugin(plugin.getPluginId().getIdString())) {
continue;
}
final String pluginName = plugin.getName();
final Set<String> words = getProcessedWordsWithoutStemming(pluginName);
final String description = plugin.getDescription();
if (description != null) {
words.addAll(getProcessedWordsWithoutStemming(description));
}
addOptions(words, null, pluginName, PluginManagerConfigurable.ID, PluginManagerConfigurable.DISPLAY_NAME);
}
}
@NotNull
private static Set<URL> findSearchableOptions() throws IOException, URISyntaxException {
final Set<URL> urls = new HashSet<>();
final Set<ClassLoader> visited = new HashSet<>();
for (final IdeaPluginDescriptor plugin : PluginManagerCore.getPlugins()) {
if (!plugin.isEnabled()) {
continue;
}
final ClassLoader classLoader = plugin.getPluginClassLoader();
if (visited.add(classLoader)) {
final Enumeration<URL> resources = classLoader.getResources("search");
while (resources.hasMoreElements()) {
final URL url = resources.nextElement();
if (URLUtil.JAR_PROTOCOL.equals(url.getProtocol())) {
final Pair<String, String> parts = ObjectUtils.notNull(URLUtil.splitJarUrl(url.getFile()));
final File file = new File(parts.first);
try (final JarFile jar = new JarFile(file)) {
final Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
final String name = entries.nextElement().getName();
if (name.startsWith("search/") && name.endsWith(SEARCHABLE_OPTIONS_XML) && StringUtil.countChars(name, '/') == 1) {
urls.add(URLUtil.getJarEntryURL(file, name));
}
}
}
}
else {
final File file = new File(url.toURI());
if (file.isDirectory()) {
final File[] files = file.listFiles((dir, name) -> name.endsWith(SEARCHABLE_OPTIONS_XML));
if (files != null) {
for (final File xml : files) {
if (xml.isFile()) {
urls.add(xml.toURI().toURL());
}
}
}
}
}
}
}
}
return urls;
}
/**
* @return XYZT:64 bits where X:16 bits - id of the interned groupName
* Y:16 bits - id of the interned id
* Z:16 bits - id of the interned hit
* T:16 bits - id of the interned path
*/
@SuppressWarnings("SpellCheckingInspection")
private long pack(@NotNull final String id, @Nullable String hit, @Nullable final String path, @Nullable String groupName) {
long _id = myIdentifierTable.toId(id.trim());
long _hit = hit == null ? Short.MAX_VALUE : myIdentifierTable.toId(hit.trim());
long _path = path == null ? Short.MAX_VALUE : myIdentifierTable.toId(path.trim());
long _groupName = groupName == null ? Short.MAX_VALUE : myIdentifierTable.toId(groupName.trim());
assert _id >= 0 && _id < Short.MAX_VALUE;
assert _hit >= 0 && _hit <= Short.MAX_VALUE;
assert _path >= 0 && _path <= Short.MAX_VALUE;
assert _groupName >= 0 && _groupName <= Short.MAX_VALUE;
return _groupName << 48 | _id << 32 | _hit << 16 | _path;
}
private OptionDescription unpack(long data) {
int _groupName = (int)(data >> 48 & 0xffff);
int _id = (int)(data >> 32 & 0xffff);
int _hit = (int)(data >> 16 & 0xffff);
int _path = (int)(data & 0xffff);
assert /*_id >= 0 && */_id < Short.MAX_VALUE;
assert /*_hit >= 0 && */_hit <= Short.MAX_VALUE;
assert /*_path >= 0 && */_path <= Short.MAX_VALUE;
assert /*_groupName >= 0 && */_groupName <= Short.MAX_VALUE;
String groupName = _groupName == Short.MAX_VALUE ? null : myIdentifierTable.fromId(_groupName).toString();
String configurableId = myIdentifierTable.fromId(_id).toString();
String hit = _hit == Short.MAX_VALUE ? null : myIdentifierTable.fromId(_hit).toString();
String path = _path == Short.MAX_VALUE ? null : myIdentifierTable.fromId(_path).toString();
return new OptionDescription(null, configurableId, hit, path, groupName);
}
static void putOptionWithHelpId(@NotNull String option,
@NotNull String id,
@Nullable String groupName,
@Nullable String hit,
@Nullable String path,
@NotNull Map<CharSequence, long[]> storage,
@NotNull SearchableOptionsRegistrarImpl registrar) {
if (registrar.isStopWord(option)) return;
String stopWord = PorterStemmerUtil.stem(option);
if (stopWord == null) return;
if (registrar.isStopWord(stopWord)) return;
long[] configs = storage.get(option);
long packed = registrar.pack(id, hit, path, groupName);
if (configs == null) {
configs = new long[]{packed};
}
else if (ArrayUtil.indexOf(configs, packed) == -1) {
configs = ArrayUtil.append(configs, packed);
}
storage.put(ByteArrayCharSequence.convertToBytesIfPossible(option), configs);
}
@Override
@NotNull
public ConfigurableHit getConfigurables(@NotNull List<ConfigurableGroup> groups,
final DocumentEvent.EventType type,
@Nullable Set<? extends Configurable> configurables,
@NotNull String option,
@Nullable Project project) {
//noinspection unchecked
return findConfigurables(groups, type, (Collection<Configurable>)configurables, option, project);
}
@NotNull
private ConfigurableHit findConfigurables(@NotNull List<ConfigurableGroup> groups,
final DocumentEvent.EventType type,
@Nullable Collection<Configurable> configurables,
@NotNull String option,
@Nullable Project project) {
Collection<Configurable> effectiveConfigurables;
if (ContainerUtil.isEmpty(configurables)) {
configurables = null;
}
if (configurables == null) {
effectiveConfigurables = new LinkedHashSet<>();
Consumer<Configurable> consumer = new CollectConsumer<>(effectiveConfigurables);
for (ConfigurableGroup group : groups) {
SearchUtil.processExpandedGroups(group, consumer);
}
}
else {
effectiveConfigurables = configurables;
}
String optionToCheck = StringUtil.toLowerCase(option.trim());
Set<String> options = getProcessedWordsWithoutStemming(optionToCheck);
Set<Configurable> nameHits = new LinkedHashSet<>();
Set<Configurable> nameFullHits = new LinkedHashSet<>();
for (Configurable each : effectiveConfigurables) {
if (each.getDisplayName() == null) continue;
final String displayName = StringUtil.toLowerCase(each.getDisplayName());
final List<String> allWords = StringUtil.getWordsIn(displayName);
if (displayName.contains(optionToCheck)) {
nameFullHits.add(each);
nameHits.add(each);
}
for (String eachWord : allWords) {
if (eachWord.startsWith(optionToCheck)) {
nameHits.add(each);
break;
}
}
if (options.isEmpty()) {
nameHits.add(each);
nameFullHits.add(each);
}
}
Set<Configurable> currentConfigurables = type == DocumentEvent.EventType.CHANGE ? new THashSet<>(effectiveConfigurables) : null;
// operate with substring
if (options.isEmpty()) {
String[] components = REG_EXP.split(optionToCheck);
if (components.length > 0) {
Collections.addAll(options, components);
}
else {
options.add(option);
}
}
Set<Configurable> contentHits;
if (configurables == null) {
contentHits = (Set<Configurable>)effectiveConfigurables;
}
else {
contentHits = new LinkedHashSet<>(effectiveConfigurables);
}
Set<String> helpIds = null;
for (String opt : options) {
final Set<OptionDescription> optionIds = getAcceptableDescriptions(opt);
if (optionIds == null) {
contentHits.clear();
return new ConfigurableHit(nameHits, nameFullHits, contentHits);
}
final Set<String> ids = new HashSet<>();
for (OptionDescription id : optionIds) {
ids.add(id.getConfigurableId());
}
if (helpIds == null) {
helpIds = ids;
}
helpIds.retainAll(ids);
}
if (helpIds != null) {
for (Iterator<Configurable> it = contentHits.iterator(); it.hasNext();) {
Configurable configurable = it.next();
if (CodeStyleFacade.getInstance(project).isUnsuitableCodeStyleConfigurable(configurable)) {
it.remove();
continue;
}
if (!(configurable instanceof SearchableConfigurable && helpIds.contains(((SearchableConfigurable)configurable).getId()))) {
it.remove();
}
}
}
if (type == DocumentEvent.EventType.CHANGE && configurables != null && currentConfigurables.equals(contentHits)) {
return getConfigurables(groups, DocumentEvent.EventType.CHANGE, null, option, project);
}
return new ConfigurableHit(nameHits, nameFullHits, contentHits);
}
@Nullable
public synchronized Set<OptionDescription> getAcceptableDescriptions(@Nullable String prefix) {
if (prefix == null) {
return null;
}
final String stemmedPrefix = PorterStemmerUtil.stem(prefix);
if (StringUtil.isEmptyOrSpaces(stemmedPrefix)) {
return null;
}
loadHugeFilesIfNecessary();
Set<OptionDescription> result = null;
for (Map.Entry<CharSequence, long[]> entry : myStorage.entrySet()) {
final long[] descriptions = entry.getValue();
final CharSequence option = entry.getKey();
if (!StringUtil.startsWith(option, prefix) && !StringUtil.startsWith(option, stemmedPrefix)) {
final String stemmedOption = PorterStemmerUtil.stem(option.toString());
if (stemmedOption != null && !stemmedOption.startsWith(prefix) && !stemmedOption.startsWith(stemmedPrefix)) {
continue;
}
}
if (result == null) {
result = new THashSet<>();
}
for (long description : descriptions) {
OptionDescription desc = unpack(description);
result.add(desc);
}
}
return result;
}
@Override
@Nullable
public String getInnerPath(SearchableConfigurable configurable, @NonNls String option) {
loadHugeFilesIfNecessary();
Set<OptionDescription> path = null;
final Set<String> words = getProcessedWordsWithoutStemming(option);
for (String word : words) {
Set<OptionDescription> configs = getAcceptableDescriptions(word);
if (configs == null) return null;
final Set<OptionDescription> paths = new HashSet<>();
for (OptionDescription config : configs) {
if (Comparing.strEqual(config.getConfigurableId(), configurable.getId())) {
paths.add(config);
}
}
if (path == null) {
path = paths;
}
path.retainAll(paths);
}
if (path == null || path.isEmpty()) {
return null;
}
else {
OptionDescription result = null;
for (OptionDescription description : path) {
final String hit = description.getHit();
if (hit != null) {
boolean theBest = true;
for (String word : words) {
if (!hit.contains(word)) {
theBest = false;
break;
}
}
if (theBest) return description.getPath();
}
result = description;
}
return result.getPath();
}
}
@Override
public boolean isStopWord(String word) {
return myStopWords.contains(word);
}
@Override
public synchronized void addOption(@NotNull String option, @Nullable String path, @NotNull String hit, @NotNull String configurableId, final String configurableDisplayName) {
putOptionWithHelpId(option, configurableId, configurableDisplayName, hit, path, myStorage, this);
}
@Override
public synchronized void addOptions(@NotNull Collection<String> words, @Nullable String path, String hit, @NotNull String configurableId, String configurableDisplayName) {
for (String word : words) {
putOptionWithHelpId(word, configurableId, configurableDisplayName, hit, path, myStorage, this);
}
}
@Override
public Set<String> getProcessedWordsWithoutStemming(@NotNull String text) {
Set<String> result = new THashSet<>();
for (String opt : REG_EXP.split(StringUtil.toLowerCase(text))) {
if (isStopWord(opt)) {
continue;
}
String processed = PorterStemmerUtil.stem(opt);
if (isStopWord(processed)) {
continue;
}
result.add(opt);
}
return result;
}
@Override
public Set<String> getProcessedWords(@NotNull String text) {
Set<String> result = new THashSet<>();
String toLowerCase = StringUtil.toLowerCase(text);
final String[] options = REG_EXP.split(toLowerCase);
for (String opt : options) {
if (isStopWord(opt)) continue;
opt = PorterStemmerUtil.stem(opt);
if (opt == null) continue;
result.add(opt);
}
return result;
}
@NotNull
@Override
public Set<String> replaceSynonyms(@NotNull Set<String> options, @NotNull SearchableConfigurable configurable) {
if (myHighlightOptionToSynonym.isEmpty()) {
return options;
}
Set<String> result = new THashSet<>(options);
loadHugeFilesIfNecessary();
for (String option : options) {
Set<String> synonyms = myHighlightOptionToSynonym.get(Couple.of(option, configurable.getId()));
if (synonyms != null) {
result.addAll(synonyms);
}
else {
result.add(option);
}
}
return result;
}
@Override
@NotNull
public Collection<String> getOptionsTopHit(@NotNull String configurableId) {
loadHugeFilesIfNecessary();
return Collections.unmodifiableCollection(myOptionsTopHit.get(configurableId));
}
}
|
package com.intellij.execution.process;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.testFramework.PlatformTestCase;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.junit.Assert;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class AnsiEscapeDecoderTest extends PlatformTestCase {
public void testTextWithoutColors() throws Exception {
AnsiEscapeDecoder decoder = new AnsiEscapeDecoder();
decoder.escapeText("", ProcessOutputTypes.STDOUT, createExpectedAcceptor(
Pair.create("", ProcessOutputTypes.STDOUT)
));
decoder.escapeText("simple text", ProcessOutputTypes.STDOUT, createExpectedAcceptor(
Pair.create("simple text", ProcessOutputTypes.STDOUT)
));
}
public void testSingleColoredChunk() throws Exception {
AnsiEscapeDecoder decoder = new AnsiEscapeDecoder();
decoder.escapeText("Chrome 35.0.1916 (Linux): Executed 0 of 1\u001B[32m SUCCESS\u001B[39m (0 secs / 0 secs)\n", ProcessOutputTypes.STDOUT, createExpectedAcceptor(
Pair.create("Chrome 35.0.1916 (Linux): Executed 0 of 1", ProcessOutputTypes.STDOUT),
Pair.create(" SUCCESS", ColoredOutputTypeRegistry.getInstance().getOutputKey("\u001B[32m")),
Pair.create(" (0 secs / 0 secs)\n", ColoredOutputTypeRegistry.getInstance().getOutputKey("\u001B[39m"))
));
}
public void testCompoundEscSeq() throws Exception {
AnsiEscapeDecoder decoder = new AnsiEscapeDecoder();
decoder.escapeText("E\u001B[41m\u001B[37mE\u001B[0mE", ProcessOutputTypes.STDOUT, createExpectedAcceptor(
Pair.create("E", ProcessOutputTypes.STDOUT),
Pair.create("E", ColoredOutputTypeRegistry.getInstance().getOutputKey("\u001B[41;37m")),
Pair.create("E", ProcessOutputTypes.STDOUT)
));
}
public void testOtherEscSeq() throws Exception {
AnsiEscapeDecoder decoder = new AnsiEscapeDecoder();
decoder.escapeText("Plain\u001B[32mGreen\u001B[39mNormal\u001B[1A\u001B[2K\u001B[31mRed\u001B[39m",
ProcessOutputTypes.STDOUT,
createExpectedAcceptor(
Pair.create("Plain", ProcessOutputTypes.STDOUT),
Pair.create("Green", ColoredOutputTypeRegistry.getInstance().getOutputKey("\u001B[32m")),
Pair.create("Normal", ColoredOutputTypeRegistry.getInstance().getOutputKey("\u001B[39m")),
Pair.create("Red", ColoredOutputTypeRegistry.getInstance().getOutputKey("\u001B[31m"))
)
);
}
@NotNull
private static List<Pair<String, String>> toListWithKeyName(@NotNull Collection<Pair<String, Key>> list) {
return ContainerUtil.map(list, new Function<Pair<String, Key>, Pair<String, String>>() {
@Override
public Pair<String, String> fun(Pair<String, Key> pair) {
return Pair.create(pair.first, pair.second.toString());
}
});
}
private static AnsiEscapeDecoder.ColoredChunksAcceptor createExpectedAcceptor(@NotNull final Pair<String, Key>... expected) {
return new AnsiEscapeDecoder.ColoredChunksAcceptor() {
@Override
public void coloredChunksAvailable(List<Pair<String, Key>> chunks) {
List<Pair<String, String>> expectedWithKeyName = toListWithKeyName(Arrays.asList(expected));
List<Pair<String, String>> actualWithKeyName = toListWithKeyName(chunks);
Assert.assertEquals(expectedWithKeyName, actualWithKeyName);
}
@Override
public void coloredTextAvailable(String text, Key attributes) {
throw new RuntimeException(); // shouldn't be called
}
};
}
}
|
package com.intellij.coverage.actions;
import com.intellij.coverage.*;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ComboBoxAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.*;
import com.intellij.util.IconUtil;
import com.intellij.util.PlatformIcons;
import com.intellij.util.containers.Convertor;
import com.intellij.util.containers.HashMap;
import com.intellij.util.text.DateFormatUtil;
import com.intellij.util.ui.tree.TreeUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.*;
import java.util.List;
public class CoverageSuiteChooserDialog extends DialogWrapper {
@NonNls private static final String LOCAL = "Local";
private final Project myProject;
private final CheckboxTree mySuitesTree;
private final CoverageDataManager myCoverageManager;
private static final Logger LOG = Logger.getInstance("#" + CoverageSuiteChooserDialog.class.getName());
private final CheckedTreeNode myRootNode;
private CoverageEngine myEngine;
public CoverageSuiteChooserDialog(Project project) {
super(project, true);
myProject = project;
myCoverageManager = CoverageDataManager.getInstance(project);
myRootNode = new CheckedTreeNode("");
initTree();
mySuitesTree = new CheckboxTree(new SuitesRenderer(), myRootNode) {
protected void installSpeedSearch() {
new TreeSpeedSearch(this, new Convertor<TreePath, String>() {
public String convert(TreePath path) {
final DefaultMutableTreeNode component = (DefaultMutableTreeNode)path.getLastPathComponent();
final Object userObject = component.getUserObject();
if (userObject instanceof CoverageSuite) {
return ((CoverageSuite)userObject).getPresentableName();
}
return userObject.toString();
}
});
}
};
mySuitesTree.getEmptyText().appendText("No coverage suites configured.");
mySuitesTree.setRootVisible(false);
mySuitesTree.setShowsRootHandles(false);
TreeUtil.installActions(mySuitesTree);
TreeUtil.expandAll(mySuitesTree);
TreeUtil.selectFirstNode(mySuitesTree);
mySuitesTree.setMinimumSize(new Dimension(25, -1));
setOKButtonText("Show selected");
init();
setTitle("Choose Coverage Suite to Display");
}
@Override
protected JComponent createCenterPanel() {
return ScrollPaneFactory.createScrollPane(mySuitesTree);
}
@Override
public JComponent getPreferredFocusedComponent() {
return mySuitesTree;
}
@Override
protected JComponent createNorthPanel() {
final DefaultActionGroup group = new DefaultActionGroup();
group.add(new AddExternalSuiteAction());
group.add(new DeleteSuiteAction());
group.add(new SwitchEngineAction());
return ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, group, true).getComponent();
}
@Override
protected void doOKAction() {
final List<CoverageSuite> suites = collectSelectedSuites();
myCoverageManager.chooseSuitesBundle(suites.isEmpty() ? null : new CoverageSuitesBundle(suites.toArray(new CoverageSuite[suites.size()])));
super.doOKAction();
}
@Override
protected Action[] createActions() {
return new Action[]{getOKAction(), new NoCoverageAction(), getCancelAction()};
}
private Set<CoverageEngine> collectEngines() {
final Set<CoverageEngine> engines = new HashSet<CoverageEngine>();
for (CoverageSuite suite : myCoverageManager.getSuites()) {
engines.add(suite.getCoverageEngine());
}
return engines;
}
private static String getCoverageRunnerTitle(CoverageRunner coverageRunner) {
return coverageRunner.getPresentableName() + " Coverage";
}
@Nullable
private static CoverageRunner getCoverageRunner(VirtualFile file) {
for (CoverageRunner runner : Extensions.getExtensions(CoverageRunner.EP_NAME)) {
if (Comparing.strEqual(file.getExtension(), runner.getDataFileExtension())) return runner;
}
return null;
}
private List<CoverageSuite> collectSelectedSuites() {
final List<CoverageSuite> suites = new ArrayList<CoverageSuite>();
TreeUtil.traverse(myRootNode, new TreeUtil.Traverse() {
@Override
public boolean accept(Object treeNode) {
if (treeNode instanceof CheckedTreeNode && ((CheckedTreeNode)treeNode).isChecked()) {
final Object userObject = ((CheckedTreeNode)treeNode).getUserObject();
if (userObject instanceof CoverageSuite) {
suites.add((CoverageSuite)userObject);
}
}
return true;
}
});
return suites;
}
private void initTree() {
myRootNode.removeAllChildren();
final HashMap<CoverageRunner, Map<String, List<CoverageSuite>>> grouped =
new HashMap<CoverageRunner, Map<String, List<CoverageSuite>>>();
groupSuites(grouped, myCoverageManager.getSuites(), myEngine);
final CoverageSuitesBundle currentSuite = myCoverageManager.getCurrentSuitesBundle();
final List<CoverageRunner> runners = new ArrayList<CoverageRunner>(grouped.keySet());
Collections.sort(runners, new Comparator<CoverageRunner>() {
@Override
public int compare(CoverageRunner o1, CoverageRunner o2) {
return o1.getPresentableName().compareToIgnoreCase(o2.getPresentableName());
}
});
for (CoverageRunner runner : runners) {
final DefaultMutableTreeNode runnerNode = new DefaultMutableTreeNode(getCoverageRunnerTitle(runner));
final Map<String, List<CoverageSuite>> providers = grouped.get(runner);
final DefaultMutableTreeNode remoteNode = new DefaultMutableTreeNode("Remote");
if (providers.size() == 1) {
final String providersKey = providers.keySet().iterator().next();
DefaultMutableTreeNode suitesNode = runnerNode;
if (!Comparing.strEqual(providersKey, DefaultCoverageFileProvider.class.getName())) {
suitesNode = remoteNode;
runnerNode.add(remoteNode);
}
final List<CoverageSuite> suites = providers.get(providersKey);
Collections.sort(suites, new Comparator<CoverageSuite>() {
@Override
public int compare(CoverageSuite o1, CoverageSuite o2) {
return o1.getPresentableName().compareToIgnoreCase(o2.getPresentableName());
}
});
for (CoverageSuite suite : suites) {
final CheckedTreeNode treeNode = new CheckedTreeNode(suite);
treeNode.setChecked(currentSuite != null && currentSuite.contains(suite) ? Boolean.TRUE : Boolean.FALSE);
suitesNode.add(treeNode);
}
}
else {
final DefaultMutableTreeNode localNode = new DefaultMutableTreeNode(LOCAL);
runnerNode.add(localNode);
runnerNode.add(remoteNode);
for (String aClass : providers.keySet()) {
DefaultMutableTreeNode node = Comparing.strEqual(aClass, DefaultCoverageFileProvider.class.getName()) ? localNode : remoteNode;
for (CoverageSuite suite : providers.get(aClass)) {
final CheckedTreeNode treeNode = new CheckedTreeNode(suite);
treeNode.setChecked(currentSuite != null && currentSuite.contains(suite) ? Boolean.TRUE : Boolean.FALSE);
node.add(treeNode);
}
}
}
myRootNode.add(runnerNode);
}
}
private static void groupSuites(final HashMap<CoverageRunner, Map<String, List<CoverageSuite>>> grouped,
final CoverageSuite[] suites,
final CoverageEngine engine) {
for (CoverageSuite suite : suites) {
if (engine != null && suite.getCoverageEngine() != engine) continue;
final CoverageFileProvider provider = suite.getCoverageDataFileProvider();
if (provider instanceof DefaultCoverageFileProvider &&
Comparing.strEqual(((DefaultCoverageFileProvider)provider).getSourceProvider(), DefaultCoverageFileProvider.class.getName())) {
if (!provider.ensureFileExists()) continue;
}
final CoverageRunner runner = suite.getRunner();
Map<String, List<CoverageSuite>> byProviders = grouped.get(runner);
if (byProviders == null) {
byProviders = new HashMap<String, List<CoverageSuite>>();
grouped.put(runner, byProviders);
}
final String sourceProvider = provider instanceof DefaultCoverageFileProvider
? ((DefaultCoverageFileProvider)provider).getSourceProvider()
: provider.getClass().getName();
List<CoverageSuite> list = byProviders.get(sourceProvider);
if (list == null) {
list = new ArrayList<CoverageSuite>();
byProviders.put(sourceProvider, list);
}
list.add(suite);
}
}
private void updateTree() {
((DefaultTreeModel)mySuitesTree.getModel()).reload();
TreeUtil.expandAll(mySuitesTree);
}
private static class SuitesRenderer extends CheckboxTree.CheckboxTreeCellRenderer {
@Override
public void customizeRenderer(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
if (value instanceof CheckedTreeNode) {
final Object userObject = ((CheckedTreeNode)value).getUserObject();
if (userObject instanceof CoverageSuite) {
CoverageSuite suite = (CoverageSuite)userObject;
getTextRenderer().append(suite.getPresentableName(), SimpleTextAttributes.REGULAR_ATTRIBUTES);
final String date = " (" + DateFormatUtil.formatPrettyDateTime(suite.getLastCoverageTimeStamp()) + ")";
getTextRenderer().append(date, SimpleTextAttributes.GRAY_ATTRIBUTES);
}
}
else if (value instanceof DefaultMutableTreeNode) {
final Object userObject = ((DefaultMutableTreeNode)value).getUserObject();
if (userObject instanceof String) {
getTextRenderer().append((String)userObject);
}
}
}
}
private class NoCoverageAction extends DialogWrapperAction {
public NoCoverageAction() {
super("&No Coverage");
}
@Override
protected void doAction(ActionEvent e) {
myCoverageManager.chooseSuitesBundle(null);
CoverageSuiteChooserDialog.this.close(DialogWrapper.OK_EXIT_CODE);
}
}
private class AddExternalSuiteAction extends AnAction {
public AddExternalSuiteAction() {
super("Add", "Add", IconUtil.getAddIcon());
registerCustomShortcutSet(CommonShortcuts.INSERT, mySuitesTree);
}
@Override
public void actionPerformed(AnActionEvent e) {
final VirtualFile file =
FileChooser.chooseFile(new FileChooserDescriptor(true, false, false, false, false, false) {
@Override
public boolean isFileSelectable(VirtualFile file) {
return getCoverageRunner(file) != null;
}
}, myProject, null);
if (file != null) {
final CoverageRunner coverageRunner = getCoverageRunner(file);
LOG.assertTrue(coverageRunner != null);
final CoverageSuite coverageSuite = myCoverageManager
.addExternalCoverageSuite(file.getName(), file.getTimeStamp(), coverageRunner,
new DefaultCoverageFileProvider(file.getPath()));
final String coverageRunnerTitle = getCoverageRunnerTitle(coverageRunner);
DefaultMutableTreeNode node = TreeUtil.findNodeWithObject(myRootNode, coverageRunnerTitle);
if (node == null) {
node = new DefaultMutableTreeNode(coverageRunnerTitle);
myRootNode.add(node);
}
if (node.getChildCount() > 0) {
final TreeNode childNode = node.getChildAt(0);
if (!(childNode instanceof CheckedTreeNode)) {
if (LOCAL.equals(((DefaultMutableTreeNode)childNode).getUserObject())) {
node = (DefaultMutableTreeNode)childNode;
} else {
final DefaultMutableTreeNode localNode = new DefaultMutableTreeNode(LOCAL);
node.add(localNode);
node = localNode;
}
}
}
final CheckedTreeNode suiteNode = new CheckedTreeNode(coverageSuite);
suiteNode.setChecked(true);
node.add(suiteNode);
TreeUtil.sort(node, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof CheckedTreeNode && o2 instanceof CheckedTreeNode) {
final Object userObject1 = ((CheckedTreeNode)o1).getUserObject();
final Object userObject2 = ((CheckedTreeNode)o2).getUserObject();
if (userObject1 instanceof CoverageSuite && userObject2 instanceof CoverageSuite) {
final String presentableName1 = ((CoverageSuite)userObject1).getPresentableName();
final String presentableName2 = ((CoverageSuite)userObject2).getPresentableName();
return presentableName1.compareToIgnoreCase(presentableName2);
}
}
return 0;
}
});
updateTree();
TreeUtil.selectNode(mySuitesTree, suiteNode);
}
}
}
private class DeleteSuiteAction extends AnAction {
public DeleteSuiteAction() {
super("Delete", "Delete", PlatformIcons.DELETE_ICON);
registerCustomShortcutSet(CommonShortcuts.DELETE, mySuitesTree);
}
@Override
public void actionPerformed(AnActionEvent e) {
final CheckedTreeNode[] selectedNodes = mySuitesTree.getSelectedNodes(CheckedTreeNode.class, null);
for (CheckedTreeNode selectedNode : selectedNodes) {
final Object userObject = selectedNode.getUserObject();
if (userObject instanceof CoverageSuite) {
final CoverageSuite selectedSuite = (CoverageSuite)userObject;
if (selectedSuite.getCoverageDataFileProvider() instanceof DefaultCoverageFileProvider &&
Comparing.strEqual(((DefaultCoverageFileProvider)selectedSuite.getCoverageDataFileProvider()).getSourceProvider(),
DefaultCoverageFileProvider.class.getName())) {
myCoverageManager.removeCoverageSuite(selectedSuite);
TreeUtil.removeLastPathComponent(mySuitesTree, new TreePath(selectedNode.getPath()));
}
}
}
}
@Override
public void update(AnActionEvent e) {
final CheckedTreeNode[] selectedSuites = mySuitesTree.getSelectedNodes(CheckedTreeNode.class, null);
final Presentation presentation = e.getPresentation();
presentation.setEnabled(false);
for (CheckedTreeNode node : selectedSuites) {
final Object userObject = node.getUserObject();
if (userObject instanceof CoverageSuite) {
final CoverageSuite selectedSuite = (CoverageSuite)userObject;
if (selectedSuite.getCoverageDataFileProvider() instanceof DefaultCoverageFileProvider &&
Comparing.strEqual(((DefaultCoverageFileProvider)selectedSuite.getCoverageDataFileProvider()).getSourceProvider(),
DefaultCoverageFileProvider.class.getName())) {
presentation.setEnabled(true);
}
}
}
}
}
private class SwitchEngineAction extends ComboBoxAction {
@NotNull
@Override
protected DefaultActionGroup createPopupActionGroup(JComponent button) {
final DefaultActionGroup engChooser = new DefaultActionGroup();
for (final CoverageEngine engine : collectEngines()) {
engChooser.add(new AnAction(engine.getPresentableText()) {
@Override
public void actionPerformed(AnActionEvent e) {
myEngine = engine;
initTree();
updateTree();
}
});
}
return engChooser;
}
@Override
public void update(AnActionEvent e) {
super.update(e);
e.getPresentation().setVisible(collectEngines().size() > 1);
}
}
}
|
package org.editorconfig.plugincomponents;
import com.intellij.lang.Language;
import com.intellij.lang.LanguageAnnotators;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.fileTypes.LanguageFileType;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ProjectRootModificationTracker;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.CachedValuesManager;
import org.editorconfig.Utils;
import org.editorconfig.annotations.EditorConfigAnnotator;
import org.editorconfig.core.EditorConfig;
import org.editorconfig.core.EditorConfig.OutPair;
import org.editorconfig.core.EditorConfigException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
public class SettingsProviderComponent implements ApplicationComponent {
private EditorConfig editorConfig;
public SettingsProviderComponent(FileTypeManager manager) {
editorConfig = new EditorConfig();
registerAnnotator(manager);
}
public void registerAnnotator(FileTypeManager manager) {
final Set<String> languages = new HashSet<String>();
final EditorConfigAnnotator annotator = new EditorConfigAnnotator();
for (FileType type : manager.getRegisteredFileTypes()) {
if (type instanceof LanguageFileType) {
final Language lang = ((LanguageFileType)type).getLanguage();
final String id = lang.getID();
// don't add annotator for language twice
// don't add annotator for languages not having own annotators - they may rely on parent annotators
if (languages.contains(id) || (lang.getBaseLanguage() != null/* && LanguageAnnotators.INSTANCE.forKey(lang).isEmpty()*/)) continue;
LanguageAnnotators.INSTANCE.addExplicitExtension(lang, annotator);
languages.add(id);
}
}
}
public static SettingsProviderComponent getInstance() {
return ServiceManager.getService(SettingsProviderComponent.class);
}
public List<OutPair> getOutPairs(Project project, String filePath) {
final List<OutPair> outPairs;
try {
final Set<String> rootDirs = getRootDirs(project);
outPairs = editorConfig.getProperties(filePath, rootDirs);
return outPairs;
}
catch (EditorConfigException error) {
Utils.invalidConfigMessage(project, error.getMessage(), "", filePath);
return new ArrayList<OutPair>();
}
}
public Set<String> getRootDirs(final Project project) {
if (!Registry.is("editor.config.stop.at.project.root")) {
return Collections.emptySet();
}
return CachedValuesManager.getManager(project).getCachedValue(project, new CachedValueProvider<Set<String>>() {
@Nullable
@Override
public Result<Set<String>> compute() {
final Set<String> dirs = new HashSet<String>();
final VirtualFile projectBase = project.getBaseDir();
dirs.add(project.getBasePath());
for (Module module : ModuleManager.getInstance(project).getModules()) {
for (VirtualFile root : ModuleRootManager.getInstance(module).getContentRoots()) {
if (!VfsUtilCore.isAncestor(projectBase, root, false)) {
dirs.add(root.getPath());
}
}
}
return new Result<Set<String>>(dirs, ProjectRootModificationTracker.getInstance(project));
}
});
}
public void initComponent() {
}
public void disposeComponent() {
}
@NotNull
public String getComponentName() {
return "SettingsProviderComponent";
}
}
|
package hex.tree;
import java.util.Arrays;
import java.util.Random;
import water.*;
import water.util.IcedBitSet;
import water.util.SB;
// Highly compressed tree encoding:
// tree: 1B nodeType, 2B colId, 4B splitVal, left-tree-size, left, right
// nodeType: (from lsb):
// 2 bits (1,2) skip-tree-size-size,
// 2 bits (4,8) operator flag (0 --> <, 1 --> ==, 2 --> small (4B) group, 3 --> big (var size) group),
// 1 bit ( 16) left leaf flag,
// 1 bit ( 32) left leaf type flag (0: subtree, 1: small cat, 2: big cat, 3: float)
// 1 bit ( 64) right leaf flag,
// 1 bit (128) right leaf type flag (0: subtree, 1: small cat, 2: big cat, 3: float)
// left, right: tree | prediction
// prediction: 4 bytes of float (or 1 or 2 bytes of class prediction)
public class CompressedTree extends Keyed {
final byte [] _bits;
final int _nclass; // Number of classes being predicted (for an integer prediction tree)
final long _seed;
public CompressedTree( byte[] bits, int nclass, long seed, int tid, int cls ) {
super(makeTreeKey(tid, cls));
_bits = bits; _nclass = nclass; _seed = seed;
}
/** Highly efficient (critical path) tree scoring */
public double score( final double row[]) { return score(row, false); }
public double score( final double row[], boolean computeLeafAssignment) {
AutoBuffer ab = new AutoBuffer(_bits);
IcedBitSet ibs = null; // Lazily set on hitting first group test
long bitsRight = 0;
int level = 0;
while(true) {
int nodeType = ab.get1U();
int colId = ab.get2();
if( colId == 65535 ) return scoreLeaf(ab);
// boolean equal = ((nodeType&4)==4);
int equal = (nodeType&12) >> 2;
assert (equal >= 0 && equal <= 3): "illegal equal value " + equal+" at "+ab+" in bitpile "+Arrays.toString(_bits);
// Extract value or group to split on
float splitVal = -1;
if(equal == 0 || equal == 1) { // Standard float-compare test (either < or ==)
splitVal = ab.get4f(); // Get the float to compare
} else { // Bitset test
if( ibs == null ) ibs = new IcedBitSet(0);
if( equal == 2 ) ibs.fill2(_bits,ab);
else ibs.fill3(_bits,ab);
}
// Compute the amount to skip.
int lmask = nodeType & 0x33;
int rmask = (nodeType & 0xC0) >> 2;
int skip = 0;
switch(lmask) {
case 0: skip = ab.get1U(); break;
case 1: skip = ab.get2 (); break;
case 2: skip = ab.get3 (); break;
case 3: skip = ab.get4 (); break;
case 16: skip = _nclass < 256?1:2; break; // Small leaf
case 48: skip = 4; break; // skip the prediction
default: assert false:"illegal lmask value " + lmask+" at "+ab+" in bitpile "+Arrays.toString(_bits);
}
// WARNING: Generated code has to be consistent with this code:
// - Double.NaN < 3.7f => return false => BUT left branch has to be selected (i.e., ab.position())
// - Double.NaN != 3.7f => return true => left branch has to be select selected (i.e., ab.position())
double d = row[colId];
if( ( equal==0 && d >= splitVal) ||
( equal==1 && d == splitVal) ||
( (equal==2 || equal==3) && ibs.contains((int)d) )) { //if Double.isNaN(d), then (int)d == 0, which means that NA is treated like categorical level 0
ab.skip(skip); // Skip to the right subtree
if (computeLeafAssignment && level < 64) bitsRight |= 1 << level;
lmask = rmask; // And set the leaf bits into common place
} else {
/* go left */
}
level++;
if( (lmask&16)==16 ) {
if (computeLeafAssignment) {
bitsRight |= 1 << level; //mark the end of the tree
return Double.longBitsToDouble(bitsRight);
}
return scoreLeaf(ab);
}
}
}
public String getDecisionPath(final double row[] ) {
double d = score(row, true);
long l = Double.doubleToRawLongBits(d);
StringBuilder sb = new StringBuilder();
int pos=0;
for (int i=0;i<64;++i) {
long right = (l>>i)&0x1L;
sb.append(right==1? "R" : "L");
if (right==1) pos=i;
}
return sb.substring(0, pos);
}
private float scoreLeaf( AutoBuffer ab ) { return ab.get4f(); }
public Random rngForChunk( int cidx ) {
Random rand = new Random(_seed);
for( int i=0; i<cidx; i++ ) rand.nextLong();
long seed = rand.nextLong();
return new Random(seed);
}
@Override protected long checksum_impl() { throw water.H2O.fail(); }
public String toString( SharedTreeModel.SharedTreeOutput tm ) {
final String[] names = tm._names;
final SB sb = new SB();
new TreeVisitor<RuntimeException>(this) {
int _d;
@Override protected void pre( int col, float fcmp, IcedBitSet gcmp, int equal ) {
sb.i().p(names[col]).p(' ');
if( equal==0 ) sb.p("< ").p(fcmp);
else if( equal==1 ) sb.p("!=").p(fcmp);
else sb.p("in ").p(gcmp);
sb.ii(1).nl();
}
@Override protected void post( int col, float fcmp, int equal ) { sb.di(1); }
@Override protected void leaf( float pred ) { sb.i().p("return ").p(pred).nl(); }
}.visit();
return sb.toString();
}
public static Key<CompressedTree> makeTreeKey(int treeId, int clazz) {
return Key.makeSystem("tree_" + treeId + "_" + clazz + "_" + Key.rand());
}
}
|
package hex.rulefit;
import hex.ConfusionMatrix;
import hex.ScoringInfo;
import hex.genmodel.utils.DistributionFamily;
import hex.glm.GLM;
import hex.glm.GLMModel;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import water.DKV;
import water.Key;
import water.Scope;
import water.TestUtil;
import water.fvec.Frame;
import water.fvec.NFSFileVec;
import water.fvec.Vec;
import water.parser.ParseDataset;
import water.runner.CloudSize;
import water.runner.H2ORunner;
import water.test.util.ConfusionMatrixUtils;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.*;
@RunWith(H2ORunner.class)
@CloudSize(1)
public class RuleFitTest extends TestUtil {
@Test
public void testBestPracticeExampleWithoutScope() {
RuleFitModel rfModel = null;
GLMModel glmModel = null;
Frame fr = null, fr2 = null, fr3 = null;
try {
fr = parse_test_file("./smalldata/gbm_test/titanic.csv");
String responseColumnName = "survived";
asFactor(fr, responseColumnName);
asFactor(fr, "pclass");
fr.remove("name").remove();
fr.remove("ticket").remove();
fr.remove("cabin").remove();
fr.remove("embarked").remove();
fr.remove("boat").remove();
fr.remove("body").remove();
fr.remove("home.dest").remove();
DKV.put(fr);
RuleFitModel.RuleFitParameters params = new RuleFitModel.RuleFitParameters();
params._seed = 1234;
params._train = fr._key;
params._response_column = responseColumnName;
params._max_num_rules = 100;
params._model_type = RuleFitModel.ModelType.RULES;
params._distribution = DistributionFamily.bernoulli;
params._min_rule_length = 1;
params._max_rule_length = 10;
rfModel = new RuleFit(params).trainModel().get();
System.out.println("Intercept: \n" + rfModel._output._intercept[0]);
System.out.println(rfModel._output._rule_importance);
fr2 = rfModel.score(fr);
Assert.assertTrue(rfModel.testJavaScoring(fr,fr2,1e-4));
Vec predictions = fr2.vec("predict");
Vec data = fr.vec("survived");
ConfusionMatrix ruleFitConfusionMatrix = ConfusionMatrixUtils.buildCM(data, predictions);
// GLM to compare:
GLMModel.GLMParameters glmParameters = rfModel.glmModel._parms;
glmParameters._train = fr._key;
glmParameters._response_column = rfModel._parms._response_column;
glmModel = new GLM(glmParameters).trainModel().get();
fr3 = glmModel.score(fr);
predictions = fr3.vec("predict");
ConfusionMatrix glmConfusionMatrix = ConfusionMatrixUtils.buildCM(data, predictions);
System.out.println("RuleFit ACC: \n" + ruleFitConfusionMatrix.accuracy());
System.out.println("RuleFit specificity: \n" + ruleFitConfusionMatrix.specificity());
System.out.println("RuleFit sensitivity: \n" + ruleFitConfusionMatrix.recall());
assertEquals(ruleFitConfusionMatrix.accuracy(),0.7868601986249045,1e-4);
assertEquals(ruleFitConfusionMatrix.specificity(),0.8207663782447466,1e-4);
assertEquals(ruleFitConfusionMatrix.recall(),0.732,1e-4);
System.out.println("pure GLM ACC: \n" + glmConfusionMatrix.accuracy());
System.out.println("pure GLM specificity: \n" + glmConfusionMatrix.specificity());
System.out.println("pure GLM sensitivity: \n" + glmConfusionMatrix.recall());
assertEquals(glmConfusionMatrix.accuracy(),0.7815126050420168,1e-4);
assertEquals(glmConfusionMatrix.specificity(),0.8145859085290482,1e-4);
assertEquals(glmConfusionMatrix.recall(),0.728,1e-4);
ScoringInfo RuleFitScoringInfo = rfModel.glmModel.getScoringInfo()[0];
ScoringInfo GLMScoringInfo = glmModel.getScoringInfo()[0];
System.out.println("RuleFit MSE: " + RuleFitScoringInfo.scored_train._mse);
System.out.println("GLM MSE: " + GLMScoringInfo.scored_train._mse);
System.out.println("RuleFit r2: " + RuleFitScoringInfo.scored_train._r2);
System.out.println("GLM r2: " + GLMScoringInfo.scored_train._r2);
} finally {
if (fr != null) fr.remove();
if (fr2 != null) fr2.remove();
if (fr3 != null) fr3.remove();
if (rfModel != null) {
rfModel.remove();
}
if (glmModel != null) glmModel.remove();
}
}
@Test
public void testBestPracticeExampleWithLinearVariablesWithoutScope() {
// the same as above but uses rules + linear terms
RuleFitModel rfModel = null;
GLMModel glmModel = null;
Frame fr = null, fr2 = null, fr3 = null;
try {
fr = parse_test_file("./smalldata/gbm_test/titanic.csv");
String responseColumnName = "survived";
asFactor(fr, responseColumnName);
asFactor(fr, "pclass");
fr.remove("name").remove();
fr.remove("ticket").remove();
fr.remove("cabin").remove();
fr.remove("embarked").remove();
fr.remove("boat").remove();
fr.remove("body").remove();
fr.remove("home.dest").remove();
final Vec weightsVector = fr.anyVec().makeOnes(1)[0];
final String weightsColumnName = "weights";
fr.add(weightsColumnName, weightsVector);
DKV.put(fr);
RuleFitModel.RuleFitParameters params = new RuleFitModel.RuleFitParameters();
params._seed = 1234;
params._train = fr._key;
params._response_column = responseColumnName;
params._max_num_rules = 100;
params._model_type = RuleFitModel.ModelType.RULES_AND_LINEAR;
params._weights_column = "weights";
params._min_rule_length = 1;
params._max_rule_length = 7;
rfModel = new RuleFit(params).trainModel().get();
System.out.println("Intercept: \n" + rfModel._output._intercept[0]);
System.out.println(rfModel._output._rule_importance);
fr2 = rfModel.score(fr);
Assert.assertTrue(rfModel.testJavaScoring(fr,fr2,1e-4));
Vec predictions = fr2.vec("predict");
Vec data = fr.vec("survived");
ConfusionMatrix ruleFitConfusionMatrix = ConfusionMatrixUtils.buildCM(data, predictions);
// GLM to compare:
GLMModel.GLMParameters glmParameters = rfModel.glmModel._parms;
glmParameters._train = fr._key;
glmParameters._weights_column = rfModel._parms._weights_column;
glmParameters._response_column = rfModel._parms._response_column;
glmModel = new GLM(glmParameters).trainModel().get();
fr3 = glmModel.score(fr);
predictions = fr3.vec("predict");
ConfusionMatrix glmConfusionMatrix = ConfusionMatrixUtils.buildCM(data, predictions);
System.out.println("RuleFit ACC: \n" + ruleFitConfusionMatrix.accuracy());
System.out.println("RuleFit specificity: \n" + ruleFitConfusionMatrix.specificity());
System.out.println("RuleFit sensitivity: \n" + ruleFitConfusionMatrix.recall());
assertEquals(ruleFitConfusionMatrix.accuracy(),0.7685255920550038,1e-4);
assertEquals(ruleFitConfusionMatrix.specificity(),0.761433868974042,1e-4);
assertEquals(ruleFitConfusionMatrix.recall(),0.78,1e-4);
System.out.println("pure GLM ACC: \n" + glmConfusionMatrix.accuracy());
System.out.println("pure GLM specificity: \n" + glmConfusionMatrix.specificity());
System.out.println("pure GLM sensitivity: \n" + glmConfusionMatrix.recall());
assertEquals(glmConfusionMatrix.accuracy(),0.7815126050420168,1e-4);
assertEquals(glmConfusionMatrix.specificity(),0.8145859085290482,1e-4);
assertEquals(glmConfusionMatrix.recall(),0.728,1e-4);
ScoringInfo RuleFitScoringInfo = rfModel.glmModel.getScoringInfo()[0];
ScoringInfo GLMScoringInfo = glmModel.getScoringInfo()[0];
System.out.println("RuleFit MSE: " + RuleFitScoringInfo.scored_train._mse);
System.out.println("GLM MSE: " + GLMScoringInfo.scored_train._mse);
System.out.println("RuleFit r2: " + RuleFitScoringInfo.scored_train._r2);
System.out.println("GLM r2: " + GLMScoringInfo.scored_train._r2);
} finally {
if (fr != null) fr.remove();
if (fr2 != null) fr2.remove();
if (fr3 != null) fr3.remove();
if (rfModel != null) {
rfModel.remove();
}
if (glmModel != null) glmModel.remove();
}
}
@Test
public void testBestPracticeExample() {
try {
Scope.enter();
final Frame fr = Scope.track(parse_test_file("./smalldata/gbm_test/titanic.csv"));
String responseColumnName = "survived";
asFactor(fr, responseColumnName);
asFactor(fr, "pclass");
fr.remove("name").remove();
fr.remove("ticket").remove();
fr.remove("cabin").remove();
fr.remove("embarked").remove();
fr.remove("boat").remove();
fr.remove("body").remove();
fr.remove("home.dest").remove();
DKV.put(fr);
RuleFitModel.RuleFitParameters params = new RuleFitModel.RuleFitParameters();
params._seed = 1234;
params._train = fr._key;
params._response_column = responseColumnName;
params._max_num_rules = 100;
params._model_type = RuleFitModel.ModelType.RULES;
params._distribution = DistributionFamily.bernoulli;
params._min_rule_length = 1;
params._max_rule_length = 10;
final RuleFitModel rfModel = new RuleFit(params).trainModel().get();
Scope.track_generic(rfModel);
System.out.println("Intercept: \n" + rfModel._output._intercept[0]);
System.out.println(rfModel._output._rule_importance);
final Frame fr2 = Scope.track(rfModel.score(fr));
Assert.assertTrue(rfModel.testJavaScoring(fr,fr2,1e-4));
Vec predictions = fr2.vec("predict");
Vec data = fr.vec("survived");
ConfusionMatrix ruleFitConfusionMatrix = ConfusionMatrixUtils.buildCM(data, predictions);
// GLM to compare:
GLMModel.GLMParameters glmParameters = rfModel.glmModel._parms;
glmParameters._train = fr._key;
glmParameters._response_column = rfModel._parms._response_column;
final GLMModel glmModel = new GLM(glmParameters).trainModel().get();
Scope.track_generic(glmModel);
final Frame fr3 = Scope.track(glmModel.score(fr));
predictions = fr3.vec("predict");
ConfusionMatrix glmConfusionMatrix = ConfusionMatrixUtils.buildCM(data, predictions);
System.out.println("RuleFit ACC: \n" + ruleFitConfusionMatrix.accuracy());
System.out.println("RuleFit specificity: \n" + ruleFitConfusionMatrix.specificity());
System.out.println("RuleFit sensitivity: \n" + ruleFitConfusionMatrix.recall());
assertEquals(ruleFitConfusionMatrix.accuracy(),0.7868601986249045,1e-4);
assertEquals(ruleFitConfusionMatrix.specificity(),0.8207663782447466,1e-4);
assertEquals(ruleFitConfusionMatrix.recall(),0.732,1e-4);
System.out.println("pure GLM ACC: \n" + glmConfusionMatrix.accuracy());
System.out.println("pure GLM specificity: \n" + glmConfusionMatrix.specificity());
System.out.println("pure GLM sensitivity: \n" + glmConfusionMatrix.recall());
assertEquals(glmConfusionMatrix.accuracy(),0.7815126050420168,1e-4);
assertEquals(glmConfusionMatrix.specificity(),0.8145859085290482,1e-4);
assertEquals(glmConfusionMatrix.recall(),0.728,1e-4);
ScoringInfo RuleFitScoringInfo = rfModel.glmModel.getScoringInfo()[0];
ScoringInfo GLMScoringInfo = glmModel.getScoringInfo()[0];
System.out.println("RuleFit MSE: " + RuleFitScoringInfo.scored_train._mse);
System.out.println("GLM MSE: " + GLMScoringInfo.scored_train._mse);
System.out.println("RuleFit r2: " + RuleFitScoringInfo.scored_train._r2);
System.out.println("GLM r2: " + GLMScoringInfo.scored_train._r2);
System.out.println("RuleFit AUC:" + rfModel.auc());
System.out.println("GLM AUC:" + glmModel.auc());
System.out.println("RuleFit logloss:" + rfModel.logloss());
System.out.println("GLM logloss:" + glmModel.logloss());
} finally {
Scope.exit();
}
}
@Test
public void testBestPracticeExampleWithLinearVariables() {
// the same as above but uses rules + linear terms
try {
Scope.enter();
final Frame fr = Scope.track(parse_test_file("./smalldata/gbm_test/titanic.csv"));
String responseColumnName = "survived";
asFactor(fr, responseColumnName);
asFactor(fr, "pclass");
fr.remove("name").remove();
fr.remove("ticket").remove();
fr.remove("cabin").remove();
fr.remove("embarked").remove();
fr.remove("boat").remove();
fr.remove("body").remove();
fr.remove("home.dest").remove();
final Vec weightsVector = Vec.makeOne(fr.numRows());
final String weightsColumnName = "weights";
fr.add(weightsColumnName, weightsVector);
DKV.put(fr);
RuleFitModel.RuleFitParameters params = new RuleFitModel.RuleFitParameters();
params._seed = 1234;
params._train = fr._key;
params._response_column = responseColumnName;
params._max_num_rules = 100;
params._model_type = RuleFitModel.ModelType.RULES_AND_LINEAR;
params._weights_column = "weights";
params._min_rule_length = 1;
params._max_rule_length = 10;
final RuleFitModel rfModel = new RuleFit(params).trainModel().get();
Scope.track_generic(rfModel);
System.out.println("Intercept: \n" + rfModel._output._intercept[0]);
System.out.println(rfModel._output._rule_importance);
final Frame fr2 = Scope.track(rfModel.score(fr));
Assert.assertTrue(rfModel.testJavaScoring(fr,fr2,1e-4));
Vec predictions = fr2.vec("predict");
Vec data = fr.vec("survived");
ConfusionMatrix ruleFitConfusionMatrix = ConfusionMatrixUtils.buildCM(data, predictions);
// GLM to compare:
GLMModel.GLMParameters glmParameters = rfModel.glmModel._parms;
glmParameters._train = fr._key;
glmParameters._weights_column = rfModel._parms._weights_column;
glmParameters._response_column = rfModel._parms._response_column;
final GLMModel glmModel = new GLM(glmParameters).trainModel().get();
Scope.track_generic(glmModel);
final Frame fr3 = Scope.track(glmModel.score(fr));
predictions = fr3.vec("predict");
ConfusionMatrix glmConfusionMatrix = ConfusionMatrixUtils.buildCM(data, predictions);
System.out.println("RuleFit ACC: \n" + ruleFitConfusionMatrix.accuracy());
System.out.println("RuleFit specificity: \n" + ruleFitConfusionMatrix.specificity());
System.out.println("RuleFit sensitivity: \n" + ruleFitConfusionMatrix.recall());
assertEquals(ruleFitConfusionMatrix.accuracy(),0.7685255920550038,1e-4);
assertEquals(ruleFitConfusionMatrix.specificity(),0.761433868974042,1e-4);
assertEquals(ruleFitConfusionMatrix.recall(),0.78,1e-4);
System.out.println("pure GLM ACC: \n" + glmConfusionMatrix.accuracy());
System.out.println("pure GLM specificity: \n" + glmConfusionMatrix.specificity());
System.out.println("pure GLM sensitivity: \n" + glmConfusionMatrix.recall());
assertEquals(glmConfusionMatrix.accuracy(),0.7815126050420168,1e-4);
assertEquals(glmConfusionMatrix.specificity(),0.8145859085290482,1e-4);
assertEquals(glmConfusionMatrix.recall(),0.728,1e-4);
ScoringInfo RuleFitScoringInfo = rfModel.glmModel.getScoringInfo()[0];
ScoringInfo GLMScoringInfo = glmModel.getScoringInfo()[0];
System.out.println("RuleFit MSE: " + RuleFitScoringInfo.scored_train._mse);
System.out.println("GLM MSE: " + GLMScoringInfo.scored_train._mse);
System.out.println("RuleFit r2: " + RuleFitScoringInfo.scored_train._r2);
System.out.println("GLM r2: " + GLMScoringInfo.scored_train._r2);
System.out.println("RuleFit AUC:" + rfModel.auc());
System.out.println("GLM AUC:" + glmModel.auc());
System.out.println("RuleFit logloss:" + rfModel.logloss());
System.out.println("GLM logloss:" + glmModel.logloss());
} finally {
Scope.exit();
}
}
@Test
public void testCarsRules() {
try {
Scope.enter();
final Frame fr = Scope.track(parse_test_file("./smalldata/junit/cars.csv"));
RuleFitModel.RuleFitParameters params = new RuleFitModel.RuleFitParameters();
params._seed = 1234;
params._response_column = "power (hp)";
params._ignored_columns = new String[]{"name"};
params._train = fr._key;
params._max_num_rules = 200;
params._max_rule_length = 5;
params._model_type = RuleFitModel.ModelType.RULES;
params._min_rule_length = 1;
RuleFitModel model = new RuleFit( params).trainModel().get();
Scope.track_generic(model);
System.out.println("Intercept: \n" + model._output._intercept[0]);
System.out.println(model._output._rule_importance);
final Frame fr2 = Scope.track(model.score(fr));
double[] expectedCoeffs = new double[] {13.50732, 8.37949, 8.33540, 7.78257, -7.57849, 7.51095, 5.65917, -5.59525, -4.04595, -3.73260, -3.66489,
-3.42019, -3.15852, -2.35430, -2.21467, 1.44047, -1.21574, -1.14403, -0.69578, -0.65761, -0.60060, -0.51955, 0.31480, -0.24659, -0.19722,
0.19242, -0.03043, -0.02091, 0.01179, 0.00583, 0.00102, 7.412075457645576E-4, -5.431219267171002E-4};
String[] expectedVars = new String[] {"M0T0N4", "M1T25N9", "M1T48N8", "M1T28N9", "M1T13N8", "M1T18N8",
"M1T26N8", "M1T6N8", "M1T4N10", "M2T30N15", "M1T0N7", "M2T36N15", "M1T36N7", "M1T14N7", "M1T1N9",
"M0T1N3", "M1T2N10", "M3T13N36", "M1T26N9", "M1T20N9", "M1T33N9", "M2T38N17", "M0T11N4",
"M1T5N7", "M0T0N3", "M0T18N3", "M0T1N4", "M1T7N7", "M0T26N3", "M1T3N9", "M0T22N4", "M0T27N4",
"M0T11N3"};
Set<String> zeroVars = new HashSet<>(Arrays.asList("M1T37N9", "M0T14N4", "M1T38N9", "M1T7N9", "M0T4N3", "M1T43N9"));
final double coefDelta = 1e-4;
for (int i = 0; i < expectedVars.length; i++) {
assertEquals(expectedCoeffs[i], (double) model._output._rule_importance.get(i,1),coefDelta);
assertEquals(expectedVars[i], model._output._rule_importance.get(i,0));
}
// zero-coef vars can be in any order (it doesn't make sense to compare order if it is bellow the delta precision)
for (int i = expectedVars.length; i < model._output._rule_importance.getRowDim(); i++) {
assertEquals(0, (double) model._output._rule_importance.get(i,1),coefDelta);
assertTrue(zeroVars.contains((String) model._output._rule_importance.get(i,0)));
}
GLMModel.GLMParameters glmParameters = model.glmModel._parms;
glmParameters._train = fr._key;
glmParameters._response_column = model._parms._response_column;
final GLMModel glmModel = new GLM(glmParameters).trainModel().get();
Scope.track_generic(glmModel);
Scope.track(glmModel.score(fr));
Assert.assertTrue(model.testJavaScoring(fr,fr2,1e-4));
ScoringInfo RuleFitScoringInfo = model.glmModel.getScoringInfo()[0];
ScoringInfo GLMScoringInfo = glmModel.getScoringInfo()[0];
System.out.println("RuleFit MSE: " + RuleFitScoringInfo.scored_train._mse);
System.out.println("GLM MSE: " + GLMScoringInfo.scored_train._mse);
System.out.println("RuleFit r2: " + RuleFitScoringInfo.scored_train._r2);
System.out.println("GLM r2: " + GLMScoringInfo.scored_train._r2);
System.out.println("RuleFit RMSLE:" + model.rmsle());
System.out.println("GLM RMSLE:" + glmModel.rmsle());
} finally {
Scope.exit();
}
}
@Test
public void testCarsRulesAndLinear() {
// only linear variables are important in this case
try {
Scope.enter();
final Frame fr = Scope.track(parse_test_file( "./smalldata/junit/cars.csv"));
RuleFitModel.RuleFitParameters params = new RuleFitModel.RuleFitParameters();
params._seed = 1234;
params._response_column = "power (hp)";
params._ignored_columns = new String[]{"name"};
params._train = fr._key;
params._max_num_rules = 200;
params._max_rule_length = 5;
params._model_type = RuleFitModel.ModelType.RULES_AND_LINEAR;
params._distribution = DistributionFamily.gaussian;
params._min_rule_length = 1;
final RuleFitModel model = new RuleFit(params).trainModel().get();
Scope.track_generic(model);
System.out.println("Intercept: \n" + model._output._intercept[0]);
System.out.println(model._output._rule_importance);
double[] expectedCoeffs = new double[] {-3.76823, -0.12718, 0.11265, -0.08923, 0.01601};
String[] expectedVars = new String[] {"linear.0-60 mph (s)", "linear.economy (mpg)", "linear.displacement (cc)", "linear.year", "linear.weight (lb)"};
for (int i = 0; i < model._output._rule_importance.getRowDim(); i++) {
assertEquals(expectedCoeffs[i], (double) model._output._rule_importance.get(i,1),1e-4);
assertEquals(expectedVars[i], model._output._rule_importance.get(i,0));
}
final Frame scoredByRF = Scope.track(model.score(fr));
Vec RFpredictions = scoredByRF.vec("predict");
GLMModel.GLMParameters glmParameters = model.glmModel._parms;
glmParameters._train = fr._key;
glmParameters._response_column = model._parms._response_column;
final GLMModel glmModel = new GLM(glmParameters).trainModel().get();
Scope.track_generic(glmModel);
final Frame scoredByGLM = Scope.track(glmModel.score(fr));
Vec GLMpredictions = scoredByGLM.vec("predict");
Assert.assertTrue(model.testJavaScoring(fr,scoredByRF,1e-4));
// should be equal because only linear terms were important during RF training
assertVecEquals(GLMpredictions, RFpredictions, 1e-4);
ScoringInfo RuleFitScoringInfo = model.glmModel.getScoringInfo()[0];
ScoringInfo GLMScoringInfo = glmModel.getScoringInfo()[0];
System.out.println("RuleFit MSE: " + RuleFitScoringInfo.scored_train._mse);
System.out.println("GLM MSE: " + GLMScoringInfo.scored_train._mse);
System.out.println("RuleFit r2: " + RuleFitScoringInfo.scored_train._r2);
System.out.println("GLM r2: " + GLMScoringInfo.scored_train._r2);
} finally {
Scope.exit();
}
}
@Test
public void testCarsLongRules() {
try {
Scope.enter();
final Frame fr = Scope.track(parse_test_file("./smalldata/junit/cars.csv"));
RuleFitModel.RuleFitParameters params = new RuleFitModel.RuleFitParameters();
params._seed = 1234;
params._response_column = "power (hp)";
params._ignored_columns = new String[]{"name"};
params._train = fr._key;
params._max_num_rules = 200;
params._max_rule_length = 10;
params._model_type = RuleFitModel.ModelType.RULES_AND_LINEAR;
params._min_rule_length = 1;
final RuleFitModel model = new RuleFit(params).trainModel().get();
Scope.track_generic(model);
System.out.println("Intercept: \n" + model._output._intercept[0]);
System.out.println(model._output._rule_importance);
final Frame fr2 = Scope.track(model.score(fr));
double[] expectedCoeffs = new double[] {-3.76824, -0.12718, 0.11265, -0.08923, 0.01601};
String[] expectedVars = new String[] {"linear.0-60 mph (s)", "linear.economy (mpg)", "linear.displacement (cc)", "linear.year", "linear.weight (lb)"};
for (int i = 0; i < model._output._rule_importance.getRowDim(); i++) {
assertEquals(expectedCoeffs[i], (double) model._output._rule_importance.get(i,1),1e-4);
assertEquals(expectedVars[i], model._output._rule_importance.get(i,0));
}
Assert.assertTrue(model.testJavaScoring(fr, fr2,1e-4));
GLMModel.GLMParameters glmParameters = model.glmModel._parms;
glmParameters._train = fr._key;
glmParameters._response_column = model._parms._response_column;
final GLMModel glmModel = new GLM(glmParameters).trainModel().get();
Scope.track_generic(glmModel);
Scope.track(glmModel.score(fr));
ScoringInfo RuleFitScoringInfo = model.glmModel.getScoringInfo()[0];
ScoringInfo GLMScoringInfo = glmModel.getScoringInfo()[0];
System.out.println("RuleFit MSE: " + RuleFitScoringInfo.scored_train._mse);
System.out.println("GLM MSE: " + GLMScoringInfo.scored_train._mse);
System.out.println("RuleFit r2: " + RuleFitScoringInfo.scored_train._r2);
System.out.println("GLM r2: " + GLMScoringInfo.scored_train._r2);
} finally {
Scope.exit();
}
}
@Test
public void testBostonHousing() {
try {
Scope.enter();
final Frame fr = parse_test_file("./smalldata/gbm_test/BostonHousing.csv");
Scope.track(fr);
String responseColumnName = fr.lastVecName();
RuleFitModel.RuleFitParameters params = new RuleFitModel.RuleFitParameters();
params._seed = 12345;
params._train = fr._key;
params._model_type = RuleFitModel.ModelType.RULES;
params._response_column = responseColumnName;
params._min_rule_length = 1;
params._max_rule_length = 10;
final RuleFitModel rfModel = new RuleFit(params).trainModel().get();
Scope.track_generic(rfModel);
System.out.println("Intercept: \n" + rfModel._output._intercept[0]);
System.out.println(rfModel._output._rule_importance);
final Frame fr2 = Scope.track(rfModel.score(fr));
Assert.assertTrue(rfModel.testJavaScoring(fr,fr2,1e-4));
// GLM to compare:
GLMModel.GLMParameters glmParameters = rfModel.glmModel._parms;
glmParameters._train = fr._key;
glmParameters._response_column = rfModel._parms._response_column;
final GLMModel glmModel = new GLM(glmParameters).trainModel().get();
Scope.track_generic(glmModel);
Scope.track(glmModel.score(fr));
ScoringInfo RuleFitScoringInfo = rfModel.glmModel.getScoringInfo()[0];
ScoringInfo GLMScoringInfo = glmModel.getScoringInfo()[0];
System.out.println("RuleFit MSE: " + RuleFitScoringInfo.scored_train._mse);
System.out.println("GLM MSE: " + GLMScoringInfo.scored_train._mse);
System.out.println("RuleFit r2: " + RuleFitScoringInfo.scored_train._r2);
System.out.println("GLM r2: " + GLMScoringInfo.scored_train._r2);
} finally {
Scope.exit();
}
}
@Test
public void testDiabetesWithWeights() {
try {
Scope.enter();
final Frame fr = parse_test_file("./smalldata/diabetes/diabetes_text_train.csv");
Scope.track(fr);
final Vec weightsVector = createRandomBinaryWeightsVec(fr.numRows(), 10);
final String weightsColumnName = "weights";
fr.add(weightsColumnName, weightsVector);
DKV.put(fr);
RuleFitModel.RuleFitParameters params = new RuleFitModel.RuleFitParameters();
params._seed = 12345;
params._train = fr._key;
params._model_type = RuleFitModel.ModelType.RULES_AND_LINEAR;
params._response_column = "diabetesMed";
params._weights_column = "weights";
params._max_num_rules = 200;
params._max_rule_length = 5;
params._min_rule_length = 1;
final RuleFitModel rfModel = new RuleFit(params).trainModel().get();
Scope.track_generic(rfModel);
System.out.println("Intercept: \n" + rfModel._output._intercept[0]);
System.out.println(rfModel._output._rule_importance);
final Frame fr2 = Scope.track(rfModel.score(fr));
Assert.assertTrue(rfModel.testJavaScoring(fr,fr2,1e-4));
// GLM to compare:
GLMModel.GLMParameters glmParameters = rfModel.glmModel._parms;
glmParameters._train = fr._key;
glmParameters._weights_column = rfModel._parms._weights_column;
glmParameters._response_column = rfModel._parms._response_column;
final GLMModel glmModel = new GLM(glmParameters).trainModel().get();
Scope.track_generic(glmModel);
Scope.track(glmModel.score(fr));
ScoringInfo RuleFitScoringInfo = rfModel.glmModel.getScoringInfo()[0];
ScoringInfo GLMScoringInfo = glmModel.getScoringInfo()[0];
System.out.println("RuleFit MSE: " + RuleFitScoringInfo.scored_train._mse);
System.out.println("GLM MSE: " + GLMScoringInfo.scored_train._mse);
System.out.println("RuleFit r2: " + RuleFitScoringInfo.scored_train._r2);
System.out.println("GLM r2: " + GLMScoringInfo.scored_train._r2);
} finally {
Scope.exit();
}
}
@Test
public void testMulticlass() {
try {
Scope.enter();
final Frame fr = Scope.track(parse_test_file("smalldata/iris/iris_train.csv"));
RuleFitModel.RuleFitParameters params = new RuleFitModel.RuleFitParameters();
params._seed = 12345;
params._train = fr._key;
params._model_type = RuleFitModel.ModelType.RULES_AND_LINEAR;
params._response_column = "species";
final RuleFitModel rfModel = new RuleFit(params).trainModel().get();
Scope.track_generic(rfModel);
System.out.println("Intercept: \n" + rfModel._output._intercept[0]);
System.out.println(rfModel._output._rule_importance);
final Frame fr2 = Scope.track(rfModel.score(fr));
Assert.assertTrue(rfModel.testJavaScoring(fr,fr2,1e-4));
} finally {
Scope.exit();
}
}
@Test
public void testBadColsBug() {
try {
Scope.enter();
final Frame fr = Scope.track(parse_test_file("smalldata/rulefit/repro_bad_cols_bug.csv"));
RuleFitModel.RuleFitParameters params = new RuleFitModel.RuleFitParameters();
params._seed = 42;
params._train = fr._key;
params._model_type = RuleFitModel.ModelType.RULES_AND_LINEAR;
params._response_column = "target";
params._max_num_rules = 1000;
asFactor(fr, "target");
final RuleFitModel rfModel = new RuleFit(params).trainModel().get();
Scope.track_generic(rfModel);
System.out.println("Intercept: \n" + rfModel._output._intercept[0]);
System.out.println(rfModel._output._rule_importance);
final Frame fr2 = Scope.track(rfModel.score(fr));
Assert.assertTrue(rfModel.testJavaScoring(fr,fr2,1e-4));
} finally {
Scope.exit();
}
}
}
|
package com.opengamma.masterdb.security;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import java.util.LinkedList;
import java.util.TimeZone;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import com.opengamma.core.common.Currency;
import com.opengamma.financial.security.equity.EquitySecurity;
import com.opengamma.financial.security.equity.GICSCode;
import com.opengamma.id.Identifier;
import com.opengamma.id.IdentifierBundle;
import com.opengamma.master.security.SecurityDocument;
import com.opengamma.masterdb.DbMasterTestUtils;
import com.opengamma.util.test.DBTest;
/**
* Test DbSecurityMaster.
*/
public class DbSecurityMasterTest extends DBTest {
private static final Logger s_logger = LoggerFactory.getLogger(DbSecurityMasterTest.class);
private DbSecurityMaster _secMaster;
public DbSecurityMasterTest(String databaseType, String databaseVersion) {
super(databaseType, databaseVersion);
s_logger.info("running testcases for {}", databaseType);
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}
@Before
public void setUp() throws Exception {
super.setUp();
ConfigurableApplicationContext context = DbMasterTestUtils.getContext(getDatabaseType());
_secMaster = (DbSecurityMaster) context.getBean(getDatabaseType() + "DbSecurityMaster");
}
@After
public void tearDown() throws Exception {
super.tearDown();
_secMaster = null;
}
@Test
public void test_basics() throws Exception {
assertNotNull(_secMaster);
assertEquals(true, _secMaster.getIdentifierScheme().equals("DbSec"));
assertNotNull(_secMaster.getDbSource());
assertNotNull(_secMaster.getTimeSource());
assertNotNull(_secMaster.getWorkers());
}
@Test
public void test_equity() throws Exception {
EquitySecurity sec = new EquitySecurity("London", "LON", "OpenGamma Ltd", Currency.getInstance("GBP"));
sec.setName("OpenGamma");
sec.setGicsCode(GICSCode.getInstance(2));
sec.setShortName("OG");
sec.setIdentifiers(IdentifierBundle.of(Identifier.of("Test", "OG")));
SecurityDocument addDoc = new SecurityDocument(sec);
SecurityDocument added = _secMaster.add(addDoc);
SecurityDocument loaded = _secMaster.get(added.getUniqueId());
assertEquals(added, loaded);
}
@Ignore("Test fails because of a known issue")
@Test
public void test_concurrentModification() {
final AtomicBoolean exceptionOccurred = new AtomicBoolean();
Runnable task = new Runnable() {
@Override
public void run() {
try {
test_equity();
} catch (Throwable t) {
exceptionOccurred.set(true);
s_logger.error("Error running task", t);
}
}
};
// 5 threads for plenty of concurrent activity
ExecutorService executor = Executors.newFixedThreadPool(5);
// 10 security inserts is always enough to produce a duplicate key exception
LinkedList<Future<?>> futures = new LinkedList<Future<?>>();
for (int i = 0; i < 10; i++) {
futures.add(executor.submit(task));
}
while (!futures.isEmpty()) {
Future<?> future = futures.poll();
try {
future.get();
} catch (Throwable t) {
s_logger.error("Exception waiting for task to complete", t);
}
}
assertFalse(exceptionOccurred.get());
}
@Test
public void test_toString() {
assertEquals("DbSecurityMaster[DbSec]", _secMaster.toString());
}
}
|
package com.netflix.ribbonclientextensions;
import static org.junit.Assert.*;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.reactivex.netty.protocol.http.client.HttpClient;
import io.reactivex.netty.protocol.http.client.HttpClientResponse;
import org.junit.Test;
import rx.Observable;
import rx.functions.Action0;
import rx.functions.Action1;
import com.google.common.collect.Lists;
import com.google.mockwebserver.MockResponse;
import com.google.mockwebserver.MockWebServer;
import com.netflix.client.config.DefaultClientConfigImpl;
import com.netflix.client.config.IClientConfigKey;
import com.netflix.client.netty.RibbonTransport;
import com.netflix.hystrix.HystrixObservableCommand;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.LoadBalancerBuilder;
import com.netflix.loadbalancer.Server;
import com.netflix.ribbonclientextensions.http.HttpRequestTemplate;
import com.netflix.ribbonclientextensions.hystrix.FallbackHandler;
public class RibbonTest {
@Test
public void testCommand() throws IOException {
// LogManager.getRootLogger().setLevel((Level)Level.DEBUG);
MockWebServer server = new MockWebServer();
String content = "Hello world";
server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-type", "text/plain")
.setBody(content));
server.play();
ILoadBalancer lb = LoadBalancerBuilder.newBuilder().buildFixedServerListLoadBalancer(Lists.newArrayList(new Server("localhost", server.getPort())));
HttpClient<ByteBuf, ByteBuf> httpClient = RibbonTransport.newHttpClient(lb, DefaultClientConfigImpl.getClientConfigWithDefaultValues());
HttpRequestTemplate<ByteBuf, ByteBuf> template = Ribbon.newHttpRequestTemplate("test", httpClient);
RibbonRequest<ByteBuf> request = template.withUri("/").requestBuilder().build();
String result = request.execute().toString(Charset.defaultCharset());
assertEquals(content, result);
}
@Test
public void testTransformer() throws IOException, InterruptedException {
// LogManager.getRootLogger().setLevel((Level)Level.DEBUG);
MockWebServer server = new MockWebServer();
String content = "Hello world";
server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-type", "text/plain")
.setBody(content));
server.play();
ILoadBalancer lb = LoadBalancerBuilder.newBuilder().buildFixedServerListLoadBalancer(Lists.newArrayList(new Server("localhost", server.getPort())));
HttpClient<ByteBuf, ByteBuf> httpClient = RibbonTransport.newHttpClient(lb, DefaultClientConfigImpl.getClientConfigWithDefaultValues());
HttpRequestTemplate<ByteBuf, ByteBuf> template = Ribbon.newHttpRequestTemplate("test", httpClient)
.withNetworkResponseTransformer(new ResponseTransformer<HttpClientResponse<ByteBuf>>() {
@Override
public HttpClientResponse<ByteBuf> call(HttpClientResponse<ByteBuf> t1) {
throw new HystrixBadRequestException("error", new IllegalArgumentException());
}
});
RibbonRequest<ByteBuf> request = template.withUri("/").requestBuilder().build();
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
request.toObservable().subscribe(new Action1<ByteBuf>() {
@Override
public void call(ByteBuf t1) {
}
},
new Action1<Throwable>(){
@Override
public void call(Throwable t1) {
error.set(t1);
latch.countDown();
}
},
new Action0() {
@Override
public void call() {
// TODO Auto-generated method stub
}
});
latch.await();
assertTrue(error.get() instanceof HystrixBadRequestException);
assertTrue(error.get().getCause() instanceof IllegalArgumentException);
}
@Test
public void testFallback() throws IOException {
// LogManager.getRootLogger().setLevel((Level)Level.DEBUG);
ILoadBalancer lb = LoadBalancerBuilder.newBuilder().buildFixedServerListLoadBalancer(Lists.newArrayList(new Server("localhost", 12345)));
HttpClient<ByteBuf, ByteBuf> httpClient = RibbonTransport.newHttpClient(lb,
DefaultClientConfigImpl.getClientConfigWithDefaultValues().setPropertyWithType(IClientConfigKey.CommonKeys.MaxAutoRetriesNextServer, 1));
HttpRequestTemplate<ByteBuf, ByteBuf> template = Ribbon.newHttpRequestTemplate("test", httpClient);
final String fallback = "fallback";
RibbonRequest<ByteBuf> request = template.withUri("/")
.withFallbackProvider(new FallbackHandler<ByteBuf>() {
@Override
public Observable<ByteBuf> call(HystrixObservableCommand<ByteBuf> t1) {
return Observable.just(Unpooled.buffer().writeBytes(fallback.getBytes()));
}
})
.requestBuilder().build();
String result = request.execute().toString(Charset.defaultCharset());
// System.out.println(result);
assertEquals(fallback, result);
}
}
|
package org.noear.weed;
import org.noear.weed.cache.CacheUsing;
import org.noear.weed.cache.ICacheController;
import org.noear.weed.cache.ICacheService;
import org.noear.weed.ext.Act2;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
public interface IQuery extends ICacheController<IQuery> {
long getCount() throws SQLException;
Object getValue() throws SQLException;
<T> T getValue(T def) throws SQLException;
Variate getVariate() throws SQLException;
Variate getVariate(Act2<CacheUsing,Variate> cacheCondition) throws SQLException;
<T extends IBinder> T getItem(T model) throws SQLException;
<T extends IBinder> T getItem(T model, Act2<CacheUsing, T> cacheCondition) throws SQLException;
<T extends IBinder> List<T> getList(T model) throws SQLException;
<T extends IBinder> List<T> getList(T model, Act2<CacheUsing, List<T>> cacheCondition) throws SQLException;
<T> T getItem(Class<T> cls) throws SQLException;
<T> T getItem(Class<T> cls,Act2<CacheUsing, T> cacheCondition) throws SQLException;
<T> List<T> getList(Class<T> cls) throws SQLException;
<T> List<T> getList(Class<T> cls,Act2<CacheUsing, List<T>> cacheCondition) throws SQLException;
DataList getDataList() throws SQLException;
DataList getDataList(Act2<CacheUsing, DataList> cacheCondition) throws SQLException;
DataItem getDataItem() throws SQLException;
DataItem getDataItem(Act2<CacheUsing, DataItem> cacheCondition) throws SQLException;
List<Map<String,Object>> getMapList() throws SQLException;
Map<String,Object> getMap() throws SQLException;
<T> List<T> getArray(String column) throws SQLException;
<T> List<T> getArray(int columnIndex) throws SQLException;
}
|
package edu.rpi.phil.legup.newgui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.GroupLayout;
import java.awt.Insets;
import java.io.File;
import java.io.FilenameFilter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import java.util.LinkedList;
import javax.swing.AbstractButton;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JDesktopPane;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.JTextArea;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
import edu.rpi.phil.legup.BoardState;
import edu.rpi.phil.legup.Legup;
import edu.rpi.phil.legup.PuzzleModule;
import edu.rpi.phil.legup.PuzzleGeneration;
import edu.rpi.phil.legup.Selection;
import edu.rpi.phil.legup.Submission;
import edu.rpi.phil.legup.saveable.SaveableProof;
import edu.rpi.phil.legup.ILegupGui;
//import edu.rpi.phil.legup.newgui.TreeFrame;
import javax.swing.plaf.ToolBarUI;
import javax.swing.plaf.basic.BasicToolBarUI;
import java.awt.Color;
import java.awt.Point;
import java.io.IOException;
import javax.swing.BorderFactory;
//import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
public class LEGUP_Gui extends JFrame implements ActionListener, TreeSelectionListener, ILegupGui, WindowListener
{
private static final long serialVersionUID = -2304281047341398965L;
/**
* Daniel Ploch - Added 09/25/2009
* Integrated variables for different Proof Modes in LEGUP
* The PROOF_CONFIG environment variable stores the settings as bitwise flags
*
* AllOW_JUST: Allows the user to use the Justification Panel to verify answers.
* ALLOW_HINTS: Allow the user to query the tutor for hints (no "Oops - I gave you the answer" step)
* ALLOW_DEFAPP: Allow the user to use default-applications (have the AI auto-infer parts of the solution)
* ALLOW_FULLAI: Gives user full access to the AI menu, including use of the AI solving algorithm (includes "Oops" tutor step).
* REQ_STEP_JUST: Requires the user to justify (correct not necessary) the latest transition before making a new one (safety/training device)
* IMD_FEEDBACK: Shows green and red arrows in Proof-Tree for correct/incorrect justifications in real-time.
* INTERN_RO: Internal nodes (in the Proof-Tree) are Read-Only, only leaf nodes can be modified. Ideal safety feature
* AUTO_JUST: AI automatically justifies moves as you make them.
*/
private static int CONFIG_INDEX = 0;
public static final int ALLOW_HINTS = 1;
public static final int ALLOW_DEFAPP = 2;
public static final int ALLOW_FULLAI = 4;
public static final int ALLOW_JUST = 8;
public static final int REQ_STEP_JUST = 16;
public static final int IMD_FEEDBACK = 32;
public static final int INTERN_RO = 64;
public static final int AUTO_JUST = 128;
public static boolean profFlag( int flag ){
return !((PROF_FLAGS[CONFIG_INDEX] & flag) == 0);
}
private static final String[] PROFILES = {
"No Assistance",
"Rigorous Proof",
"Casual Proof",
"Assisted Proof",
"Guided Proof",
"Training-Wheels Proof",
"No Restrictions" };
private static final int[] PROF_FLAGS = {
0,
ALLOW_JUST | REQ_STEP_JUST,
ALLOW_JUST,
ALLOW_HINTS | ALLOW_JUST | AUTO_JUST,
ALLOW_HINTS | ALLOW_JUST | REQ_STEP_JUST,
ALLOW_HINTS | ALLOW_DEFAPP | ALLOW_JUST | IMD_FEEDBACK | INTERN_RO,
ALLOW_HINTS | ALLOW_DEFAPP | ALLOW_FULLAI | ALLOW_JUST };
PickGameDialog pgd = null;
Legup legupMain = null;
private final FileDialog fileChooser;
private edu.rpi.phil.legup.AI myAI = new edu.rpi.phil.legup.AI();
/*** TOOLBAR CONSTANTS ***/
private static final int TOOLBAR_NEW = 0;
private static final int TOOLBAR_OPEN = 1;
private static final int TOOLBAR_SAVE = 2;
private static final int TOOLBAR_UNDO = 3;
private static final int TOOLBAR_REDO = 4;
private static final int TOOLBAR_CONSOLE = 5;
private static final int TOOLBAR_HINT = 6;
private static final int TOOLBAR_CHECK = 7;
private static final int TOOLBAR_SUBMIT = 8;
private static final int TOOLBAR_DIRECTIONS = 9;
private static final int TOOLBAR_ZOOMIN = 10;
private static final int TOOLBAR_ZOOMOUT = 11;
private static final int TOOLBAR_ZOOMRESET = 12;
private static final int TOOLBAR_ZOOMFIT = 13;
private static final int TOOLBAR_ANNOTATIONS = 14;
final static String[] toolBarNames =
{
"New",
"Open",
"Save",
"Undo",
"Redo",
"Console",
"Hint",
"Check",
"Submit",
"Directions",
"Zoom In",
"Zoom Out",
"Normal Zoom",
"Best Fit",
"Annotations"
};
AbstractButton[] toolBarButtons =
{
new JButton(toolBarNames[0], new ImageIcon("images/" + toolBarNames[0] + ".png")),
new JButton(toolBarNames[1], new ImageIcon("images/" + toolBarNames[1] + ".png")),
new JButton(toolBarNames[2], new ImageIcon("images/" + toolBarNames[2] + ".png")),
new JButton(toolBarNames[3], new ImageIcon("images/" + toolBarNames[3] + ".png")),
new JButton(toolBarNames[4], new ImageIcon("images/" + toolBarNames[4] + ".png")),
new JButton(toolBarNames[5], new ImageIcon("images/" + toolBarNames[5] + ".png")),
new JButton(toolBarNames[6], new ImageIcon("images/" + toolBarNames[6] + ".png")),
new JButton(toolBarNames[7], new ImageIcon("images/" + toolBarNames[7] + ".png")), //Check
new JButton(toolBarNames[8], new ImageIcon("images/" + toolBarNames[8] + ".png")), //Submit
new JButton(toolBarNames[9], new ImageIcon("images/" + toolBarNames[9] + ".png")), //Directions
new JButton(/*toolBarNames[10],*/ new ImageIcon("images/" + toolBarNames[10] + ".png")),
new JButton(/*toolBarNames[11],*/ new ImageIcon("images/" + toolBarNames[11] + ".png")),
new JButton(/*toolBarNames[12],*/ new ImageIcon("images/" + toolBarNames[12] + ".png")),
new JButton(/*toolBarNames[13],*/ new ImageIcon("images/" + toolBarNames[13] + ".png")),
new JButton(toolBarNames[14], new ImageIcon("images/" + toolBarNames[14] + ".png")) //Toggle annotations
};
final static int[] toolbarSeperatorBefore =
{
3, 5, 9, 10
};
public void repaintBoard()
{
if (getBoard() != null) getBoard().boardDataChanged(null);
}
public LEGUP_Gui(Legup legupMain)
{
this.legupMain = legupMain;
legupMain.getSelections().addTreeSelectionListener(this);
setTitle("LEGUP");
setLayout( new BorderLayout() );
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setupMenu();
setupToolBar();
setupContent();
pack();
setVisible(true);
// Centers the window
setLocationRelativeTo( null );
fileChooser = new FileDialog(this);
}
// menubar related fields
private JMenuBar bar = new JMenuBar();
private JMenu file = new JMenu("File");
private JMenuItem newPuzzle = new JMenuItem("New Puzzle");
private JMenuItem genPuzzle = new JMenuItem("Puzzle Generators");
private JMenuItem openProof = new JMenuItem("Open LEGUP Proof");
private JMenuItem saveProof = new JMenuItem("Save LEGUP Proof");
private JMenuItem exit = new JMenuItem("Exit");
private JMenu edit = new JMenu("Edit");
private JMenuItem undo = new JMenuItem("Undo");
private JMenuItem redo = new JMenuItem("Redo");
// no entries yet
/* private JMenu view = new JMenu("View"); */
private JMenu proof = new JMenu("Proof");
private JCheckBoxMenuItem allowDefault = new JCheckBoxMenuItem("Allow Default Rule Applications",false);
private JCheckBoxMenuItem caseRuleGen = new JCheckBoxMenuItem("Automatically generate cases for CaseRule",false);
public boolean autoGenCaseRules = false;
private JCheckBoxMenuItem imdFeedback = new JCheckBoxMenuItem("Provide immediate feedback",false);
public boolean imdFeedbackFlag = false;
private JMenu proofMode = new JMenu("Proof Mode");
private JCheckBoxMenuItem[] proofModeItems = new JCheckBoxMenuItem[PROF_FLAGS.length];
private JMenu AI = new JMenu("AI");
private JMenuItem Run = new JMenuItem("Run AI to completion");
private JMenuItem Step = new JMenuItem("Run AI one Step");
private JMenuItem Test = new JMenuItem("Test AI!");
private JMenuItem hint = new JMenuItem("Hint");
private JMenu help = new JMenu("Help");
// contains all the code to setup the menubar
private void setupMenu(){
bar.add(file);
file.add(newPuzzle);
newPuzzle.addActionListener(this);
newPuzzle.setAccelerator(KeyStroke.getKeyStroke('N',2));
file.add(genPuzzle);
genPuzzle.addActionListener(this);
file.addSeparator();
file.add(openProof);
openProof.addActionListener(this);
openProof.setAccelerator(KeyStroke.getKeyStroke('O',2));
file.add(saveProof);
saveProof.addActionListener(this);
saveProof.setAccelerator(KeyStroke.getKeyStroke('S',2));
file.addSeparator();
file.add(exit);
exit.addActionListener(this);
exit.setAccelerator(KeyStroke.getKeyStroke('Q',2));
bar.add(edit);
edit.add(undo);
undo.addActionListener(this);
undo.setAccelerator(KeyStroke.getKeyStroke('Z',2));
edit.add(redo);
redo.addActionListener(this);
redo.setAccelerator(KeyStroke.getKeyStroke('Y',2));
// no entries yet
/* bar.add(view); */
bar.add(proof);
proof.add(allowDefault);
allowDefault.addActionListener(this);
proof.add(caseRuleGen);
caseRuleGen.addActionListener(this);
caseRuleGen.setState(true);
proof.add(imdFeedback);
imdFeedback.addActionListener(this);
imdFeedback.setState(true);
/*proof.add(proofMode);
for (int i = 0; i < PROF_FLAGS.length; i++)
{
proofModeItems[i] = new JCheckBoxMenuItem(PROFILES[i], i == CONFIG_INDEX);
proofModeItems[i].addActionListener(this);
proofMode.add(proofModeItems[i]);
}*/
/*bar.add(AI);
AI.add(Step);
Step.addActionListener(this);
Step.setAccelerator(KeyStroke.getKeyStroke("F9"));
AI.add(Run);
Run.addActionListener(this);
Run.setAccelerator(KeyStroke.getKeyStroke("F10"));
AI.add(Test);
Test.addActionListener(this);
AI.add(hint);
hint.addActionListener(this);
hint.setAccelerator(KeyStroke.getKeyStroke('H',0));*/
bar.add(help);
setJMenuBar(bar);
this.addWindowListener(this);
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
System.out.println("listener initialized");
}
// toolbar related fields
private JToolBar toolBar;
// contains all the code to setup the toolbar
private void setupToolBar(){
toolBar = new JToolBar();
toolBar.setFloatable( false );
toolBar.setRollover( true );
for (int x = 0; x < toolBarButtons.length; ++x){
for (int y = 0; y < toolbarSeperatorBefore.length; ++y){
if (x == toolbarSeperatorBefore[y]){
toolBar.addSeparator();
}
}
toolBar.add(toolBarButtons[x]);
toolBarButtons[x].addActionListener(this);
toolBarButtons[x].setToolTipText(toolBarNames[x]);
// TODO text under icons
toolBarButtons[x].setVerticalTextPosition( SwingConstants.BOTTOM );
toolBarButtons[x].setHorizontalTextPosition( SwingConstants.CENTER );
}
// TODO disable buttons
toolBarButtons[TOOLBAR_SAVE].setEnabled(false);
toolBarButtons[TOOLBAR_UNDO].setEnabled(false);
toolBarButtons[TOOLBAR_REDO].setEnabled(false);
toolBarButtons[TOOLBAR_HINT].setEnabled(false);
toolBarButtons[TOOLBAR_CHECK].setEnabled(false);
toolBarButtons[TOOLBAR_SUBMIT].setEnabled(false);
toolBarButtons[TOOLBAR_DIRECTIONS].setEnabled(false);
toolBarButtons[TOOLBAR_ANNOTATIONS].setEnabled(false);
add( toolBar, BorderLayout.NORTH );
}
// TODO
private JustificationFrame justificationFrame;
private Tree tree;
public Tree getTree() {return tree;}
private Console console;
private Board board;
private TitledBorder boardBorder;
private JSplitPane test, test2;
public JustificationFrame getJustificationFrame()
{
return justificationFrame;//((JustificationFrame)test.getLeftComponent());
}
public Board getBoard()
{
return board;//((Board)test.getRightComponent());
}
private LinkedList<Board> boardStack = new LinkedList<Board>();
public void pushBoard(Board b)
{
b.setBorder(boardBorder);
boardStack.push(board);
int z1 = board.getZoom();
double z2 = ((double)z1) / 100;
b.zoomTo(z2);
b.getViewport().setViewPosition(board.getViewport().getViewPosition());
//b.zoomTo(board.getZoom());
board = b;
test.setRightComponent(b);
}
public void popBoard()// throws java.util.NoSuchElementException
{
Board b = boardStack.pop();
int z1 = board.getZoom();
double z2 = ((double)z1) / 100;
b.zoomTo(z2);
b.getViewport().setViewPosition(board.getViewport().getViewPosition());
//b.zoomTo(board.getZoom());
board = b;
test.setRightComponent(b);
}
// contains all the code to setup the main content
private void setupContent(){
JPanel consoleBox = new JPanel( new BorderLayout() );
JPanel treeBox = new JPanel( new BorderLayout() );
JPanel ruleBox = new JPanel( new BorderLayout() );
// TODO Console
console = new Console();
//consoleBox.add( console, BorderLayout.SOUTH );
// TODO experimental floating toolbar
//((BasicToolBarUI) console.getUI()).setFloatingLocation(500,500);
//((BasicToolBarUI) console.getUI()).setFloating(true, new Point(500,500));
// TODO
tree = new Tree( this );
//treeBox.add( tree, BorderLayout.SOUTH );
justificationFrame = new JustificationFrame( this );
//ruleBox.add( justificationFrame, BorderLayout.WEST );
board = new NormalBoard( this );
board.setPreferredSize( new Dimension( 600, 400 ) );
JPanel boardPanel = new JPanel( new BorderLayout() );
//boardPanel.add(board.pop);
//boardPanel.add( board );
//split pane fun :)
test = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, justificationFrame, board);
test2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, test, tree);
test.setPreferredSize(new Dimension(600, 400));
test2.setPreferredSize(new Dimension(600, 600));
//boardPanel.add(test);
boardPanel.add(test2);
//no more fun :(
boardBorder = BorderFactory.createTitledBorder("Board");
boardBorder.setTitleJustification(TitledBorder.CENTER);
board.setBorder(boardBorder);
ruleBox.add( boardPanel );
treeBox.add( ruleBox );
consoleBox.add( treeBox );
add( consoleBox );
//JLabel placeholder = new JLabel( "Nothing." );
//placeholder.setPreferredSize( new Dimension( 600, 400 ) );
//add( placeholder );
/*JPanel panel = new JPanel();
GroupLayout layout = new GroupLayout(panel);
panel.setLayout(layout);
tree = new Tree( this );
panel.add(tree);
justificationFrame = new JustificationFrame( this );
panel.add(tree);
board = new Board( this );
board.setPreferredSize( new Dimension( 600, 400 ) );
//JPanel boardPanel = new JPanel( new BorderLayout() );
//test = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, justificationFrame, board);
//test2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, test, tree);
//test.setPreferredSize(new Dimension(600, 400));
//test2.setPreferredSize(new Dimension(600, 600));
//boardPanel.add(test2);
TitledBorder title = BorderFactory.createTitledBorder("Board");
title.setTitleJustification(TitledBorder.CENTER);
board.setBorder(title);
panel.add(board);
layout.setHorizontalGroup( layout.createParallelGroup()
.addGroup(layout.createSequentialGroup()
.addComponent(justificationFrame)
.addComponent(board)
)
.addComponent(tree)
);
layout.setVerticalGroup( layout.createSequentialGroup()
.addGroup(layout.createParallelGroup()
.addComponent(justificationFrame)
.addComponent(board)
)
.addComponent(tree)
);
add(panel);*/
}
class proofFilter implements FilenameFilter
{
public boolean accept(File dir, String name)
{
System.out.println("proofFilter " + ((name.contains(".proof")) ? "accepts" : "rejects") + " \"" + name + "\"");
if(name.contains(".proof"))return true;
return false;
}
}
private void openProof()
{
if(Legup.getInstance().getInitialBoardState() != null){if(!noquit("opening a new proof?"))return;}
JFileChooser proofchooser = new JFileChooser("boards");
fileChooser.setMode(FileDialog.LOAD);
fileChooser.setTitle("Select Proof");
fileChooser.setVisible(true);
//proofFilter filter = new proofFilter();
//fileChooser.setFilenameFilter(filter);
String filename = fileChooser.getFile();
if (filename != null) // user didn't press cancel
{
filename = fileChooser.getDirectory() + filename;
if (!filename.toLowerCase().endsWith(".proof"))
{
JOptionPane.showMessageDialog(null,"File selected does not have the suffix \".proof\".");
return;
}
Legup.getInstance().loadProofFile(filename);
}
}
public void saveProof()
{
BoardState root = legupMain.getInitialBoardState();
if (root == null){return;}
fileChooser.setMode(FileDialog.SAVE);
fileChooser.setTitle("Select Proof");
fileChooser.setVisible(true);
//proofFilter filter = new proofFilter();
//fileChooser.setFilenameFilter(filter);
String filename = fileChooser.getFile();
if (filename != null) // user didn't pressed cancel
{
filename = fileChooser.getDirectory() + filename;
if (!filename.toLowerCase().endsWith(".proof"))
filename = filename + ".proof";
try {
SaveableProof.saveProof(root, filename);
getTree().modifiedSinceSave = false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void checkProof()
{
BoardState root = legupMain.getInitialBoardState();
boolean delayStatus = root.evalDelayStatus();
repaintAll();
PuzzleModule pm = legupMain.getPuzzleModule();
if (pm.checkProof(root) && delayStatus)
{
int confirm = JOptionPane.showConfirmDialog(null, "Congratulations! Your proof is correct. Would you like to submit?", "Proof Submission", JOptionPane.YES_NO_OPTION);
if (confirm == 0)
{
Submission submit = new Submission(root, true);
}
showStatus("Your proof is correct.", false);
}
else
{
String message = "";
if(root.getFinalState() != null)
{
if(!delayStatus)message += "\nThere are invalid steps, which have been colored red.";
if(!pm.checkProof(root))message += "\nThe board is not solved.";
}
else message += "There is not a unique non-condradictory leaf state. Incomplete case rules are pale green.";
showStatus(message, true);
}
}
private void submit()
{
BoardState root = legupMain.getInitialBoardState();
boolean delayStatus = root.evalDelayStatus();
repaintAll();
PuzzleModule pm = legupMain.getPuzzleModule();
if (pm.checkProof(root) && delayStatus)
{
// 0 means yes, 1 means no (Java's fault...)
int confirm = JOptionPane.showConfirmDialog(null, "Are you sure you wish to submit?", "Proof Submission", JOptionPane.YES_NO_OPTION);
if (confirm == 0)
{
Submission submit = new Submission(root, true);
}
}
else
{
JOptionPane.showConfirmDialog(null, "Your proof is incorrect! Are you sure you wish to submit?", "Proof Submission", JOptionPane.YES_NO_OPTION);
Submission submit = new Submission(root, false);
}
}
private void directions()
{
JOptionPane.showMessageDialog(null, "For ever move you make, you must provide a justification for it (located in the Rules panel).\n"
+ "While working on the puzzle, you may click on the \"Check\" button to test your proof for correctness.",
"Directions", JOptionPane.PLAIN_MESSAGE);
}
private void showAll() {
getBoard().initSize();
// TODO disable buttons
toolBarButtons[TOOLBAR_SAVE].setEnabled(true);
toolBarButtons[TOOLBAR_UNDO].setEnabled(false);
toolBarButtons[TOOLBAR_REDO].setEnabled(false);
toolBarButtons[TOOLBAR_HINT].setEnabled(true);
toolBarButtons[TOOLBAR_CHECK].setEnabled(true);
toolBarButtons[TOOLBAR_SUBMIT].setEnabled(true);
toolBarButtons[TOOLBAR_DIRECTIONS].setEnabled(true);
toolBarButtons[TOOLBAR_ANNOTATIONS].setEnabled(true);
this.pack();
}
private void repaintAll(){
getBoard().repaint();
getJustificationFrame().repaint();
tree.repaint();
}
/*
* ILegupGui interface methods
* @see edu.rpi.phil.legup.ILegupGui
*/
public void showStatus(String status, boolean error)
{
showStatus(status,error,1);
}
public void showStatus(String status, boolean error, int timer)
{
getTree().updateStatusTimer = timer;
getJustificationFrame().setStatus(!error,status);
// TODO console
console.println( "Status: " + status );
}
public void errorEncountered(String error)
{
JOptionPane.showMessageDialog(null,error);
}
public void promptPuzzle(){
if(Legup.getInstance().getInitialBoardState() != null){
if(!noquit("opening a new puzzle?")) return;
}
JFileChooser newPuzzle = new JFileChooser("boards");
FileNameExtensionFilter filetype = new FileNameExtensionFilter( "LEGUP Puzzles", "xml" );
newPuzzle.setFileFilter( filetype );
if( newPuzzle.showOpenDialog(this) == JFileChooser.APPROVE_OPTION ){
legupMain.loadBoardFile( newPuzzle.getSelectedFile().getAbsolutePath() );
PuzzleModule pm = legupMain.getPuzzleModule();
if( pm != null ){
getJustificationFrame().setJustifications(pm);
// AI setup
myAI.setBoard(pm);
}
// show them all
showAll();
} else {
//System.out.println("Cancel Pressed");
}
}
public void reloadGui()
{
getJustificationFrame().setJustifications(Legup.getInstance().getPuzzleModule());
getJustificationFrame().resetSize();
// AI setup
myAI.setBoard(Legup.getInstance().getPuzzleModule());
// show them all
showAll();
}
/*
* Events
*/
//ask to save current proof
public boolean noquit(String instr)
{
if(!getTree().modifiedSinceSave)return true;
String quest = "Would you like to save your proof before ";
quest += instr;
LEGUP_Gui curgui = Legup.getInstance().getGui();
//System.out.println("Attempting to save good sirs...");
Object[] options = {"Save Proof", "Do Not Save Proof", "Cancel"};
int n = JOptionPane.showOptionDialog(bar, quest, "Save", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
switch(n)
{
case JOptionPane.YES_OPTION:
curgui.saveProof();
return true;
case JOptionPane.NO_OPTION:
return true;
case JOptionPane.CANCEL_OPTION:
return false;
case JOptionPane.CLOSED_OPTION:
//pick an option!
return noquit(instr);
default:
return true;
}
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == newPuzzle || e.getSource() == toolBarButtons[TOOLBAR_NEW])
{
promptPuzzle();
}
else if (e.getSource() == openProof || e.getSource() == toolBarButtons[TOOLBAR_OPEN])
{
openProof();
int x = 0; //breakpoint
x = x + 1; //suppresses warnings of x not being used
}
else if (e.getSource() == saveProof || e.getSource() == toolBarButtons[TOOLBAR_SAVE])
{
saveProof();
}
else if (e.getSource() == genPuzzle)
{
PuzzleGeneratorDialog pgd = new PuzzleGeneratorDialog(this);
pgd.setVisible(true);
if (pgd.getChoice() == PuzzleGeneratorDialog.PUZZLE_CHOSEN)
{
PuzzleModule module = PuzzleGeneration.getModule(pgd.puzzleChosen());
BoardState puzzle = PuzzleGeneration.makePuzzle(pgd.puzzleChosen(), pgd.difficultyChosen(), this);
legupMain.initializeGeneratedPuzzle(module, puzzle);
getJustificationFrame().setJustifications(module);
// AI setup
myAI.setBoard(module);
// show them all
showAll();
}
}
else if (e.getSource() == exit)
{
System.exit(0);
}
else if (e.getSource() == undo || e.getSource() == toolBarButtons[TOOLBAR_UNDO])
{
getTree().undo();
resetUndoRedo();
//System.out.println("Undo!");
}
else if (e.getSource() == redo || e.getSource() == toolBarButtons[TOOLBAR_REDO])
{
getTree().redo();
resetUndoRedo();
//System.out.println("Redo!");
}
else if (e.getSource() == toolBarButtons[TOOLBAR_CONSOLE])
{
console.setVisible(!console.isVisible());
pack();
}
else if (e.getSource() == toolBarButtons[TOOLBAR_CHECK])
{
checkProof();
}
else if (e.getSource() == toolBarButtons[TOOLBAR_SUBMIT])
{
submit();
}
else if (e.getSource() == toolBarButtons[TOOLBAR_DIRECTIONS])
{
directions();
}
else if (e.getSource() == hint || e.getSource() == toolBarButtons[TOOLBAR_HINT])
{
// Is this really necessary? It's already being set when the puzzle loads...
//myAI.setBoard(Legup.getInstance().getPuzzleModule());
// TODO console
console.println("Tutor: " + myAI.findRuleApplication(Legup.getInstance().getSelections().getFirstSelection().getState()) );
}
else if (e.getSource() == toolBarButtons[TOOLBAR_ZOOMIN]){
// TODO - kueblc
/*/ DEBUG - Not actual actions!
((BasicToolBarUI) justificationFrame.getUI()).setFloatingLocation(500,500);
((BasicToolBarUI) justificationFrame.getUI()).setFloating(true, new Point(500,500));*/
getBoard().zoomIn();
}
else if (e.getSource() == toolBarButtons[TOOLBAR_ZOOMOUT]){
getBoard().zoomOut();
}
else if (e.getSource() == toolBarButtons[TOOLBAR_ZOOMRESET]){
getBoard().zoomTo(1.0);
}
else if (e.getSource() == toolBarButtons[TOOLBAR_ZOOMFIT]){
getBoard().zoomFit();
}
else if (e.getSource() == toolBarButtons[TOOLBAR_ANNOTATIONS])
{
legupMain.getPuzzleModule().toggleAnnotations();
repaintAll();
}
else if (e.getSource() == allowDefault)
{
//Change default applications on, nothing, checks menu checked state everywhere
}
else if (e.getSource() == caseRuleGen)
{
autoGenCaseRules = caseRuleGen.getState();
}
else if (e.getSource() == imdFeedback)
{
imdFeedbackFlag = imdFeedback.getState();
Tree.colorTransitions();
}
else if (e.getSource() == Step)
{
if (myAI.loaded()) {
BoardState current = legupMain.getSelections().getFirstSelection().getState();
myAI.step(current);
}
}
else if (e.getSource() == Run)
{
if (myAI.loaded()) {
BoardState current = legupMain.getSelections().getFirstSelection().getState();
myAI.stepToCompletion(current);
}
}
else if (e.getSource() == Test)
{
if (myAI.loaded()) {
//PuzzleModule current = legupMain.getPuzzleModule();
//myAI.test(current);
BoardState current = legupMain.getSelections().getFirstSelection().getState();
myAI.findRuleApplication(current);
}
}
else
{
for (int x = 0; x < PROF_FLAGS.length; ++x)
{
if (e.getSource() == proofModeItems[x]) processConfig(x);
}
}
}
public void resetUndoRedo()
{
undo.setEnabled(getTree().undoStack.size() > 1);
toolBarButtons[TOOLBAR_UNDO].setEnabled(getTree().undoStack.size() > 1);
redo.setEnabled(getTree().redoStack.size() > 0);
toolBarButtons[TOOLBAR_REDO].setEnabled(getTree().redoStack.size() > 0);
}
public void treeSelectionChanged(ArrayList <Selection> s)
{
resetUndoRedo();
repaintAll();
}
public void processConfig(int index)
{
proofModeItems[CONFIG_INDEX].setState(false);
CONFIG_INDEX = index;
proofModeItems[CONFIG_INDEX].setState(true);
int flags = PROF_FLAGS[index];
if (!profFlag(ALLOW_DEFAPP)) allowDefault.setState(false);
allowDefault.setEnabled(profFlag(ALLOW_DEFAPP));
AI.setEnabled(profFlag(ALLOW_FULLAI));
getJustificationFrame().setStatus(true, "Proof mode "+PROFILES[index]+" has been activated");
}
@Override
public void windowActivated(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowClosed(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowClosing(WindowEvent e) {
// TODO Auto-generated method stub
if(Legup.getInstance().getInitialBoardState() != null)
{
if(noquit("exiting LEGUP?"))
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
else
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
@Override
public void windowDeactivated(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowDeiconified(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowIconified(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowOpened(WindowEvent e) {
// TODO Auto-generated method stub
}
}
|
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;
import java.util.ArrayList;
/**
* This class defines a simple embedded SQL utility class that is designed to
* work with PostgreSQL JDBC drivers.
*
*/
public class Messenger {
// reference to physical database connection.
private Connection _connection = null;
// handling the keyboard inputs through a BufferedReader
// This variable can be global for convenience.
static BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
/**
* Creates a new instance of Messenger
*
* @param hostname the MySQL or PostgreSQL server hostname
* @param database the name of the database
* @param username the user name used to login to the database
* @param password the user login password
* @throws java.sql.SQLException when failed to make a connection.
*/
public Messenger (String dbname, String dbport, String user, String passwd) throws SQLException {
System.out.print("Connecting to database...");
try{
// constructs the connection URL
String url = "jdbc:postgresql://localhost:" + dbport + "/" + dbname;
System.out.println ("Connection URL: " + url + "\n");
// obtain a physical connection
this._connection = DriverManager.getConnection(url, user, passwd);
System.out.println("Done");
}catch (Exception e){
System.err.println("Error - Unable to Connect to Database: " + e.getMessage() );
System.out.println("Make sure you started postgres on this machine");
System.exit(-1);
}//end catch
}//end Messenger
/**
* Method to execute an update SQL statement. Update SQL instructions
* includes CREATE, INSERT, UPDATE, DELETE, and DROP.
*
* @param sql the input SQL string
* @throws java.sql.SQLException when update failed
*/
public void executeUpdate (String sql) throws SQLException {
// creates a statement object
Statement stmt = this._connection.createStatement ();
// issues the update instruction
stmt.executeUpdate (sql);
// close the instruction
stmt.close ();
}//end executeUpdate
/**
* Method to execute an input query SQL instruction (i.e. SELECT). This
* method issues the query to the DBMS and outputs the results to
* standard out.
*
* @param query the input query string
* @return the number of rows returned
* @throws java.sql.SQLException when failed to execute the query
*/
public int executeQueryAndPrintResult (String query) throws SQLException {
// creates a statement object
Statement stmt = this._connection.createStatement ();
// issues the query instruction
ResultSet rs = stmt.executeQuery (query);
/*
** obtains the metadata object for the returned result set. The metadata
** contains row and column info.
*/
ResultSetMetaData rsmd = rs.getMetaData ();
int numCol = rsmd.getColumnCount ();
int rowCount = 0;
// iterates through the result set and output them to standard out.
boolean outputHeader = true;
while (rs.next()){
if(outputHeader){
for(int i = 1; i <= numCol; i++){
System.out.print(rsmd.getColumnName(i) + "\t");
}
System.out.println();
outputHeader = false;
}
for (int i=1; i<=numCol; ++i)
System.out.print (rs.getString (i) + "\t");
System.out.println ();
++rowCount;
}//end while
stmt.close ();
return rowCount;
}//end executeQuery
/**
* Method to execute an input query SQL instruction (i.e. SELECT). This
* method issues the query to the DBMS and returns the results as
* a list of records. Each record in turn is a list of attribute values
*
* @param query the input query string
* @return the query result as a list of records
* @throws java.sql.SQLException when failed to execute the query
*/
public List<List<String>> executeQueryAndReturnResult (String query) throws SQLException {
// creates a statement object
Statement stmt = this._connection.createStatement ();
// issues the query instruction
ResultSet rs = stmt.executeQuery (query);
/*
** obtains the metadata object for the returned result set. The metadata
** contains row and column info.
*/
ResultSetMetaData rsmd = rs.getMetaData ();
int numCol = rsmd.getColumnCount ();
int rowCount = 0;
// iterates through the result set and saves the data returned by the query.
boolean outputHeader = false;
List<List<String>> result = new ArrayList<List<String>>();
while (rs.next()){
List<String> record = new ArrayList<String>();
for (int i=1; i<=numCol; ++i)
record.add(rs.getString (i));
result.add(record);
}//end while
stmt.close ();
return result;
}//end executeQueryAndReturnResult
/**
* Method to execute an input query SQL instruction (i.e. SELECT). This
* method issues the query to the DBMS and returns the number of results
*
* @param query the input query string
* @return the number of rows returned
* @throws java.sql.SQLException when failed to execute the query
*/
public int executeQuery (String query) throws SQLException {
// creates a statement object
Statement stmt = this._connection.createStatement ();
// issues the query instruction
ResultSet rs = stmt.executeQuery (query);
int rowCount = 0;
// iterates through the result set and count nuber of results.
if(rs.next()){
rowCount++;
}//end while
stmt.close ();
return rowCount;
}
/**
* Method to fetch the last value from sequence. This
* method issues the query to the DBMS and returns the current
* value of sequence used for autogenerated keys
*
* @param sequence name of the DB sequence
* @return current value of a sequence
* @throws java.sql.SQLException when failed to execute the query
*/
public int getCurrSeqVal(String sequence) throws SQLException {
Statement stmt = this._connection.createStatement ();
ResultSet rs = stmt.executeQuery (String.format("Select currval('%s')", sequence));
if (rs.next())
return rs.getInt(1);
return -1;
}
/**
* Method to close the physical connection if it is open.
*/
public void cleanup(){
try{
if (this._connection != null){
this._connection.close ();
}//end if
}catch (SQLException e){
// ignored.
}//end try
}//end cleanup
/**
* The main execution method
*
* @param args the command line arguments this inclues the <mysql|pgsql> <login file>
*/
public static void main (String[] args) {
if (args.length != 3) {
System.err.println (
"Usage: " +
"java [-classpath <classpath>] " +
Messenger.class.getName () +
" <dbname> <port> <user>");
return;
}//end if
Greeting();
Messenger esql = null;
try{
// use postgres JDBC driver.
Class.forName ("org.postgresql.Driver").newInstance ();
// instantiate the Messenger object and creates a physical
// connection.
String dbname = args[0];
String dbport = args[1];
String user = args[2];
esql = new Messenger (dbname, dbport, user, "");
boolean keepon = true;
while(keepon) {
// These are sample SQL statements
System.out.println("MAIN MENU");
System.out.println("
System.out.println("1. Create user");
System.out.println("2. Log in");
System.out.println("9. < EXIT");
String authorisedUser = null;
switch (readChoice()){
case 1: CreateUser(esql); break;
case 2: authorisedUser = LogIn(esql); break;
case 9: keepon = false; break;
default : System.out.println("Unrecognized choice!"); break;
}//end switch
if (authorisedUser != null) {
boolean usermenu = true;
while(usermenu) {
System.out.println("MAIN MENU");
System.out.println("
System.out.println("1. Add to contact list");
System.out.println("2. Browse contact list");
System.out.println("3. Write a new message");
System.out.println(".........................");
System.out.println("9. Log out");
switch (readChoice()){
case 1: AddToContact(esql,authorisedUser); break;
case 2: ListContacts(esql,authorisedUser); break;
case 3: NewMessage(esql); break;
case 9: usermenu = false; break;
default : System.out.println("Unrecognized choice!"); break;
}
}
}
}//end while
}catch(Exception e) {
System.err.println (e.getMessage ());
}finally{
// make sure to cleanup the created table and close the connection.
try{
if(esql != null) {
System.out.print("Disconnecting from database...");
esql.cleanup ();
System.out.println("Done\n\nBye !");
}//end if
}catch (Exception e) {
// ignored.
}//end try
}//end try
}//end main
public static void Greeting(){
System.out.println(
"\n\n*******************************************************\n" +
" User Interface \n" +
"*******************************************************\n");
}//end Greeting
/*
* Reads the users choice given from the keyboard
* @int
**/
public static int readChoice() {
int input;
// returns only if a correct value is given.
do {
System.out.print("Please make your choice: ");
try { // read the integer, parse it and break.
input = Integer.parseInt(in.readLine());
break;
}catch (Exception e) {
System.out.println("Your input is invalid!");
continue;
}//end try
}while (true);
return input;
}//end readChoice
/*
* Creates a new user with privided login, passowrd and phoneNum
* An empty block and contact list would be generated and associated with a user
**/
public static void CreateUser(Messenger esql){
try{
System.out.print("\tEnter user login: ");
String login = in.readLine();
System.out.print("\tEnter user password: ");
String password = in.readLine();
System.out.print("\tEnter user phone: ");
String phone = in.readLine();
//Creating empty contact\block lists for a user
esql.executeUpdate("INSERT INTO USER_LIST(list_type) VALUES ('block')");
int block_id = esql.getCurrSeqVal("user_list_list_id_seq");
esql.executeUpdate("INSERT INTO USER_LIST(list_type) VALUES ('contact')");
int contact_id = esql.getCurrSeqVal("user_list_list_id_seq");
String query = String.format("INSERT INTO USR (phoneNum, login, password, block_list, contact_list) VALUES ('%s','%s','%s',%s,%s)", phone, login, password, block_id, contact_id);
esql.executeUpdate(query);
System.out.println ("User successfully created!");
}catch(Exception e){
System.err.println (e.getMessage ());
}
}//end
/*
* Check log in credentials for an existing user
* @return User login or null is the user does not exist
**/
public static String LogIn(Messenger esql){
try{
System.out.print("\tEnter user login: ");
String login = in.readLine();
System.out.print("\tEnter user password: ");
String password = in.readLine();
String query = String.format("SELECT * FROM Usr WHERE login = '%s' AND password = '%s'", login, password);
int userNum = esql.executeQuery(query);
if (userNum > 0)
return login;
return null;
}catch(Exception e){
System.err.println (e.getMessage ());
return null;
}
}//end
public static void AddToContact(Messenger esql, String authorisedUser){
try{
System.out.print("\tEnter contact login: ")
String contact = in.readLine();
//Can implement existing contact in user contact list
String query = String.format("SELECT * FROM USR WHERE login = '%s'",contact);
int userNum = esql.executeUpdate(query);
if(userNum < 1){
System.out.print("\tNo user under login '%s'.",contact);
}else{
query = string.format(
"INSERT INTO USER_LIST_CONTAINS " +
"VALUES (SELECT contact_list FROM USR WHERE login = '%s','%s') ",
authorisedUser,contact);
}
esql.executeUpdate(query);
}catch(Exception e){
System.err.println (e.getMessage ());
}
}//end
public static void ListContacts(Messenger esql,String authorisedUser){
try{
String query = String.format(
"SELECT * FROM USER_LIST_CONTAINS "+
"WHERE (SELECT contact_list FROM USR WHERE login = '%s') = list_id",contact);
//Returns # of fitting results
int result = executeQueryAndPrintResult(query);
if(result <= 0)
System.out.print("No Contacts";)
}catch(Exception e){
System.err.println (e.getMessage ());
}
}//end
public static void NewMessage(Messenger esql){
// Your code goes here.
}//end
public static void Query6(Messenger esql){
// Your code goes here.
}//end Query6
}//end Messenger
|
package fr.obvil.grep;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import site.oeuvres.fr.Tokenizer;
public class GrepMultiWordExpressions {
public static final String DEFAULT_PATH="/home/etc/Bureau/textes/";
public static final String DEFAULT_TSV="./Source/critique2000.tsv";
public static final String OBVIL_PATH="http:/obvil-dev.paris-sorbonne.fr/corpus/critique/";
public static final String GITHUB_PATH="http:/obvil.github.io/critique2000/tei/";
public static String WORD="littérature";
String nameOrYearOrTitle="";
public String getNameOrYear() {
return nameOrYearOrTitle;
}
public void setNameOrYear(String query) {
this.nameOrYearOrTitle = query;
}
public static void main(String[] args) throws MalformedURLException, SAXException, IOException, ParserConfigurationException {
GrepMultiWordExpressions maClasse=new GrepMultiWordExpressions();
Scanner line=new Scanner(System.in);
Scanner word=new Scanner(System.in);
List <String []>allRows=new ArrayList<String[]>();
System.out.println("Définissez le chemin de votre fichier tsv (./Source/critique2000.tsv)");
String tsvPath=line.nextLine();
if(tsvPath.equals(null)||tsvPath.equals(""))tsvPath=DEFAULT_TSV;
BufferedReader TSVFile = new BufferedReader(new FileReader(tsvPath));
String dataRow = TSVFile.readLine();
while (dataRow != null){
String[] dataArray = dataRow.split("\t");
allRows.add(dataArray);
dataRow = TSVFile.readLine();
}
TSVFile.close();
int columnForQuery=1;
String doItAgain="";
String chosenPath="";
System.out.println("Définissez le chemin vers vos fichiers à analyser (exemple : /home/bilbo/Téléchargements/critique2000-gh-pages/tei/)");
chosenPath=line.nextLine();
if(chosenPath.equals(null)||chosenPath.equals(""))chosenPath=DEFAULT_PATH;
while (!doItAgain.equals("non")){
HashMap <String,String[]>statsPerAuthor=new HashMap<String, String[]>();
List <String[]>statsPerDoc=new ArrayList<String[]>();
System.out.println("Souhaitez-vous un tsv regroupé par par nom, par date ou par titre ? (réponses : nom/date/titre) :");
maClasse.setNameOrYear(word.next());
int column=maClasse.rechercheParNomDateTitrePourTSV(maClasse.getNameOrYear());
String preciseQuery="";
System.out.println("Quelle type de recherche voulez-vous effectuer ? (rentrer le numéro correspondant et taper \"entrée\")");
System.out.println("1 : rechercher un seul mot, une expression ou une expression régulière");
System.out.println("2 : rechercher deux mots dans une fenêtre à définir");
int chooseTypeRequest = Integer.valueOf(word.next());
switch (chooseTypeRequest){
case 1 :
System.out.println("Quel mot voulez-vous chercher ?");
String usersWord = line.nextLine();
if (usersWord!=null)WORD=usersWord;
System.out.println("Calcul des matchs en cours...");
for (int counterRows=1; counterRows<allRows.size(); counterRows++){
String []cells=allRows.get(counterRows);
int countOccurrences=0;
String fileName=cells[2]+".xml";
StringBuilder pathSB=new StringBuilder();
pathSB.append(chosenPath);
pathSB.append(fileName);
Path path = Paths.get(pathSB.toString());
String text = new String(Files.readAllBytes( path ), StandardCharsets.UTF_8);
Tokenizer toks = new Tokenizer(text);
StringBuilder sbToks=new StringBuilder();
while( toks.read() ) {
sbToks.append(toks.getString()+" ");
}
Pattern p = Pattern.compile(" "+WORD+" ");
Matcher m = p.matcher(sbToks.toString());
while (m.find()){
countOccurrences++;
}
statsPerAuthor=maClasse.mergeDatas(statsPerAuthor, statsPerDoc, cells, column, countOccurrences, toks, fileName);
}
columnForQuery=maClasse.rechercheParNomDateTitre(word);
System.out.println("\nQuel(le) "+maClasse.getNameOrYear()+" voulez-vous ?");
line=new Scanner(System.in);
preciseQuery = line.nextLine();
WORD=usersWord;
break;
case 2 :
System.out.println("Quel premier mot voulez-vous chercher ?");
String firstUsersWord = word.next();
System.out.println("Quel second mot voulez-vous chercher ?");
String secondUsersWord = word.next();
System.out.println("Quelle est l'étendue de votre fenêtre (en nombre de mots) ?");
int usersWindow = Integer.valueOf(word.next());
System.out.println("Calcul des matchs en cours...");
for (int counterRows=1; counterRows<allRows.size(); counterRows++){
String []cells=allRows.get(counterRows);
int countOccurrences=0;
String fileName=cells[2]+".xml";
StringBuilder pathSB=new StringBuilder();
pathSB.append(chosenPath);
pathSB.append(fileName);
Path path = Paths.get(pathSB.toString());
String text = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
Tokenizer toks = new Tokenizer(text);
LinkedList<String>listTokens=new LinkedList<String>();
StringBuilder sbToks=new StringBuilder();
while( toks.read() ) {
listTokens.add(toks.getString());
sbToks.append(toks.getString()+" ");
}
Pattern p = Pattern.compile(firstUsersWord+"\\s[^\\p{L}]*(\\p{L}+(\\s[^\\w])*\\s){1,"+usersWindow+"}"+secondUsersWord, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(sbToks.toString());
while(m.find()) {
countOccurrences++;
}
Pattern p2 = Pattern.compile(secondUsersWord+"\\s[^\\p{L}]*(\\p{L}+(\\s[^\\w])*\\s){1,"+usersWindow+"}"+firstUsersWord, Pattern.CASE_INSENSITIVE);
Matcher m2 = p2.matcher(sbToks.toString());
while(m2.find()) {
countOccurrences++;
}
statsPerAuthor=maClasse.mergeDatas(statsPerAuthor, statsPerDoc, cells, column, countOccurrences, toks, fileName);
}
columnForQuery=maClasse.rechercheParNomDateTitre(word);
System.out.println("\nQuel(le) "+maClasse.getNameOrYear()+" voulez-vous ?");
line=new Scanner(System.in);
preciseQuery = line.nextLine();
WORD=firstUsersWord+" et "+secondUsersWord;
break;
}
HashMap<String, int[]>combinedStats=new HashMap<String, int[]>();
for (Entry<String, String[]>entry:statsPerAuthor.entrySet()){
String keyStr=entry.getValue()[columnForQuery];
if (combinedStats.isEmpty()==false&&combinedStats.containsKey(keyStr)){
int[]stats=new int[2];
int previousTotalInt=Integer.parseInt(entry.getValue()[1]);
int previousNbMatches=Integer.parseInt(entry.getValue()[2]);
stats[0]=previousTotalInt+combinedStats.get(keyStr)[0];
stats[1]=previousNbMatches+combinedStats.get(keyStr)[1];
combinedStats.put(entry.getValue()[columnForQuery], stats);
}
else{
int[]stats=new int[2];
stats[0]=Integer.parseInt(entry.getValue()[1]);
stats[1]=Integer.parseInt(entry.getValue()[2]);
combinedStats.put(keyStr, stats);
}
}
for (Entry<String, int[]>entry:combinedStats.entrySet()){
if (entry.getKey().contains(preciseQuery)){
System.out.println("Voici les stats pour "+preciseQuery);
System.out.println("Nombre total de tokens : "+entry.getValue()[1]);
System.out.println("Nombre d'occurrences de "+WORD+" : "+entry.getValue()[0]);
if (columnForQuery==3){
for (String []doc:statsPerDoc){
if (doc[3].contains(preciseQuery)){
System.out.println("\nPour le fichier : "+doc[5]);
System.out.println("Nombre total de tokens : "+doc[2]);
System.out.println("Nombre de matchs : "+doc[1]);
System.out.println("Fréquence Relative : "+doc[0]);
}
}
}
}
}
System.out.println("\nSouhaitez-vous enregistrer votre requête dans un csv ? (oui/non)");
String save= word.next();
if (save.equals("oui")&&(column==3||column==4)){
ExportData.exportToCSV("./TargetCSV/",WORD.replaceAll("\\s", "_"),statsPerAuthor);
}
else if (save.equals("oui")&&(column==5)){
ExportData.exportListToCSV("./TargetCSV/",WORD.replaceAll("\\s", "_"),statsPerDoc);
}
else{
System.out.println("Votre requête n'a pas été enregistrée");
}
System.out.println("\nVoulez-vous faire une nouvelle requête ? (oui/non)");
doItAgain= word.next();
}
System.out.println("Fin du programme");
}
public int rechercheParNomDateTitre (Scanner usersChoice){
int columnForQuery=0;
System.out.println("Recherche par nom, par date ou par titre (réponses : nom/date/titre) :");
setNameOrYear(usersChoice.next());
while(!nameOrYearOrTitle.equals("nom")&&!nameOrYearOrTitle.equals("date")&&!nameOrYearOrTitle.equals("titre")){
System.out.println("**********");
System.out.println("Veuillez rentrer le mot nom ou le mot date");
System.out.println("**********");
System.out.println("Recherche par nom ou par date (réponses : nom/date) :");
nameOrYearOrTitle = usersChoice.next();
}
if (nameOrYearOrTitle.equals("nom")){
columnForQuery=3;
}
else if (nameOrYearOrTitle.equals("date")){
columnForQuery=4;
}
else if (nameOrYearOrTitle.equals("titre")){
columnForQuery=5;
}
return columnForQuery;
}
public int rechercheParNomDateTitrePourTSV (String usersChoice){
int columnForQuery=0;
if (usersChoice.equals("nom")){
columnForQuery=3;
}
else if (usersChoice.equals("date")){
columnForQuery=4;
}
else if (usersChoice.equals("titre")){
columnForQuery=5;
}
return columnForQuery;
}
public HashMap <String, String[]> mergeDatas(HashMap <String, String[]>statsPerAuthor, List<String[]>statsPerDoc, String cells[], int column, int countOccurrences, Tokenizer toks, String fileName){
String statsPourListeDocs []=new String[7];
switch (column){
case 3:
if (statsPerAuthor.containsKey(cells[column])){
String [] tmp=new String[7];
tmp[1]=String.valueOf(Integer.parseInt(statsPerAuthor.get(cells[column])[1])+countOccurrences);
tmp[2]=String.valueOf(Integer.parseInt(statsPerAuthor.get(cells[column])[2])+toks.size);
tmp[0]=String.valueOf((Double.parseDouble(statsPerAuthor.get(cells[column])[1])+countOccurrences)/(Integer.parseInt(statsPerAuthor.get(cells[column])[2])+toks.size)); //Relative Frequency
tmp[3]=statsPerAuthor.get(cells[column])[3]+" // "+cells[3]; //Authors name
tmp[4]=cells[4]; // Year
tmp[5]=statsPerAuthor.get(cells[column])[5]+" // "+cells[5]; // Title
tmp[6]=fileName;
statsPerAuthor.put(cells[column], tmp);
}
else{
String mapOccurrences[]= new String[7];
mapOccurrences[1]=String.valueOf(countOccurrences);
mapOccurrences[2]=String.valueOf(toks.size);
mapOccurrences[0]=String.valueOf(countOccurrences/toks.size); //Relative Frequency
mapOccurrences[3]=cells[3]; //Authors name
mapOccurrences[4]=cells[4]; // Year
mapOccurrences[5]=cells[5]; // Title
mapOccurrences[6]=fileName;
statsPerAuthor.put(cells[column],mapOccurrences);
}
statsPourListeDocs[1]=String.valueOf(countOccurrences);
statsPourListeDocs[2]=String.valueOf(toks.size);
statsPourListeDocs[0]=String.valueOf(countOccurrences/toks.size); //Relative Frequency
statsPourListeDocs[3]=cells[3]; //Authors name
statsPourListeDocs[4]=cells[4]; // Year
statsPourListeDocs[5]=cells[5]; // Title
statsPourListeDocs[6]=fileName;
statsPerDoc.add(statsPourListeDocs);
case 4:
if (statsPerAuthor.containsKey(cells[column])){
String [] tmp=new String[7];
tmp[1]=String.valueOf(Integer.parseInt(statsPerAuthor.get(cells[column])[1])+countOccurrences);
tmp[2]=String.valueOf(Integer.parseInt(statsPerAuthor.get(cells[column])[2])+toks.size);
tmp[0]=String.valueOf((Double.parseDouble(statsPerAuthor.get(cells[column])[1])+countOccurrences)/(Integer.parseInt(statsPerAuthor.get(cells[column])[2])+toks.size)); //Relative Frequency
tmp[3]=statsPerAuthor.get(cells[column])[3]+" // "+cells[3]; //Authors name
tmp[4]=cells[4]; // Year
tmp[5]=statsPerAuthor.get(cells[column])[5]+" // "+cells[5]; // Title
tmp[6]=fileName;
statsPerAuthor.put(cells[column], tmp);
}
else{
String mapOccurrences[]= new String[7];
mapOccurrences[1]=String.valueOf(countOccurrences);
mapOccurrences[2]=String.valueOf(toks.size);
mapOccurrences[0]=String.valueOf(countOccurrences/toks.size); //Relative Frequency
mapOccurrences[3]=cells[3]; //Authors name
mapOccurrences[4]=cells[4]; // Year
mapOccurrences[5]=cells[5]; // Title
mapOccurrences[6]=fileName;
statsPerAuthor.put(cells[column],mapOccurrences);
}
statsPourListeDocs[1]=String.valueOf(countOccurrences);
statsPourListeDocs[2]=String.valueOf(toks.size);
statsPourListeDocs[0]=String.valueOf(countOccurrences/toks.size); //Relative Frequency
statsPourListeDocs[3]=cells[3]; //Authors name
statsPourListeDocs[4]=cells[4]; // Year
statsPourListeDocs[5]=cells[5]; // Title
statsPourListeDocs[6]=fileName;
statsPerDoc.add(statsPourListeDocs);
}
return statsPerAuthor;
}
}
|
package net.fortuna.ical4j.model.component;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.Iterator;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.ComponentList;
import net.fortuna.ical4j.model.Date;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.Dur;
import net.fortuna.ical4j.model.Parameter;
import net.fortuna.ical4j.model.Period;
import net.fortuna.ical4j.model.PeriodList;
import net.fortuna.ical4j.model.Property;
import net.fortuna.ical4j.model.PropertyList;
import net.fortuna.ical4j.model.ValidationException;
import net.fortuna.ical4j.model.parameter.Value;
import net.fortuna.ical4j.model.property.Clazz;
import net.fortuna.ical4j.model.property.Created;
import net.fortuna.ical4j.model.property.Description;
import net.fortuna.ical4j.model.property.DtEnd;
import net.fortuna.ical4j.model.property.DtStamp;
import net.fortuna.ical4j.model.property.DtStart;
import net.fortuna.ical4j.model.property.Duration;
import net.fortuna.ical4j.model.property.Geo;
import net.fortuna.ical4j.model.property.LastModified;
import net.fortuna.ical4j.model.property.Location;
import net.fortuna.ical4j.model.property.Organizer;
import net.fortuna.ical4j.model.property.Priority;
import net.fortuna.ical4j.model.property.RecurrenceId;
import net.fortuna.ical4j.model.property.Sequence;
import net.fortuna.ical4j.model.property.Status;
import net.fortuna.ical4j.model.property.Summary;
import net.fortuna.ical4j.model.property.Transp;
import net.fortuna.ical4j.model.property.Uid;
import net.fortuna.ical4j.model.property.Url;
import net.fortuna.ical4j.util.CompatibilityHints;
import net.fortuna.ical4j.util.Dates;
import net.fortuna.ical4j.util.PropertyValidator;
import net.fortuna.ical4j.util.Strings;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Defines an iCalendar VEVENT component.
*
* <pre>
* 4.6.1 Event Component
*
* Component Name: "VEVENT"
*
* Purpose: Provide a grouping of component properties that describe an
* event.
*
* Format Definition: A "VEVENT" calendar component is defined by the
* following notation:
*
* eventc = "BEGIN" ":" "VEVENT" CRLF
* eventprop *alarmc
* "END" ":" "VEVENT" CRLF
*
* eventprop = *(
*
* ; the following are optional,
* ; but MUST NOT occur more than once
*
* class / created / description / dtstart / geo /
* last-mod / location / organizer / priority /
* dtstamp / seq / status / summary / transp /
* uid / url / recurid /
*
* ; either 'dtend' or 'duration' may appear in
* ; a 'eventprop', but 'dtend' and 'duration'
* ; MUST NOT occur in the same 'eventprop'
*
* dtend / duration /
*
* ; the following are optional,
* ; and MAY occur more than once
*
* attach / attendee / categories / comment /
* contact / exdate / exrule / rstatus / related /
* resources / rdate / rrule / x-prop
*
* )
* </pre>
*
* Example 1 - Creating a new all-day event:
*
* <pre><code>
* java.util.Calendar cal = java.util.Calendar.getInstance();
* cal.set(java.util.Calendar.MONTH, java.util.Calendar.DECEMBER);
* cal.set(java.util.Calendar.DAY_OF_MONTH, 25);
*
* VEvent christmas = new VEvent(cal.getTime(), "Christmas Day");
*
* // initialise as an all-day event..
* christmas.getProperties().getProperty(Property.DTSTART).getParameters().add(
* Value.DATE);
*
* // add timezone information..
* VTimeZone tz = VTimeZone.getDefault();
* TzId tzParam = new TzId(tz.getProperties().getProperty(Property.TZID)
* .getValue());
* christmas.getProperties().getProperty(Property.DTSTART).getParameters().add(
* tzParam);
* </code></pre>
*
* Example 2 - Creating an event of one (1) hour duration:
*
* <pre><code>
* java.util.Calendar cal = java.util.Calendar.getInstance();
* // tomorrow..
* cal.add(java.util.Calendar.DAY_OF_MONTH, 1);
* cal.set(java.util.Calendar.HOUR_OF_DAY, 9);
* cal.set(java.util.Calendar.MINUTE, 30);
*
* VEvent meeting = new VEvent(cal.getTime(), 1000 * 60 * 60, "Progress Meeting");
*
* // add timezone information..
* VTimeZone tz = VTimeZone.getDefault();
* TzId tzParam = new TzId(tz.getProperties().getProperty(Property.TZID)
* .getValue());
* meeting.getProperties().getProperty(Property.DTSTART).getParameters().add(
* tzParam);
* </code></pre>
*
* Example 3 - Retrieve a list of periods representing a recurring event in a specified range:
*
* <pre><code>
* Calendar weekday9AM = Calendar.getInstance();
* weekday9AM.set(2005, Calendar.MARCH, 7, 9, 0, 0);
* weekday9AM.set(Calendar.MILLISECOND, 0);
*
* Calendar weekday5PM = Calendar.getInstance();
* weekday5PM.set(2005, Calendar.MARCH, 7, 17, 0, 0);
* weekday5PM.set(Calendar.MILLISECOND, 0);
*
* // Do the recurrence until December 31st.
* Calendar untilCal = Calendar.getInstance();
* untilCal.set(2005, Calendar.DECEMBER, 31);
* untilCal.set(Calendar.MILLISECOND, 0);
*
* // 9:00AM to 5:00PM Rule
* Recur recur = new Recur(Recur.WEEKLY, untilCal.getTime());
* recur.getDayList().add(WeekDay.MO);
* recur.getDayList().add(WeekDay.TU);
* recur.getDayList().add(WeekDay.WE);
* recur.getDayList().add(WeekDay.TH);
* recur.getDayList().add(WeekDay.FR);
* recur.setInterval(3);
* recur.setWeekStartDay(WeekDay.MO.getDay());
* RRule rrule = new RRule(recur);
*
* Summary summary = new Summary("TEST EVENTS THAT HAPPEN 9-5 MON-FRI");
*
* weekdayNineToFiveEvents = new VEvent();
* weekdayNineToFiveEvents.getProperties().add(rrule);
* weekdayNineToFiveEvents.getProperties().add(summary);
* weekdayNineToFiveEvents.getProperties().add(new DtStart(weekday9AM.getTime()));
* weekdayNineToFiveEvents.getProperties().add(new DtEnd(weekday5PM.getTime()));
*
* // Test Start 04/01/2005, End One month later.
* // Query Calendar Start and End Dates.
* Calendar queryStartDate = Calendar.getInstance();
* queryStartDate.set(2005, Calendar.APRIL, 1, 14, 47, 0);
* queryStartDate.set(Calendar.MILLISECOND, 0);
* Calendar queryEndDate = Calendar.getInstance();
* queryEndDate.set(2005, Calendar.MAY, 1, 11, 15, 0);
* queryEndDate.set(Calendar.MILLISECOND, 0);
*
* // This range is monday to friday every three weeks, starting from
* // March 7th 2005, which means for our query dates we need
* // April 18th through to the 22nd.
* PeriodList periods = weekdayNineToFiveEvents.getPeriods(queryStartDate
* .getTime(), queryEndDate.getTime());
* </code></pre>
*
* @author Ben Fortuna
*/
public class VEvent extends CalendarComponent {
private static final long serialVersionUID = 2547948989200697335L;
private Log log = LogFactory.getLog(VEvent.class);
private ComponentList alarms;
/**
* Default constructor.
*/
public VEvent() {
super(VEVENT);
this.alarms = new ComponentList();
getProperties().add(new DtStamp());
}
/**
* Constructor.
* @param properties a list of properties
*/
public VEvent(final PropertyList properties) {
super(VEVENT, properties);
this.alarms = new ComponentList();
}
/**
* Constructor.
* @param properties a list of properties
* @param alarms a list of alarms
*/
public VEvent(final PropertyList properties, final ComponentList alarms) {
super(VEVENT, properties);
this.alarms = alarms;
}
/**
* Constructs a new VEVENT instance starting at the specified time with the specified summary.
* @param start the start date of the new event
* @param summary the event summary
*/
public VEvent(final Date start, final String summary) {
this();
getProperties().add(new DtStart(start));
getProperties().add(new Summary(summary));
}
/**
* Constructs a new VEVENT instance starting and ending at the specified times with the specified summary.
* @param start the start date of the new event
* @param end the end date of the new event
* @param summary the event summary
*/
public VEvent(final Date start, final Date end, final String summary) {
this();
getProperties().add(new DtStart(start));
getProperties().add(new DtEnd(end));
getProperties().add(new Summary(summary));
}
/**
* Constructs a new VEVENT instance starting at the specified times, for the specified duration, with the specified
* summary.
* @param start the start date of the new event
* @param duration the duration of the new event
* @param summary the event summary
*/
public VEvent(final Date start, final Dur duration, final String summary) {
this();
getProperties().add(new DtStart(start));
getProperties().add(new Duration(duration));
getProperties().add(new Summary(summary));
}
/**
* Returns the list of alarms for this event.
* @return a component list
*/
public final ComponentList getAlarms() {
return alarms;
}
/**
* @see java.lang.Object#toString()
*/
public final String toString() {
StringBuffer b = new StringBuffer();
b.append(BEGIN);
b.append(':');
b.append(getName());
b.append(Strings.LINE_SEPARATOR);
b.append(getProperties());
b.append(getAlarms());
b.append(END);
b.append(':');
b.append(getName());
b.append(Strings.LINE_SEPARATOR);
return b.toString();
}
/**
* @see net.fortuna.ical4j.model.Component#validate(boolean)
*/
public final void validate(final boolean recurse)
throws ValidationException {
// validate that getAlarms() only contains VAlarm components
Iterator iterator = getAlarms().iterator();
while (iterator.hasNext()) {
Component component = (Component) iterator.next();
if (!(component instanceof VAlarm)) {
throw new ValidationException("Component ["
+ component.getName() + "] may not occur in VEVENT");
}
}
if (!CompatibilityHints
.isHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION)) {
// From "4.8.4.7 Unique Identifier":
// Conformance: The property MUST be specified in the "VEVENT", "VTODO",
// "VJOURNAL" or "VFREEBUSY" calendar components.
PropertyValidator.getInstance().assertOne(Property.UID,
getProperties());
// From "4.8.7.2 Date/Time Stamp":
// Conformance: This property MUST be included in the "VEVENT", "VTODO",
// "VJOURNAL" or "VFREEBUSY" calendar components.
PropertyValidator.getInstance().assertOne(Property.DTSTAMP,
getProperties());
}
/*
* ; the following are optional, ; but MUST NOT occur more than once class / created / description / dtstart /
* geo / last-mod / location / organizer / priority / dtstamp / seq / status / summary / transp / uid / url /
* recurid /
*/
PropertyValidator.getInstance().assertOneOrLess(Property.CLASS,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.CREATED,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.DESCRIPTION,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.DTSTART,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.GEO,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.LAST_MODIFIED,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.LOCATION,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.ORGANIZER,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.PRIORITY,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.DTSTAMP,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.SEQUENCE,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.STATUS,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.SUMMARY,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.TRANSP,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.UID,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.URL,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.RECURRENCE_ID,
getProperties());
Status status = (Status) getProperty(Property.STATUS);
if (status != null && !Status.VEVENT_TENTATIVE.equals(status)
&& !Status.VEVENT_CONFIRMED.equals(status)
&& !Status.VEVENT_CANCELLED.equals(status)) {
throw new ValidationException("Status property ["
+ status.toString() + "] is not applicable for VEVENT");
}
/*
* ; either 'dtend' or 'duration' may appear in ; a 'eventprop', but 'dtend' and 'duration' ; MUST NOT occur in
* the same 'eventprop' dtend / duration /
*/
try {
PropertyValidator.getInstance().assertNone(Property.DTEND,
getProperties());
}
catch (ValidationException ve) {
PropertyValidator.getInstance().assertNone(Property.DURATION,
getProperties());
}
if (getProperty(Property.DTEND) != null) {
/*
* The "VEVENT" is also the calendar component used to specify an anniversary or daily reminder within a
* calendar. These events have a DATE value type for the "DTSTART" property instead of the default data type
* of DATE-TIME. If such a "VEVENT" has a "DTEND" property, it MUST be specified as a DATE value also. The
* anniversary type of "VEVENT" can span more than one date (i.e, "DTEND" property value is set to a
* calendar date after the "DTSTART" property value).
*/
DtStart start = (DtStart) getProperty(Property.DTSTART);
DtEnd end = (DtEnd) getProperty(Property.DTEND);
if (start != null) {
Parameter startValue = start.getParameter(Parameter.VALUE);
Parameter endValue = end.getParameter(Parameter.VALUE);
if (startValue != null) {
if(startValue.equals(Value.DATE_TIME) && endValue==null) {
// DATE-TIME is the default so this is ok
} else if (!startValue.equals(endValue)) {
throw new ValidationException("Property [" + Property.DTEND
+ "] must have the same [" + Parameter.VALUE
+ "] as [" + Property.DTSTART + "]");
}
} else if(endValue!=null) {
// if DTSTART's VALUE is null then DTEND's must be DATE-TIME
if(!endValue.equals(Value.DATE_TIME))
throw new ValidationException("Property [" + Property.DTEND
+ "] must have the same [" + Parameter.VALUE
+ "] as [" + Property.DTSTART + "]");
}
}
}
/*
* ; the following are optional, ; and MAY occur more than once attach / attendee / categories / comment /
* contact / exdate / exrule / rstatus / related / resources / rdate / rrule / x-prop
*/
if (recurse) {
validateProperties();
}
}
/**
* Returns a normalised list of periods representing the consumed time for this event.
* @param rangeStart
* @param rangeEnd
* @return a normalised list of periods representing consumed time for this event
* @see VEvent#getConsumedTime(Date, Date, boolean)
*/
public final PeriodList getConsumedTime(final Date rangeStart,
final Date rangeEnd) {
return getConsumedTime(rangeStart, rangeEnd, true);
}
/**
* Returns a list of periods representing the consumed time for this event in the specified range. Note that the
* returned list may contain a single period for non-recurring components or multiple periods for recurring
* components. If no time is consumed by this event an empty list is returned.
* @param rangeStart the start of the range to check for consumed time
* @param rangeEnd the end of the range to check for consumed time
* @param normalise indicate whether the returned list of periods should be normalised
* @return a list of periods representing consumed time for this event
*/
public final PeriodList getConsumedTime(final Date rangeStart,
final Date rangeEnd, final boolean normalise) {
PeriodList periods = new PeriodList();
// if component is transparent return empty list..
if (Transp.TRANSPARENT.equals(getProperty(Property.TRANSP))) {
return periods;
}
// try {
periods = calculateRecurrenceSet(new Period(new DateTime(rangeStart),
new DateTime(rangeEnd)));
// catch (ValidationException ve) {
// log.error("Invalid event data", ve);
// return periods;
// if periods already specified through recurrence, return..
// ..also normalise before returning.
if (!periods.isEmpty() && normalise) {
return periods.normalise();
}
return periods;
}
/**
* @return the optional access classification property for an event
*/
public final Clazz getClassification() {
return (Clazz) getProperty(Property.CLASS);
}
/**
* @return the optional creation-time property for an event
*/
public final Created getCreated() {
return (Created) getProperty(Property.CREATED);
}
/**
* @return the optional description property for an event
*/
public final Description getDescription() {
return (Description) getProperty(Property.DESCRIPTION);
}
/**
* Convenience method to pull the DTSTART out of the property list.
* @return The DtStart object representation of the start Date
*/
public final DtStart getStartDate() {
return (DtStart) getProperty(Property.DTSTART);
}
/**
* @return the optional geographic position property for an event
*/
public final Geo getGeographicPos() {
return (Geo) getProperty(Property.GEO);
}
/**
* @return the optional last-modified property for an event
*/
public final LastModified getLastModified() {
return (LastModified) getProperty(Property.LAST_MODIFIED);
}
/**
* @return the optional location property for an event
*/
public final Location getLocation() {
return (Location) getProperty(Property.LOCATION);
}
/**
* @return the optional organizer property for an event
*/
public final Organizer getOrganizer() {
return (Organizer) getProperty(Property.ORGANIZER);
}
/**
* @return the optional priority property for an event
*/
public final Priority getPriority() {
return (Priority) getProperty(Property.PRIORITY);
}
/**
* @return the optional date-stamp property
*/
public final DtStamp getDateStamp() {
return (DtStamp) getProperty(Property.DTSTAMP);
}
/**
* @return the optional sequence number property for an event
*/
public final Sequence getSequence() {
return (Sequence) getProperty(Property.SEQUENCE);
}
/**
* @return the optional status property for an event
*/
public final Status getStatus() {
return (Status) getProperty(Property.STATUS);
}
/**
* @return the optional summary property for an event
*/
public final Summary getSummary() {
return (Summary) getProperty(Property.SUMMARY);
}
/**
* @return the optional time transparency property for an event
*/
public final Transp getTransparency() {
return (Transp) getProperty(Property.TRANSP);
}
/**
* @return the optional URL property for an event
*/
public final Url getUrl() {
return (Url) getProperty(Property.URL);
}
/**
* @return the optional recurrence identifier property for an event
*/
public final RecurrenceId getRecurrenceId() {
return (RecurrenceId) getProperty(Property.RECURRENCE_ID);
}
/**
* Returns the end date of this event. Where an end date is not available it will be derived from the event
* duration.
* @return a DtEnd instance, or null if one cannot be derived
*/
public final DtEnd getEndDate() {
return getEndDate(true);
}
/**
* Convenience method to pull the DTEND out of the property list. If DTEND was not specified, use the DTSTART +
* DURATION to calculate it.
* @param deriveFromDuration specifies whether to derive an end date from the event duration where an end date is
* not found
* @return The end for this VEVENT.
*/
public final DtEnd getEndDate(final boolean deriveFromDuration) {
DtEnd dtEnd = (DtEnd) getProperty(Property.DTEND);
// No DTEND? No problem, we'll use the DURATION.
if (dtEnd == null && deriveFromDuration && getDuration() != null) {
DtStart dtStart = getStartDate();
Duration vEventDuration = getDuration();
dtEnd = new DtEnd(Dates.getInstance(vEventDuration.getDuration()
.getTime(dtStart.getDate()), (Value) dtStart
.getParameter(Parameter.VALUE)));
if (dtStart.isUtc()) {
dtEnd.setUtc(true);
}
}
return dtEnd;
}
/**
* @return the optional Duration property
*/
public final Duration getDuration() {
return (Duration) getProperty(Property.DURATION);
}
/**
* Returns the UID property of this component if available.
* @return a Uid instance, or null if no UID property exists
*/
public final Uid getUid() {
return (Uid) getProperty(Property.UID);
}
/*
* (non-Javadoc)
* @see net.fortuna.ical4j.model.Component#equals(java.lang.Object)
*/
public boolean equals(Object arg0) {
if (arg0 instanceof VEvent) {
return super.equals(arg0)
&& ObjectUtils.equals(alarms, ((VEvent) arg0).getAlarms());
}
return super.equals(arg0);
}
/* (non-Javadoc)
* @see net.fortuna.ical4j.model.Component#hashCode()
*/
public int hashCode() {
return new HashCodeBuilder().append(getName()).append(getProperties())
.append(getAlarms()).toHashCode();
}
/**
* Overrides default copy method to add support for copying alarm sub-components.
* @see net.fortuna.ical4j.model.Component#copy()
*/
public Component copy() throws ParseException, IOException,
URISyntaxException {
VEvent copy = (VEvent) super.copy();
copy.alarms = new ComponentList(alarms);
return copy;
}
}
|
package com.purdue.CampusFeed;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
public class BrowseFragment extends Fragment {
private ListView lv;
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.browse_layout, container, false);
}
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
//move list view initialization here
lv = (ListView) getActivity().findViewById(R.id.browse_listview);
RowGenerator_ArrayAdapter adapter = new RowGenerator_ArrayAdapter(getActivity(), values);
if(lv==null)
{
Toast.makeText(getActivity(),"list view is null", Toast.LENGTH_SHORT).show();
return;
}
else{
lv.setAdapter(adapter);
}
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long id) {
/*String text = (String) adapterView.getItemAtPosition(pos);
Toast.makeText(getActivity(), text + " selected", Toast.LENGTH_SHORT).show();*/
getFragmentManager().beginTransaction().replace(R.id.content_frame, new EventPageFragment()).commit();
}
});
}
}
|
package com.perimeterx.api;
import com.perimeterx.api.activities.DefaultActivityHandler;
import com.perimeterx.api.blockhandler.BlockHandler;
import com.perimeterx.api.providers.DefaultHostnameProvider;
import com.perimeterx.api.providers.HostnameProvider;
import com.perimeterx.api.providers.IPProvider;
import com.perimeterx.api.providers.RemoteAddressIPProvider;
import com.perimeterx.api.verificationhandler.DefaultVerificationHandler;
import com.perimeterx.http.PXClient;
import com.perimeterx.models.PXContext;
import com.perimeterx.models.configuration.ModuleMode;
import com.perimeterx.models.configuration.PXConfiguration;
import com.perimeterx.models.exceptions.PXException;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import testutils.TestObjectUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponseWrapper;
@Test
public class DefaultVerificationHandlerTest {
private DefaultActivityHandler activityHandler;
private IPProvider ipProvider;
private HostnameProvider hostnameProvider;
private PXConfiguration config;
private DefaultVerificationHandler defaultVerificationHandler;
private BlockHandler blockHandler;
@BeforeMethod
public void setUp() {
this.config = PXConfiguration.builder()
.appId("appId")
.authToken("token")
.cookieKey("cookieKey")
.moduleMode(ModuleMode.MONITOR)
.remoteConfigurationEnabled(false)
.blockingScore(30)
.bypassMonitorHeader("TEST-BYPASS")
.build();;
PXClient pxClient = TestObjectUtils.blockingPXClient(config.getBlockingScore());
this.activityHandler = new DefaultActivityHandler(pxClient, config);
this.hostnameProvider = new DefaultHostnameProvider();
this.ipProvider = new RemoteAddressIPProvider();
this.defaultVerificationHandler = new DefaultVerificationHandler(config, activityHandler);
}
@Test
public void TestMonitorModeBypass() throws PXException {
HttpServletRequest request = new MockHttpServletRequest();
((MockHttpServletRequest) request).addHeader("TEST-BYPASS", "1");
HttpServletResponseWrapper response = new HttpServletResponseWrapper(new MockHttpServletResponse());
PXContext context = new PXContext(request, ipProvider, hostnameProvider, config);
context.setRiskScore(100);
DefaultVerificationHandler defaultVerificationHandler = new DefaultVerificationHandler(config, activityHandler);
context.setBlockAction("b");
boolean verified = defaultVerificationHandler.handleVerification(context, response);
Assert.assertFalse(verified);
}
@Test
public void TestMonitorModeBypassWrongValueInHeader() throws PXException {
HttpServletRequest request = new MockHttpServletRequest();
((MockHttpServletRequest) request).addHeader("TEST-BYPASS", "0");
HttpServletResponseWrapper response = new HttpServletResponseWrapper(new MockHttpServletResponse());
PXContext context = new PXContext(request, ipProvider, hostnameProvider, config);
context.setRiskScore(100);
DefaultVerificationHandler defaultVerificationHandler = new DefaultVerificationHandler(config, activityHandler);
context.setBlockAction("b");
boolean verified = defaultVerificationHandler.handleVerification(context, response);
Assert.assertTrue(verified);
}
@Test
public void TestMonitorModeBypassHeaderDefinedAndMissingFromRequest() throws PXException {
HttpServletRequest request = new MockHttpServletRequest();
HttpServletResponseWrapper response = new HttpServletResponseWrapper(new MockHttpServletResponse());
PXContext context = new PXContext(request, ipProvider, hostnameProvider, config);
context.setRiskScore(100);
DefaultVerificationHandler defaultVerificationHandler = new DefaultVerificationHandler(config, activityHandler);
context.setBlockAction("b");
boolean verified = defaultVerificationHandler.handleVerification(context, response);
Assert.assertTrue(verified);
}
}
|
package com.uwetrottmann.tmdb2.services;
import com.uwetrottmann.tmdb2.BaseTestCase;
import com.uwetrottmann.tmdb2.TestData;
import com.uwetrottmann.tmdb2.entities.AppendToResponse;
import com.uwetrottmann.tmdb2.entities.Credits;
import com.uwetrottmann.tmdb2.entities.Images;
import com.uwetrottmann.tmdb2.entities.ListResultsPage;
import com.uwetrottmann.tmdb2.entities.Movie;
import com.uwetrottmann.tmdb2.entities.MovieAlternativeTitles;
import com.uwetrottmann.tmdb2.entities.MovieKeywords;
import com.uwetrottmann.tmdb2.entities.MovieResultsPage;
import com.uwetrottmann.tmdb2.entities.ReleaseDatesResult;
import com.uwetrottmann.tmdb2.entities.ReleaseDatesResults;
import com.uwetrottmann.tmdb2.entities.ReviewResultsPage;
import com.uwetrottmann.tmdb2.entities.Translations;
import com.uwetrottmann.tmdb2.entities.Videos;
import com.uwetrottmann.tmdb2.enumerations.AppendToResponseItem;
import org.junit.Test;
import retrofit2.Call;
import java.io.IOException;
import java.text.ParseException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
public class MoviesServiceTest extends BaseTestCase {
@Test
public void test_summary() throws ParseException, IOException {
Call<Movie> call = getManager().moviesService().summary(TestData.MOVIE_ID, null, null);
Movie movie = call.execute().body();
assertMovie(movie);
assertThat(movie.original_title).isEqualTo(TestData.MOVIE_TITLE);
}
@Test
public void test_summary_language() throws ParseException, IOException {
Call<Movie> call = getManager().moviesService().summary(TestData.MOVIE_ID, "pt-BR", null);
Movie movie = call.execute().body();
assertThat(movie).isNotNull();
assertThat(movie.title).isEqualTo("Clube da Luta");
}
@Test
public void test_summary_with_collection() throws ParseException, IOException {
Call<Movie> call = getManager().moviesService().summary(TestData.MOVIE_WITH_COLLECTION_ID, null, null);
Movie movie = call.execute().body();
assertThat(movie.title).isEqualTo(TestData.MOVIE_WITH_COLLECTION_TITLE);
assertThat(movie.belongs_to_collection).isNotNull();
assertThat(movie.belongs_to_collection.id).isEqualTo(1241);
assertThat(movie.belongs_to_collection.name).isEqualTo("Harry Potter Collection");
}
private void assertMovie(Movie movie) {
assertThat(movie).isNotNull();
assertThat(movie.id).isEqualTo(TestData.MOVIE_ID);
assertThat(movie.title).isEqualTo(TestData.MOVIE_TITLE);
assertThat(movie.overview).isNotEmpty();
assertThat(movie.tagline).isNotEmpty();
assertThat(movie.adult).isFalse();
assertThat(movie.backdrop_path).isNotEmpty();
assertThat(movie.budget).isEqualTo(63000000);
assertThat(movie.imdb_id).isEqualTo(TestData.MOVIE_IMDB);
assertThat(movie.poster_path).isNotEmpty();
assertThat(movie.release_date).isEqualTo("1999-10-14");
assertThat(movie.revenue).isEqualTo(100853753);
assertThat(movie.runtime).isEqualTo(139);
assertThat(movie.vote_average).isPositive();
assertThat(movie.vote_count).isPositive();
}
@Test
public void test_summary_append_videos() throws IOException {
Call<Movie> call = getManager().moviesService().summary(TestData.MOVIE_ID,
null,
new AppendToResponse(
AppendToResponseItem.VIDEOS));
Movie movie = call.execute().body();
assertNotNull(movie.videos);
}
@Test
public void test_summary_append_credits() throws IOException {
Call<Movie> call = getManager().moviesService().summary(TestData.MOVIE_ID,
null,
new AppendToResponse(
AppendToResponseItem.CREDITS));
Movie movie = call.execute().body();
assertNotNull(movie.credits);
}
@Test
public void test_summary_append_release_dates() throws IOException {
Call<Movie> call = getManager().moviesService().summary(TestData.MOVIE_ID,
null,
new AppendToResponse(
AppendToResponseItem.RELEASE_DATES));
Movie movie = call.execute().body();
assertNotNull(movie.release_dates);
}
@Test
public void test_summary_append_similar() throws IOException {
Call<Movie> call = getManager().moviesService().summary(TestData.MOVIE_ID,
null,
new AppendToResponse(
AppendToResponseItem.SIMILAR));
Movie movie = call.execute().body();
assertNotNull(movie.similar);
}
@Test
public void test_summary_append_all() throws IOException {
Call<Movie> call = getManager().moviesService().summary(TestData.MOVIE_ID,
null,
new AppendToResponse(
AppendToResponseItem.RELEASE_DATES,
AppendToResponseItem.CREDITS,
AppendToResponseItem.VIDEOS,
AppendToResponseItem.SIMILAR));
Movie movie = call.execute().body();
assertNotNull(movie.release_dates);
assertNotNull(movie.release_dates.results);
assertThat(movie.release_dates.results).isNotEmpty();
assertNotNull(movie.credits);
assertNotNull(movie.videos);
assertNotNull(movie.similar);
}
@Test
public void test_alternative_titles() throws IOException {
Call<MovieAlternativeTitles> call = getManager().moviesService().alternativeTitles(TestData.MOVIE_ID, null);
MovieAlternativeTitles titles = call.execute().body();
assertThat(titles).isNotNull();
assertThat(titles.id).isEqualTo(TestData.MOVIE_ID);
assertThat(titles.titles).isNotEmpty();
assertThat(titles.titles.get(0).iso_3166_1).hasSize(2);
assertThat(titles.titles.get(0).title).isNotEmpty();
}
@Test
public void test_credits() throws IOException {
Call<Credits> call = getManager().moviesService().credits(TestData.MOVIE_ID);
Credits credits = call.execute().body();
assertThat(credits).isNotNull();
assertThat(credits.id).isEqualTo(TestData.MOVIE_ID);
assertThat(credits.cast).isNotEmpty();
assertThat(credits.cast.get(0)).isNotNull();
assertThat(credits.cast.get(0).name).isEqualTo("Edward Norton");
assertThat(credits.crew).isNotEmpty();
}
@Test
public void test_images() throws IOException {
Call<Images> call = getManager().moviesService().images(TestData.MOVIE_ID, null);
Images images = call.execute().body();
assertThat(images).isNotNull();
assertThat(images.id).isEqualTo(TestData.MOVIE_ID);
assertThat(images.backdrops).isNotEmpty();
assertThat(images.backdrops.get(0).file_path).isNotEmpty();
assertThat(images.backdrops.get(0).width).isEqualTo(1280);
assertThat(images.backdrops.get(0).height).isEqualTo(720);
assertThat(images.backdrops.get(0).iso_639_1).isEqualTo("en");
assertThat(images.backdrops.get(0).aspect_ratio).isGreaterThan(1.7f);
assertThat(images.backdrops.get(0).vote_average).isPositive();
assertThat(images.backdrops.get(0).vote_count).isPositive();
assertThat(images.posters).isNotEmpty();
assertThat(images.posters.get(0).file_path).isNotEmpty();
assertThat(images.posters.get(0).width).isPositive();
assertThat(images.posters.get(0).height).isPositive();
assertThat(images.posters.get(0).iso_639_1).hasSize(2);
assertThat(images.posters.get(0).aspect_ratio).isGreaterThan(0.6f);
assertThat(images.posters.get(0).vote_average).isPositive();
assertThat(images.posters.get(0).vote_count).isPositive();
}
@Test
public void test_keywords() throws IOException {
Call<MovieKeywords> call = getManager().moviesService().keywords(TestData.MOVIE_ID);
MovieKeywords keywords = call.execute().body();
assertThat(keywords).isNotNull();
assertThat(keywords.id).isEqualTo(TestData.MOVIE_ID);
assertThat(keywords.keywords.get(0).id).isEqualTo(825);
assertThat(keywords.keywords.get(0).name).isEqualTo("support group");
}
@Test
public void test_release_dates() throws IOException {
Call<ReleaseDatesResults> call = getManager().moviesService().releaseDates(TestData.MOVIE_ID);
ReleaseDatesResults results = call.execute().body();
assertThat(results).isNotNull();
assertThat(results.id).isEqualTo(TestData.MOVIE_ID);
assertThat(results.results).isNotNull();
assertThat(results.results.isEmpty()).isFalse();
ReleaseDatesResult usResult = null;
for (ReleaseDatesResult result : results.results) {
assertThat(result.iso_3166_1).isNotNull();
if (result.iso_3166_1.equals("US")) {
usResult = result;
}
}
assertThat(usResult).isNotNull();
assertThat(usResult.release_dates).isNotNull();
assertThat(usResult.release_dates.isEmpty()).isFalse();
assertThat(usResult.release_dates.get(0).iso_639_1).isNotNull();
assertThat(usResult.release_dates.get(0).certification).isEqualTo("R");
assertThat(usResult.release_dates.get(0).release_date).isEqualTo("1999-10-14T00:00:00.000Z");
assertThat(usResult.release_dates.get(0).note).isNotNull();
assertThat(usResult.release_dates.get(0).type).isBetween(1, 6);
}
@Test
public void test_videos() throws IOException {
Call<Videos> call = getManager().moviesService().videos(TestData.MOVIE_ID, null);
Videos videos = call.execute().body();
assertThat(videos).isNotNull();
assertThat(videos.id).isEqualTo(TestData.MOVIE_ID);
assertThat(videos.results.get(0).id).isNotNull();
assertThat(videos.results.get(0).iso_639_1).isNotNull();
assertThat(videos.results.get(0).key).isNotNull();
assertThat(videos.results.get(0).name).isNotNull();
assertThat(videos.results.get(0).site).isEqualTo("YouTube");
assertThat(videos.results.get(0).size).isNotNull();
assertThat(videos.results.get(0).type).isEqualTo("Trailer");
}
@Test
public void test_translations() throws IOException {
Call<Translations> call = getManager().moviesService().translations(TestData.MOVIE_ID, null);
Translations translations = call.execute().body();
assertThat(translations).isNotNull();
assertThat(translations.id).isEqualTo(TestData.MOVIE_ID);
for (Translations.Translation translation : translations.translations) {
assertThat(translation.name).isNotNull();
assertThat(translation.iso_639_1).isNotNull();
assertThat(translation.english_name).isNotNull();
}
}
@Test
public void test_similar() throws IOException {
Call<MovieResultsPage> call = getManager().moviesService().similar(TestData.MOVIE_ID, 3, null);
MovieResultsPage results = call.execute().body();
assertThat(results).isNotNull();
assertThat(results.page).isNotNull().isPositive();
assertThat(results.total_pages).isNotNull().isPositive();
assertThat(results.total_results).isNotNull().isPositive();
assertThat(results.results).isNotEmpty();
assertThat(results.results.get(0).adult).isEqualTo(false);
assertThat(results.results.get(0).backdrop_path).isNotNull();
assertThat(results.results.get(0).id).isNotNull().isPositive();
assertThat(results.results.get(0).original_title).isNotNull();
assertThat(results.results.get(0).release_date).isNotNull();
assertThat(results.results.get(0).poster_path).isNotNull();
assertThat(results.results.get(0).popularity).isNotNull().isPositive();
assertThat(results.results.get(0).title).isNotNull();
assertThat(results.results.get(0).vote_average).isNotNull().isPositive();
assertThat(results.results.get(0).vote_count).isNotNull().isPositive();
}
@Test
public void test_reviews() throws IOException {
Call<ReviewResultsPage> call = getManager().moviesService().reviews(49026, 1, null);
ReviewResultsPage results = call.execute().body();
assertThat(results).isNotNull();
assertThat(results.id).isNotNull();
assertThat(results.page).isNotNull().isPositive();
assertThat(results.total_pages).isNotNull().isPositive();
assertThat(results.total_results).isNotNull().isPositive();
assertThat(results.results).isNotEmpty();
assertThat(results.results.get(0).id).isNotNull();
assertThat(results.results.get(0).author).isNotNull();
assertThat(results.results.get(0).content).isNotNull();
assertThat(results.results.get(0).url).isNotNull();
}
@Test
public void test_lists() throws IOException {
Call<ListResultsPage> call = getManager().moviesService().lists(49026, 1, null);
ListResultsPage results = call.execute().body();
assertThat(results).isNotNull();
assertThat(results.id).isNotNull();
assertThat(results.page).isNotNull().isPositive();
assertThat(results.total_pages).isNotNull().isPositive();
assertThat(results.total_results).isNotNull().isPositive();
assertThat(results.results).isNotEmpty();
assertThat(results.results.get(0).id).isNotNull();
assertThat(results.results.get(0).description).isNotNull();
assertThat(results.results.get(0).favorite_count).isNotNull().isPositive();
assertThat(results.results.get(0).item_count).isNotNull().isPositive();
assertThat(results.results.get(0).iso_639_1).isNotNull();
assertThat(results.results.get(0).name).isNotNull();
assertThat(results.results.get(0).poster_path).isNotNull();
}
@Test
public void test_latest() throws IOException {
Call<Movie> call = getManager().moviesService().latest();
Movie movie = call.execute().body();
// Latest movie might not have a complete TMDb entry, but should at least some basic properties.
assertThat(movie).isNotNull();
assertThat(movie.id).isPositive();
assertThat(movie.title).isNotEmpty();
}
@Test
public void test_upcoming() throws IOException {
Call<MovieResultsPage> call = getManager().moviesService().upcoming(null, null);
MovieResultsPage page = call.execute().body();
assertThat(page).isNotNull();
assertThat(page.results).isNotEmpty();
}
@Test
public void test_nowPlaying() throws IOException {
Call<MovieResultsPage> call = getManager().moviesService().nowPlaying(null, null);
MovieResultsPage page = call.execute().body();
assertThat(page).isNotNull();
assertThat(page.results).isNotEmpty();
}
@Test
public void test_popular() throws IOException {
Call<MovieResultsPage> call = getManager().moviesService().popular(null, null);
MovieResultsPage page = call.execute().body();
assertThat(page).isNotNull();
assertThat(page.results).isNotEmpty();
}
@Test
public void test_topRated() throws IOException {
Call<MovieResultsPage> call = getManager().moviesService().topRated(null, null);
MovieResultsPage page = call.execute().body();
assertThat(page).isNotNull();
assertThat(page.results).isNotEmpty();
}
}
|
package com.wpetit.projecthome.generator;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import com.jayway.jsonpath.JsonPath;
import com.wpetit.projecthome.generator.dto.EnvironmentDto;
import com.wpetit.projecthome.generator.dto.EnvironmentLinkDto;
import com.wpetit.projecthome.generator.dto.JenkinsConfigurationDto;
import com.wpetit.projecthome.generator.dto.LinkDto;
import com.wpetit.projecthome.generator.dto.ProjectDto;
import com.wpetit.projecthome.generator.dto.SonarConfigurationDto;
import com.wpetit.projecthome.generator.dto.ToolDto;
import com.wpetit.projecthome.generator.services.ProjectService;
/**
* The {@link ProjectServiceIT} class.
*
* @author wpetit
*
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ProjectServiceIT {
/** The restTemplate. **/
@Autowired
private TestRestTemplate restTemplate;
/**
* Test method for {@link ProjectService#addProject(ProjectDto)}.
*/
@Test
public void testAddProject() {
final ProjectDto projectDto = new ProjectDto();
projectDto.setName("my-project");
final HttpEntity<ProjectDto> entity = new HttpEntity<>(projectDto);
final ResponseEntity<String> response = restTemplate.exchange("/project-home-generator/project", HttpMethod.PUT,
entity, String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
final String expected = "{name:\"my-project\"}";
JSONAssert.assertEquals(expected, response.getBody(), false);
}
/**
* Test method for {@link ProjectService#getProject(Long)}.
*/
@Test
public void testGetProject() {
final ProjectDto projectDto = new ProjectDto();
projectDto.setName("my-project");
final HttpEntity<ProjectDto> entity = new HttpEntity<>(projectDto);
final ResponseEntity<String> projectResponse = restTemplate.exchange("/project-home-generator/project",
HttpMethod.PUT, entity, String.class);
final Integer projectId = JsonPath.read(projectResponse.getBody(), "$.id");
final ResponseEntity<String> response = restTemplate.getForEntity("/project-home-generator/project/{id}",
String.class, projectId);
assertEquals(HttpStatus.OK, response.getStatusCode());
final String expected = "{name:\"my-project\"}";
JSONAssert.assertEquals(expected, response.getBody(), false);
}
/**
* Test method for {@link ProjectService#getProject(Long)} with unknown
* project.
*/
@Test
public void testGetProjectUnknown() {
final Integer projectId = 98000;
final ResponseEntity<String> response = restTemplate.getForEntity("/project-home-generator/project/{id}",
String.class, projectId);
assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode());
}
/**
* Test method for
* {@link ProjectService#addJenkinsConfiguration(Long, JenkinsConfigurationDto)}.
*/
@Test
public void testAddJenkinsConfiguration() {
// create project
final ProjectDto projectDto = new ProjectDto();
projectDto.setName("my-project");
final HttpEntity<ProjectDto> projectEntity = new HttpEntity<>(projectDto);
final ResponseEntity<String> projectResponse = restTemplate.exchange("/project-home-generator/project",
HttpMethod.PUT, projectEntity, String.class);
final Integer projectId = JsonPath.read(projectResponse.getBody(), "$.id");
// add jenkins conf
final JenkinsConfigurationDto jenkinsConfigurationDto = new JenkinsConfigurationDto();
jenkinsConfigurationDto.setUrl("http://ci.wpetit.com/jenkins");
jenkinsConfigurationDto.setJobsName(Arrays.asList("job1"));
final HttpEntity<JenkinsConfigurationDto> entity = new HttpEntity<>(jenkinsConfigurationDto);
final ResponseEntity<String> response = restTemplate.exchange("/project-home-generator/project/{id}/jenkins",
HttpMethod.PUT, entity, String.class, projectId);
assertEquals(HttpStatus.OK, response.getStatusCode());
final String expected = "{\"url\":\"http://ci.wpetit.com/jenkins\",\"jobsName\":[\"job1\"],\"projectId\":"
+ projectId + "}";
JSONAssert.assertEquals(expected, response.getBody(), false);
}
/**
* Test method for {@link ProjectService#getJenkinsConfiguration(Long)}.
*/
@Test
public void testGetJenkinsConfiguration() {
// create project
final ProjectDto projectDto = new ProjectDto();
projectDto.setName("my-project");
final HttpEntity<ProjectDto> projectEntity = new HttpEntity<>(projectDto);
final ResponseEntity<String> projectResponse = restTemplate.exchange("/project-home-generator/project",
HttpMethod.PUT, projectEntity, String.class);
final Integer projectId = JsonPath.read(projectResponse.getBody(), "$.id");
// add jenkins conf
final JenkinsConfigurationDto jenkinsConfigurationDto = new JenkinsConfigurationDto();
jenkinsConfigurationDto.setUrl("http://ci.wpetit.com/jenkins");
jenkinsConfigurationDto.setJobsName(Arrays.asList("job1"));
final HttpEntity<JenkinsConfigurationDto> entity = new HttpEntity<>(jenkinsConfigurationDto);
restTemplate.exchange("/project-home-generator/project/{id}/jenkins", HttpMethod.PUT, entity, String.class,
projectId);
final ResponseEntity<String> response = restTemplate
.getForEntity("/project-home-generator/project/{id}/jenkins", String.class, projectId);
final String expected = "{\"url\":\"http://ci.wpetit.com/jenkins\",\"jobsName\":[\"job1\"],\"projectId\":"
+ projectId + "}";
JSONAssert.assertEquals(expected, response.getBody(), false);
}
/**
* Test method for {@link ProjectService#getJenkinsConfiguration(Long)} with
* unknown project.
*/
@Test
public void testGetJenkinsConfigurationUnknownProject() {
final Integer projectId = 98000;
final ResponseEntity<String> response = restTemplate
.getForEntity("/project-home-generator/project/{id}/jenkins", String.class, projectId);
assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode());
}
/**
* Test method for
* {@link ProjectService#addSonarConfiguration(Long, SonarConfigurationDto)}.
*/
@Test
public void testAddSonarConfiguration() {
// create project
final ProjectDto projectDto = new ProjectDto();
projectDto.setName("my-project");
final HttpEntity<ProjectDto> projectEntity = new HttpEntity<>(projectDto);
final ResponseEntity<String> projectResponse = restTemplate.exchange("/project-home-generator/project",
HttpMethod.PUT, projectEntity, String.class);
final Integer projectId = JsonPath.read(projectResponse.getBody(), "$.id");
// add sonar conf
final SonarConfigurationDto sonarConfigurationDto = new SonarConfigurationDto();
sonarConfigurationDto.setUrl("http://ci.wpetit.com/sonar");
sonarConfigurationDto.setResourceNames(Arrays.asList("res1"));
final HttpEntity<SonarConfigurationDto> entity = new HttpEntity<>(sonarConfigurationDto);
final ResponseEntity<String> response = restTemplate.exchange("/project-home-generator/project/{id}/sonar",
HttpMethod.PUT, entity, String.class, projectId);
assertEquals(HttpStatus.OK, response.getStatusCode());
final String expected = "{\"url\":\"http://ci.wpetit.com/sonar\",\"resourceNames\":[\"res1\"],\"projectId\":"
+ projectId + "}";
JSONAssert.assertEquals(expected, response.getBody(), false);
}
/**
* Test method for {@link ProjectService#getSonarConfiguration(Long)}.
*/
@Test
public void testGetSonarConfiguration() {
// create project
final ProjectDto projectDto = new ProjectDto();
projectDto.setName("my-project");
final HttpEntity<ProjectDto> projectEntity = new HttpEntity<>(projectDto);
final ResponseEntity<String> projectResponse = restTemplate.exchange("/project-home-generator/project",
HttpMethod.PUT, projectEntity, String.class);
final Integer projectId = JsonPath.read(projectResponse.getBody(), "$.id");
// add sonar conf
final SonarConfigurationDto sonarConfigurationDto = new SonarConfigurationDto();
sonarConfigurationDto.setUrl("http://ci.wpetit.com/sonar");
sonarConfigurationDto.setResourceNames(Arrays.asList("res1"));
final HttpEntity<SonarConfigurationDto> entity = new HttpEntity<>(sonarConfigurationDto);
restTemplate.exchange("/project-home-generator/project/{id}/sonar", HttpMethod.PUT, entity, String.class,
projectId);
final ResponseEntity<String> response = restTemplate.getForEntity("/project-home-generator/project/{id}/sonar",
String.class, projectId);
final String expected = "{\"url\":\"http://ci.wpetit.com/sonar\",\"resourceNames\":[\"res1\"],\"projectId\":"
+ projectId + "}";
JSONAssert.assertEquals(expected, response.getBody(), false);
}
/**
* Test method for {@link ProjectService#getSonarConfiguration(Long)}.
*/
@Test
public void testGetSonarConfigurationUnknownProject() {
final Integer projectId = 99000;
final ResponseEntity<String> response = restTemplate.getForEntity("/project-home-generator/project/{id}/sonar",
String.class, projectId);
assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode());
}
/**
* Test method for {@link ProjectService#addTool(Long, ToolDto)}.
*/
@Test
public void testAddTool() {
// create project
final ProjectDto projectDto = new ProjectDto();
projectDto.setName("my-project");
final HttpEntity<ProjectDto> projectEntity = new HttpEntity<>(projectDto);
final ResponseEntity<String> projectResponse = restTemplate.exchange("/project-home-generator/project",
HttpMethod.PUT, projectEntity, String.class);
final Integer projectId = JsonPath.read(projectResponse.getBody(), "$.id");
// add tool
final ToolDto toolDto = new ToolDto();
toolDto.setUrl("http://ci.wpetit.com/nexus");
toolDto.setName("Nexus");
final HttpEntity<ToolDto> entity = new HttpEntity<>(toolDto);
final ResponseEntity<String> response = restTemplate.exchange("/project-home-generator/project/{id}/tool",
HttpMethod.PUT, entity, String.class, projectId);
assertEquals(HttpStatus.OK, response.getStatusCode());
final String expected = "{\"url\":\"http://ci.wpetit.com/nexus\",\"name\":\"Nexus\",\"projectId\":" + projectId
+ "}";
JSONAssert.assertEquals(expected, response.getBody(), false);
}
/**
* Test method for {@link ProjectService#addLink(Long, LinkDto)}.
*/
@Test
public void testAddLink() {
// create project
final ProjectDto projectDto = new ProjectDto();
projectDto.setName("my-project");
final HttpEntity<ProjectDto> projectEntity = new HttpEntity<>(projectDto);
final ResponseEntity<String> projectResponse = restTemplate.exchange("/project-home-generator/project",
HttpMethod.PUT, projectEntity, String.class);
final Integer projectId = JsonPath.read(projectResponse.getBody(), "$.id");
// add link
final LinkDto linkDto = new LinkDto();
linkDto.setUrl("http://ci.wpetit.com/link");
linkDto.setName("link1");
linkDto.setImage("http://ci.wpetit.com/link.png");
final HttpEntity<LinkDto> entity = new HttpEntity<>(linkDto);
final ResponseEntity<String> response = restTemplate.exchange("/project-home-generator/project/{id}/link",
HttpMethod.PUT, entity, String.class, projectId);
assertEquals(HttpStatus.OK, response.getStatusCode());
final String expected = "{\"url\":\"http:
+ projectId + "}";
JSONAssert.assertEquals(expected, response.getBody(), false);
}
/**
* Test method for
* {@link ProjectService#addEnvironment(Long, EnvironmentDto)}.
*/
@Test
public void testAddEnvironment() {
// create project
final ProjectDto projectDto = new ProjectDto();
projectDto.setName("my-project");
final HttpEntity<ProjectDto> projectEntity = new HttpEntity<>(projectDto);
final ResponseEntity<String> projectResponse = restTemplate.exchange("/project-home-generator/project",
HttpMethod.PUT, projectEntity, String.class);
final Integer projectId = JsonPath.read(projectResponse.getBody(), "$.id");
// add environment
final EnvironmentDto environmentDto = new EnvironmentDto();
environmentDto.setName("env1");
final HttpEntity<EnvironmentDto> entity = new HttpEntity<>(environmentDto);
final ResponseEntity<String> response = restTemplate.exchange(
"/project-home-generator/project/{id}/environment", HttpMethod.PUT, entity, String.class, projectId);
assertEquals(HttpStatus.OK, response.getStatusCode());
final String expected = "{\"name\":\"env1\",\"projectId\":" + projectId + "}";
JSONAssert.assertEquals(expected, response.getBody(), false);
}
/**
* Test method for
* {@link ProjectService#addEnvironmentLink(Long, EnvironmentLinkDto)}.
*/
@Test
public void testAddEnvironmentLink() {
// create project
final ProjectDto projectDto = new ProjectDto();
projectDto.setName("my-project");
final HttpEntity<ProjectDto> projectEntity = new HttpEntity<>(projectDto);
final ResponseEntity<String> projectResponse = restTemplate.exchange("/project-home-generator/project",
HttpMethod.PUT, projectEntity, String.class);
final Integer projectId = JsonPath.read(projectResponse.getBody(), "$.id");
// add environment
final EnvironmentDto environmentDto = new EnvironmentDto();
environmentDto.setName("env1");
final HttpEntity<EnvironmentDto> environmentEntity = new HttpEntity<>(environmentDto);
final ResponseEntity<String> environmentResponse = restTemplate.exchange(
"/project-home-generator/project/{id}/environment", HttpMethod.PUT, environmentEntity, String.class,
projectId);
final Integer environmentId = JsonPath.read(environmentResponse.getBody(), "$.id");
// add environment link
final EnvironmentLinkDto environmentLinkDto = new EnvironmentLinkDto();
environmentLinkDto.setName("envLink1");
environmentLinkDto.setUrl("http://ci.wpetit.com/envLink1");
final HttpEntity<EnvironmentLinkDto> entity = new HttpEntity<>(environmentLinkDto);
final ResponseEntity<String> response = restTemplate.exchange(
"/project-home-generator/project/{id}/environment/{environmentId}/link", HttpMethod.PUT, entity,
String.class, projectId, environmentId);
assertEquals(HttpStatus.OK, response.getStatusCode());
final String expected = "{\"name\":\"envLink1\",\"url\":\"http://ci.wpetit.com/envLink1\",\"environmentId\":"
+ environmentId + "}";
JSONAssert.assertEquals(expected, response.getBody(), false);
}
/**
* Test method for
* {@link ProjectService#generateProjectConfiguration(Long)}.
*/
@Test
public void testGenerateProjectConfiguration() throws Exception {
// add project
final ProjectDto projectDto = new ProjectDto();
projectDto.setName("project1");
final HttpEntity<ProjectDto> projectEntity = new HttpEntity<>(projectDto);
final ResponseEntity<String> projectResponse = restTemplate.exchange("/project-home-generator/project",
HttpMethod.PUT, projectEntity, String.class);
final Integer projectId = JsonPath.read(projectResponse.getBody(), "$.id");
// add environment
final EnvironmentDto environmentDto = new EnvironmentDto();
environmentDto.setName("env1");
final HttpEntity<EnvironmentDto> environmentEntity = new HttpEntity<>(environmentDto);
final ResponseEntity<String> environmentResponse = restTemplate.exchange(
"/project-home-generator/project/{id}/environment", HttpMethod.PUT, environmentEntity, String.class,
projectId);
final Integer environmentId = JsonPath.read(environmentResponse.getBody(), "$.id");
// add environment link
final EnvironmentLinkDto environmentLinkDto = new EnvironmentLinkDto();
environmentLinkDto.setName("Project-home");
environmentLinkDto.setUrl("http://ci.wpetit.com");
final HttpEntity<EnvironmentLinkDto> envLinkEntity = new HttpEntity<>(environmentLinkDto);
restTemplate.exchange("/project-home-generator/project/{id}/environment/{environmentId}/link", HttpMethod.PUT,
envLinkEntity, String.class, projectId, environmentId);
// add tool
final ToolDto toolDto = new ToolDto();
toolDto.setUrl("http://ci.wpetit.com/nexus");
toolDto.setName("Nexus");
final HttpEntity<ToolDto> toolEntity = new HttpEntity<>(toolDto);
restTemplate.exchange("/project-home-generator/project/{id}/tool", HttpMethod.PUT, toolEntity, String.class,
projectId);
// add link
final LinkDto linkDto = new LinkDto();
linkDto.setUrl("http://ci.wpetit.com/nexus");
linkDto.setName("Nexus");
linkDto.setImage("images/nexus.png");
final HttpEntity<LinkDto> linkEntity = new HttpEntity<>(linkDto);
restTemplate.exchange("/project-home-generator/project/{id}/link", HttpMethod.PUT, linkEntity, String.class,
projectId);
// add jenkins configuration
final JenkinsConfigurationDto jenkinsConfigurationDto = new JenkinsConfigurationDto();
jenkinsConfigurationDto.setUrl("http://ci.wpetit.com/jenkins");
jenkinsConfigurationDto.setJobsName(Arrays.asList("project-home-generator"));
final HttpEntity<JenkinsConfigurationDto> jenkinsEntity = new HttpEntity<>(jenkinsConfigurationDto);
restTemplate.exchange("/project-home-generator/project/{id}/jenkins", HttpMethod.PUT, jenkinsEntity,
String.class, projectId);
// add sonar conf
final SonarConfigurationDto sonarConfigurationDto = new SonarConfigurationDto();
sonarConfigurationDto.setUrl("http://ci.wpetit.com/sonar");
sonarConfigurationDto.setResourceNames(Arrays.asList("com.wpetit:project-home-generator"));
final HttpEntity<SonarConfigurationDto> sonarEntity = new HttpEntity<>(sonarConfigurationDto);
restTemplate.exchange("/project-home-generator/project/{id}/sonar", HttpMethod.PUT, sonarEntity, String.class,
projectId);
final String expected = "{\"applicationName\":\"project1\",\"applicationLogo\":null,\"applicationLinks\":[{\"linkLogo\":\"images/nexus.png\",\"linkName\":\"Nexus\",\"linkUrl\":\"http:
+ "\"env\":[{\"name\":\"env1\",\"urls\":[{\"urlName\":\"Project-home\",\"url\":\"http://ci.wpetit.com\"}]}],"
+ "\"jenkinsUrl\":\"http://ci.wpetit.com/jenkins\",\"jenkinsBase64UsrPwd\":\"REPLACE_WITH BASE64(USER_JENKINS:PWD_JENKINS)\","
+ "\"sonarBase64UsrPwd\":\"REPLACE_WITH BASE64(USER_SONAR:PWD_SONAR)\",\"sonarUrl\":\"http://ci.wpetit.com/sonar\","
+ "\"jenkinsJobs\":[\"project-home-generator\"],\"sonarResources\":[\"com.wpetit:project-home-generator\"]}";
final ResponseEntity<String> response = restTemplate.getForEntity("/project-home-generator/project/{id}/conf",
String.class, projectId);
assertEquals(HttpStatus.OK, response.getStatusCode());
JSONAssert.assertEquals(expected, response.getBody(), false);
}
}
|
package edu.harvard.iq.dataverse.util.json;
import edu.harvard.iq.dataverse.ControlledVocabularyValue;
import edu.harvard.iq.dataverse.DatasetField;
import edu.harvard.iq.dataverse.DatasetFieldCompoundValue;
import edu.harvard.iq.dataverse.DatasetFieldServiceBean;
import edu.harvard.iq.dataverse.DatasetFieldType;
import edu.harvard.iq.dataverse.DatasetFieldValue;
import java.io.StringReader;
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 javax.json.Json;
import javax.json.JsonObject;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author michael
*/
public class JsonParserTest {
MockDatasetFieldSvc mockDatasetFieldSvc = null;
DatasetFieldType keywordType;
DatasetFieldType descriptionType;
DatasetFieldType subjectType;
DatasetFieldType pubIdType;
DatasetFieldType compoundSingleType;
public JsonParserTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
mockDatasetFieldSvc = new MockDatasetFieldSvc();
keywordType = mockDatasetFieldSvc.add(new DatasetFieldType("keyword", "primitive", true));
descriptionType = mockDatasetFieldSvc.add( new DatasetFieldType("description", "primitive", false) );
subjectType = mockDatasetFieldSvc.add(new DatasetFieldType("subject", "controlledVocabulary", true));
subjectType.setAllowControlledVocabulary(true);
subjectType.setControlledVocabularyValues( Arrays.asList(
new ControlledVocabularyValue(1l, "mgmt", subjectType),
new ControlledVocabularyValue(2l, "law", subjectType),
new ControlledVocabularyValue(3l, "cs", subjectType)
));
pubIdType = mockDatasetFieldSvc.add(new DatasetFieldType("publicationIdType", "controlledVocabulary", false));
pubIdType.setAllowControlledVocabulary(true);
pubIdType.setControlledVocabularyValues( Arrays.asList(
new ControlledVocabularyValue(1l, "ark", pubIdType),
new ControlledVocabularyValue(2l, "doi", pubIdType),
new ControlledVocabularyValue(3l, "url", pubIdType)
));
compoundSingleType = mockDatasetFieldSvc.add(new DatasetFieldType("coordinate", "compound", false));
Set<DatasetFieldType> childTypes = new HashSet<>();
childTypes.add( mockDatasetFieldSvc.add(new DatasetFieldType("lat", "primitive", false)) );
childTypes.add( mockDatasetFieldSvc.add(new DatasetFieldType("lon", "primitive", false)) );
for ( DatasetFieldType t : childTypes ) {
t.setParentDatasetFieldType(compoundSingleType);
}
compoundSingleType.setChildDatasetFieldTypes(childTypes);
}
@After
public void tearDown() {
}
/*
@Test
public void testParseField_compound_single() throws JsonParseException {
JsonObject json = json("{\n" +
" \"value\": [\n" +
" {\n" +
" \"value\": \"500.3\",\n" +
" \"typeClass\": \"primitive\",\n" +
" \"multiple\": false,\n" +
" \"typeName\": \"lon\"\n" +
" },\n" +
" {\n" +
" \"value\": \"300.3\",\n" +
" \"typeClass\": \"primitive\",\n" +
" \"multiple\": false,\n" +
" \"typeName\": \"lat\"\n" +
" }\n" +
" ],\n" +
" \"typeClass\": \"compound\",\n" +
" \"multiple\": false,\n" +
" \"typeName\": \"coordinate\"\n" +
"}");
JsonParser instance = new JsonParser( mockDatasetFieldSvc, null );
DatasetField result = instance.parseField(json);
assertEquals( compoundSingleType, result.getDatasetFieldType() );
DatasetFieldCompoundValue val = result.getDatasetFieldCompoundValues().get(0);
DatasetField lon = new DatasetField();
lon.setDatasetFieldType( mockDatasetFieldSvc.findByName("lon"));
lon.setDatasetFieldValues( Collections.singletonList(new DatasetFieldValue(lon, "500.3")) );
DatasetField lat = new DatasetField();
lat.setDatasetFieldType( mockDatasetFieldSvc.findByName("lat"));
lat.setDatasetFieldValues( Collections.singletonList(new DatasetFieldValue(lat, "300.3")) );
List<DatasetField> actual = val.getChildDatasetFields();
assertEquals( lon, actual.get(0) );
assertEquals( lat, actual.get(1) );
}
@Test
public void testParseField_controlled_single() throws JsonParseException {
JsonObject json = json("{\n" +
" \"value\": \"ark\",\n" +
" \"typeClass\": \"controlledVocabulary\",\n" +
" \"multiple\": false,\n" +
" \"typeName\": \"publicationIdType\"\n" +
" }");
JsonParser instance = new JsonParser( mockDatasetFieldSvc, null );
DatasetField result = instance.parseField(json);
assertEquals( pubIdType, result.getDatasetFieldType() );
assertEquals( pubIdType.getControlledVocabularyValue("ark"), result.getSingleControlledVocabularyValue() );
}
@Test
public void testParseField_controlled_multi() throws JsonParseException {
JsonObject json = json("{\n" +
" \"value\": [\n" +
" \"mgmt\",\n" +
" \"cs\"\n" +
" ],\n" +
" \"typeClass\": \"controlledVocabulary\",\n" +
" \"multiple\": true,\n" +
" \"typeName\": \"subject\"\n" +
" }");
JsonParser instance = new JsonParser( mockDatasetFieldSvc, null );
DatasetField result = instance.parseField(json);
assertEquals( subjectType, result.getDatasetFieldType() );
assertEquals( Arrays.asList( subjectType.getControlledVocabularyValue("mgmt"),
subjectType.getControlledVocabularyValue("cs")),
result.getControlledVocabularyValues()
);
}
*/
/**
* Test of parsePrimitiveField method, of class JsonParser.
*/
/*
@Test
public void testParseField_primitive_multi() throws JsonParseException {
JsonObject json = json("{\n" +
" \"value\": [\n" +
" \"data\",\n" +
" \"set\",\n" +
" \"sample\"\n" +
" ],\n" +
" \"typeClass\": \"primitive\",\n" +
" \"multiple\": true,\n" +
" \"typeName\": \"keyword\"\n" +
" }");
JsonParser instance = new JsonParser( mockDatasetFieldSvc, null );
DatasetField result = instance.parseField(json);
assertEquals( keywordType, result.getDatasetFieldType() );
assertEquals( Arrays.asList("data","set","sample"), result.getValues() );
}
@Test
public void testParseField_primitive_single() throws JsonParseException {
JsonObject json = json("{\n" +
" \"value\": \"data\",\n" +
" \"typeClass\": \"primitive\",\n" +
" \"multiple\": false,\n" +
" \"typeName\": \"description\"\n" +
" }");
JsonParser instance = new JsonParser( mockDatasetFieldSvc, null );
DatasetField result = instance.parseField(json);
assertEquals( descriptionType, result.getDatasetFieldType() );
assertEquals( "data", result.getValue() );
}
@Test(expected=JsonParseException.class)
public void testParseField_primitive_NEType() throws JsonParseException {
JsonObject json = json("{\n" +
" \"value\": \"data\",\n" +
" \"typeClass\": \"primitive\",\n" +
" \"multiple\": false,\n" +
" \"typeName\": \"no-such-type\"\n" +
" }");
JsonParser instance = new JsonParser( mockDatasetFieldSvc, null );
DatasetField result = instance.parseField(json);
assertEquals( descriptionType, result.getDatasetFieldType() );
assertEquals( "data", result.getValue() );
}
*/
JsonObject json( String s ) {
return Json.createReader( new StringReader(s) ).readObject();
}
static class MockDatasetFieldSvc extends DatasetFieldServiceBean {
Map<String, DatasetFieldType> fieldTypes = new HashMap<>();
public DatasetFieldType add( DatasetFieldType t ) {
fieldTypes.put( t.getName(), t);
return t;
}
@Override
public DatasetFieldType findByName( String name ) {
return fieldTypes.get(name);
}
}
}
|
package info.u_team.u_team_test.item;
import info.u_team.u_team_core.item.UItem;
import info.u_team.u_team_test.entity.BetterEnderPearlEntity;
import info.u_team.u_team_test.init.*;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.*;
import net.minecraft.util.*;
import net.minecraft.world.World;
public class BetterEnderPearlItem extends UItem {
public BetterEnderPearlItem() {
super(TestItemGroups.GROUP, new Properties().rarity(Rarity.EPIC));
}
@Override
public ActionResult<ItemStack> onItemRightClick(World world, PlayerEntity player, Hand hand) {
final ItemStack stack = player.getHeldItem(hand);
world.playSound(null, player.getPosX(), player.getPosY(), player.getPosZ(), TestSounds.BETTER_ENDERPEARL_USE.get(), SoundCategory.NEUTRAL, 0.5F, 0.4F / (random.nextFloat() * 0.4F + 1.5F));
if (!world.isRemote) {
final BetterEnderPearlEntity pearl = new BetterEnderPearlEntity(world, player);
pearl.shoot(player, player.rotationPitch, player.rotationYaw, 0.0F, 2.5F, 1.2F);
world.addEntity(pearl);
}
return new ActionResult<>(ActionResultType.SUCCESS, stack);
}
}
|
package net.openhft.chronicle.wire;
import io.github.classgraph.*;
import net.openhft.chronicle.bytes.Bytes;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import javax.sql.rowset.serial.SerialBlob;
import javax.sql.rowset.serial.SerialClob;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.nio.charset.StandardCharsets;
import java.sql.Date;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.List;
import java.util.Queue;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toSet;
import static org.junit.Assert.assertEquals;
final class SerializableObjectTest extends WireTestCommon {
private static final long TIME_MS = 1_000_000_000;
private static final Set<String> IGNORED_PACKAGES = Stream.of(
"jnr.",
"sun.",
"io.github.",
"com.sun.",
"org.junit.",
"org.jcp.xml.dsig.internal.",
"jdk.nashorn.",
"org.easymock.",
"org.omg.",
"org.yaml.",
"com.sun.corba.",
"com.sun.org.",
"com.sun.security.cert.internal",
"javax.management.remote.rmi",
"javax.smartcardio",
"javafx.",
"javax.swing",
"javax.print",
"apple.security"
)
.collect(Collectors.collectingAndThen(toSet(), Collections::unmodifiableSet));
private static final Set<Class<?>> IGNORED_CLASSES = new HashSet<>(Arrays.asList(
DoubleSummaryStatistics.class,
DriverPropertyInfo.class,
SimpleDateFormat.class
));
static {
try {
// change to this because it fails in java11
final Class<?> aClass = Class.forName("com.sun.jndi.toolkit.ctx.Continuation");
IGNORED_CLASSES.add(aClass);
} catch (ClassNotFoundException ignore) {
}
}
private static final Predicate<MethodInfo> CONSTRUCTOR_IS_DEFAULT = methodInfo -> methodInfo.isPublic() && methodInfo.getTypeDescriptor().getTypeParameters().isEmpty();
private static final ClassInfoList.ClassInfoFilter NOT_IGNORED = ci -> IGNORED_PACKAGES.stream().noneMatch(ip -> ci.getPackageName().startsWith(ip));
private static Stream<WireTypeObject> cases() {
return wires()
.flatMap(wt -> mergedObjects().map(o -> new WireTypeObject(wt, o)));
}
private static Stream<Object> mergedObjects() {
Map<String, Object> map = handcraftedObjects()
.collect(Collectors.toMap(o -> {
final Class<?> aClass = o.getClass();
IGNORED_CLASSES.add(aClass);
return aClass.getName();
}, Function.identity()));
reflectedObjects()
.forEach(o -> map.put(o.getClass().getName(), o));
return map.values().stream();
}
private static Stream<Object> handcraftedObjects() {
return Stream.of(
// java.lang
true,
(byte) 1,
(char) '2',
(short) 3,
4,
5L,
6.0f,
7.0,
BigInteger.valueOf(Long.MIN_VALUE),
BigDecimal.valueOf(12.34),
MathContext.DECIMAL32,
// java.sql
new Time(TIME_MS),
new Timestamp(TIME_MS),
new SQLException("Test exception"),
new DriverPropertyInfo("A", "B"),
new Date(TIME_MS),
wrap(() -> new SerialClob("A".toCharArray())),
wrap(() -> new SerialBlob("A".getBytes(StandardCharsets.UTF_8))),
// java.util
compose(new ArrayList<String>(), l -> l.add("a"), l -> l.add("b")),
compose(new BitSet(), bs -> bs.set(10)),
Currency.getAvailableCurrencies().iterator().next(),
DoubleStream.of(1, 2, 3).summaryStatistics(),
compose(new EnumMap<TimeUnit, String>(TimeUnit.class), m -> m.put(TimeUnit.SECONDS, "secs")),
EnumSet.of(TimeUnit.NANOSECONDS, TimeUnit.SECONDS),
new EventObject("A"),
compose(new HashMap<>(), m -> m.put(1, 1)),
compose(new Hashtable<>(), m -> m.put(1, 1)),
compose(new IdentityHashMap<>(), m -> m.put(1, 1)),
IntStream.of(1, 2, 3).summaryStatistics(),
compose(new LinkedHashMap<>(), m -> m.put(2, 2), m -> m.put(1, 1), m -> m.put(3, 3)),
compose(new LinkedHashSet<>(), m -> m.add(2), m -> m.add(1), m -> m.add(3)),
compose(new LinkedList<>(), m -> m.add(2), m -> m.add(1), m -> m.add(3)),
Locale.getAvailableLocales()[1],
Optional.of("A"),
Optional.empty(),
OptionalDouble.of(2),
OptionalDouble.empty(),
OptionalInt.of(2),
OptionalInt.empty(),
OptionalLong.of(2),
OptionalLong.empty(),
compose(new Properties(), p -> p.put("A", 1), p -> p.put("B", 2)),
new SimpleTimeZone(1, "EU"),
compose(new Stack<Integer>(), q -> q.push(2), q -> q.push(1), q -> q.push(3)),
compose(new StringJoiner("[", ", ", "]"), sj -> sj.add("a"), sj -> sj.add("b")),
compose(new TreeMap<>(), m -> m.put(2, 2), m -> m.put(1, 1), m -> m.put(3, 3)),
compose(new TreeSet<>(), m -> m.add(2), m -> m.add(1), m -> m.add(3)),
UUID.randomUUID(),
compose(new Vector<>(), v -> v.add("a"), v -> v.add("b")),
Instant.ofEpochMilli(TIME_MS),
Color.BLUE,
// new MessageFormat("%s%n"),
// InetAddress.getLoopbackAddress(),
new File("file")
).filter(SerializableObjectTest::isSerializableEqualsByObject);
}
private static Object create(ThrowingSupplier s) {
try {
return s.get();
} catch (Exception e) {
throw new AssertionError(e);
}
}
private static Stream<Object> reflectedObjects() {
try (ScanResult scanResult = new ClassGraph().enableSystemJarsAndModules().enableAllInfo().scan()) {
final ClassInfoList widgetClasses = scanResult.getClassesImplementing(Serializable.class)
.filter(ci -> !ci.isAbstract())
.filter(ClassInfo::isPublic)
.filter(NOT_IGNORED)
.filter(ci -> !ci.isAnonymousInnerClass())
.filter(ci -> !ci.extendsSuperclass(LookAndFeel.class)) // These create problems
.filter(ci -> !ci.implementsInterface(DesktopManager.class)) // These create problems
.filter(ci -> ci.getConstructorInfo().stream().anyMatch(CONSTRUCTOR_IS_DEFAULT))
.filter(SerializableObjectTest::isSerializableEquals);
List<Object> objects = widgetClasses.stream()
.filter(c -> !IGNORED_CLASSES.contains(c.loadClass(true)))
.filter(SerializableObjectTest::overridesEqualsObject)
.map(ci -> ci.loadClass(true))
.filter(Objects::nonNull)
.map(SerializableObjectTest::createOrNull)
.filter(Objects::nonNull)
.collect(Collectors.toList());
/*
System.out.println("widgetClasses.size() = " + widgetClasses.size());
System.out.println("objects.size = " + objects.size());
objects.stream()
.map(i -> i.getClass().getName() + " -> " + i)
.forEach(System.out::println);*/
return objects.stream();
}
//return null;
}
private static boolean isSerializableEquals(ClassInfo ci) {
return isSerializableEquals(ci.loadClass(), null);
}
private static boolean isSerializableEqualsByObject(Object o) {
return isSerializableEquals(o.getClass(), o);
}
private static boolean isSerializableEquals(Class aClass, Object o) {
try {
Object source = o == null ? aClass.newInstance() : o;
// sanity check
if (source.toString() == null)
return false;
// can it be serialized
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(source);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
Object source2 = ois.readObject();
if (source instanceof Throwable) {
return source.getClass() == source2.getClass()
&& Objects.equals(((Throwable) source).getMessage(), ((Throwable) source2).getMessage());
} else {
return Objects.equals(source, source2);
}
} catch (InstantiationException | NotSerializableException | IllegalAccessException t) {
return false;
} catch (Throwable t) {
System.out.println(aClass + ": " + t);
return false;
}
}
private static <T> T createOrNull(final Class<T> clazz) {
try {
return clazz.getConstructor().newInstance();
} catch (ReflectiveOperationException ignore) {
return null;
}
}
/*
@Test
void reflectedObjects2() {
try (ScanResult scanResult = new ClassGraph().enableSystemJarsAndModules().enableAllInfo().scan()) {
final ClassInfoList widgetClasses = scanResult.getClassesImplementing(Serializable.class)
.filter(ci -> !ci.isAbstract())
.filter(ClassInfo::isPublic)
.filter(ci -> !IGNORED_PACKAGES.stream().anyMatch(ip -> ci.getPackageName().startsWith(ip)));
widgetClasses.
forEach(System.out::println);
System.out.println("widgetClasses.size() = " + widgetClasses.size());
}
//return null;
}
*/
private static boolean overridesEqualsObject(ClassInfo ci) {
return ci.getMethodInfo("equals").stream()
.anyMatch(m -> {
final MethodParameterInfo[] parameters = m.getParameterInfo();
if (parameters.length != 1)
return false;
final MethodParameterInfo parameter = parameters[0];
if (!Object.class.getName().equals(parameter.getTypeSignatureOrTypeDescriptor().toString()))
return false;
return !m.isNative();
});
}
private static <T, X extends Exception> T wrap(ThrowingSupplier<T, X> supplier) {
try {
return supplier.get();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
@SafeVarargs
private static <T> T compose(final T original,
final Consumer<T>... operations) {
return Stream.of(operations)
.reduce(original, (t, oper) -> {
oper.accept(t);
return t;
}, (a, b) -> a);
}
private static Stream<WireType> wires() {
return Stream.of(WireType.TEXT, WireType.JSON, WireType.BINARY);
}
static void assertEqualEnough(Object a, Object b) {
if (a.getClass() != b.getClass())
assertEquals(a, b);
if (a instanceof Throwable) {
assertEquals(a.getClass(), b.getClass());
assertEquals(((Throwable) a).getMessage(), ((Throwable) b).getMessage());
} else if (a instanceof Queue) {
assertEquals(a.toString(), b.toString());
} else {
assertEquals(a, b);
}
}
@TestFactory
Stream<DynamicTest> test() {
return DynamicTest.stream(cases(), Objects::toString, wireTypeObject -> {
final Object source = wireTypeObject.object;
// Can't handle suclasses of Properties.
if (source instanceof Properties && source.getClass() != Properties.class)
return;
final Bytes<?> bytes = Bytes.allocateElasticDirect();
try {
final Wire wire = wireTypeObject.wireType.apply(bytes);
wire.getValueOut().object((Class) source.getClass(), source);
final Object target = wire.getValueIn().object(source.getClass());
if (!(source instanceof Comparable) || ((Comparable) source).compareTo(target) != 0) {
if (wireTypeObject.wireType == WireType.JSON || source instanceof EnumMap)
assertEquals(source.toString(), target.toString());
else
assertEqualEnough(source, target);
}
} catch (IllegalArgumentException iae) {
// allow JSON to reject types not supported.
if (wireTypeObject.wireType == WireType.JSON)
return;
throw iae;
} finally {
bytes.releaseLast();
}
});
}
@FunctionalInterface
public interface ThrowingSupplier<T, X extends Exception> {
T get() throws X;
}
private static final class WireTypeObject {
WireType wireType;
Object object;
public WireTypeObject(WireType wireType, Object object) {
this.wireType = wireType;
this.object = object;
}
@Override
public String toString() {
try {
return wireType + ", " + object.getClass().getName() + " : " + object;
} catch (Throwable t) {
return t.toString();
}
}
}
}
|
package no.difi.sdp.client.internal;
import no.difi.begrep.sdp.schema_v10.*;
import no.difi.sdp.client.domain.Feil;
import no.difi.sdp.client.domain.Feiltype;
import no.difi.sdp.client.domain.Prioritet;
import no.difi.sdp.client.domain.kvittering.*;
import no.posten.dpost.offentlig.api.representations.EbmsApplikasjonsKvittering;
import no.posten.dpost.offentlig.api.representations.EbmsOutgoingMessage;
import no.posten.dpost.offentlig.api.representations.EbmsPullRequest;
import no.posten.dpost.offentlig.api.representations.Organisasjonsnummer;
import org.joda.time.DateTime;
import org.junit.Test;
import org.unece.cefact.namespaces.standardbusinessdocumentheader.StandardBusinessDocument;
import org.unece.cefact.namespaces.standardbusinessdocumentheader.StandardBusinessDocumentHeader;
import java.util.UUID;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
public class KvitteringBuilderTest {
private final KvitteringBuilder kvitteringBuilder = new KvitteringBuilder();
@Test
public void shoud_build_pull_request_with_standard_priority() {
EbmsPullRequest ebmsPullRequest = kvitteringBuilder.buildEbmsPullRequest(new Organisasjonsnummer("123"), Prioritet.NORMAL);
assertThat(ebmsPullRequest.getEbmsMottaker().orgnr.toString()).isEqualTo("123");
assertThat(ebmsPullRequest.prioritet).isEqualTo(EbmsOutgoingMessage.Prioritet.STANDARD);
}
@Test
public void shoud_build_pull_request_with_standard_high_priority() {
EbmsPullRequest ebmsPullRequest = kvitteringBuilder.buildEbmsPullRequest(new Organisasjonsnummer("123"), Prioritet.PRIORITERT);
assertThat(ebmsPullRequest.getEbmsMottaker().orgnr.toString()).isEqualTo("123");
assertThat(ebmsPullRequest.prioritet).isEqualTo(EbmsOutgoingMessage.Prioritet.PRIORITERT);
}
@Test
public void should_build_aapnings_kvittering() {
EbmsApplikasjonsKvittering ebmsKvittering = createEbmsAapningsKvittering();
AapningsKvittering aapningKvittering = (AapningsKvittering) kvitteringBuilder.buildForretningsKvittering(ebmsKvittering);
assertNotNull(aapningKvittering.getKonversasjonsId());
assertNotNull(aapningKvittering.getTidspunkt());
}
@Test
public void should_build_leverings_kvittering() {
EbmsApplikasjonsKvittering ebmsKvittering = createEbmsLeveringsKvittering();
LeveringsKvittering leveringsKvittering = (LeveringsKvittering) kvitteringBuilder.buildForretningsKvittering(ebmsKvittering);
assertNotNull(leveringsKvittering.getKonversasjonsId());
assertNotNull(leveringsKvittering.getTidspunkt());
}
@Test
public void should_build_varsling_feilet_epost_kvittering() {
EbmsApplikasjonsKvittering ebmsKvittering = createEbmsVarslingFeiletKvittering(SDPVarslingskanal.EPOST);
VarslingFeiletKvittering varslingFeiletKvittering = (VarslingFeiletKvittering) kvitteringBuilder.buildForretningsKvittering(ebmsKvittering);
assertNotNull(varslingFeiletKvittering.getKonversasjonsId());
assertNotNull(varslingFeiletKvittering.getTidspunkt());
assertThat(varslingFeiletKvittering.getBeskrivelse()).isEqualTo("Varsling feilet 'Viktig brev'");
assertThat(varslingFeiletKvittering.getVarslingskanal()).isEqualTo(Varslingskanal.EPOST);
}
@Test
public void should_build_varsling_feilet_sms_kvittering() {
EbmsApplikasjonsKvittering ebmsKvittering = createEbmsVarslingFeiletKvittering(SDPVarslingskanal.SMS);
VarslingFeiletKvittering varslingFeiletKvittering = (VarslingFeiletKvittering) kvitteringBuilder.buildForretningsKvittering(ebmsKvittering);
assertNotNull(varslingFeiletKvittering.getKonversasjonsId());
assertNotNull(varslingFeiletKvittering.getTidspunkt());
assertThat((varslingFeiletKvittering).getBeskrivelse()).isEqualTo("Varsling feilet 'Viktig brev'");
assertThat((varslingFeiletKvittering).getVarslingskanal()).isEqualTo(Varslingskanal.SMS);
}
@Test
public void should_build_tilbaketrekking_ok_kvittering() {
EbmsApplikasjonsKvittering ebmsKvittering = createEbmsTilbaketrekkingsKvittering(SDPTilbaketrekkingsstatus.OK);
TilbaketrekkingsKvittering tilbaketrekkingsKvittering = (TilbaketrekkingsKvittering) kvitteringBuilder.buildForretningsKvittering(ebmsKvittering);
assertNotNull(tilbaketrekkingsKvittering.getKonversasjonsId());
assertNotNull(tilbaketrekkingsKvittering.getTidspunkt());
assertThat(tilbaketrekkingsKvittering.getBeskrivelse()).isEqualTo("Tilbaketrekking av 'Viktig brev'");
assertThat(tilbaketrekkingsKvittering.getStatus()).isEqualTo(TilbaketrekkingsStatus.OK);
}
@Test
public void should_build_tilbaketrekking_feilet_kvittering() {
EbmsApplikasjonsKvittering ebmsKvittering = createEbmsTilbaketrekkingsKvittering(SDPTilbaketrekkingsstatus.FEILET);
TilbaketrekkingsKvittering tilbaketrekkingsKvittering = (TilbaketrekkingsKvittering) kvitteringBuilder.buildForretningsKvittering(ebmsKvittering);
assertNotNull(tilbaketrekkingsKvittering.getKonversasjonsId());
assertNotNull(tilbaketrekkingsKvittering.getTidspunkt());
assertThat((tilbaketrekkingsKvittering).getBeskrivelse()).isEqualTo("Tilbaketrekking av 'Viktig brev'");
assertThat((tilbaketrekkingsKvittering).getStatus()).isEqualTo(TilbaketrekkingsStatus.FEILET);
}
@Test
public void should_build_klient_feil() {
EbmsApplikasjonsKvittering ebmsKvittering = createEbmsFeil(SDPFeiltype.KLIENT);
Feil feil = (Feil) kvitteringBuilder.buildForretningsKvittering(ebmsKvittering);
assertNotNull(feil.getKonversasjonsId());
assertNotNull(feil.getTidspunkt());
assertThat(feil.getFeiltype()).isEqualTo(Feiltype.KLIENT);
assertThat(feil.getDetaljer()).isEqualTo("Feilinformasjon");
}
@Test
public void should_build_server_feil() {
EbmsApplikasjonsKvittering ebmsKvittering = createEbmsFeil(SDPFeiltype.SERVER);
Feil feil = (Feil) kvitteringBuilder.buildForretningsKvittering(ebmsKvittering);
assertNotNull(feil.getKonversasjonsId());
assertNotNull(feil.getTidspunkt());
assertThat(feil.getFeiltype()).isEqualTo(Feiltype.SERVER);
assertThat(feil.getDetaljer()).isEqualTo("Feilinformasjon");
}
private EbmsApplikasjonsKvittering createEbmsFeil(SDPFeiltype feiltype) {
SDPFeil sdpFeil = new SDPFeil(randomUUID(), null, DateTime.now(), feiltype, "Feilinformasjon");
return createEbmsKvittering(sdpFeil);
}
private EbmsApplikasjonsKvittering createEbmsAapningsKvittering() {
SDPKvittering aapningsKvittering = new SDPKvittering(randomUUID(), null, DateTime.now(), null, null, new SDPAapning(), null);
return createEbmsKvittering(aapningsKvittering);
}
private EbmsApplikasjonsKvittering createEbmsLeveringsKvittering() {
SDPKvittering leveringsKvittering = new SDPKvittering(randomUUID(), null, DateTime.now(), null, null, null, new SDPLevering());
return createEbmsKvittering(leveringsKvittering);
}
private EbmsApplikasjonsKvittering createEbmsVarslingFeiletKvittering(SDPVarslingskanal varslingskanal) {
SDPVarslingfeilet sdpVarslingfeilet = new SDPVarslingfeilet(varslingskanal, "Varsling feilet 'Viktig brev'");
SDPKvittering varslingFeiletKvittering = new SDPKvittering(randomUUID(), null, DateTime.now(), null, sdpVarslingfeilet, null, null);
return createEbmsKvittering(varslingFeiletKvittering);
}
private EbmsApplikasjonsKvittering createEbmsTilbaketrekkingsKvittering(SDPTilbaketrekkingsstatus status) {
SDPTilbaketrekkingsresultat sdpTilbaketrekkingsresultat = new SDPTilbaketrekkingsresultat(status, "Tilbaketrekking av 'Viktig brev'");
SDPKvittering tilbaketrekkingsKvittering = new SDPKvittering(randomUUID(), null, DateTime.now(), sdpTilbaketrekkingsresultat, null, null, null);
return createEbmsKvittering(tilbaketrekkingsKvittering);
}
private EbmsApplikasjonsKvittering createEbmsKvittering(Object sdpMelding) {
Organisasjonsnummer avsender = new Organisasjonsnummer("123");
Organisasjonsnummer mottaker = new Organisasjonsnummer("456");
StandardBusinessDocument sbd = new StandardBusinessDocument(new StandardBusinessDocumentHeader(), sdpMelding);
return EbmsApplikasjonsKvittering.create(avsender, mottaker, sbd).build();
}
private static String randomUUID() {
return UUID.randomUUID().toString();
}
}
|
package org.n52.movingcode.runtime.test;
import org.apache.log4j.BasicConfigurator;
import org.junit.Test;
import org.n52.movingcode.runtime.feed.FeedGenerator;
import org.n52.movingcode.runtime.feed.FeedTemplate;
public class FeedGeneratorTest {
// the source folder where the packages currently reside
private static final String repositoryFolder = "src/test/resources/testpackages";
// the target folder where the feed shall be created / updated
private static final String webFolder = "D:\\atomFeedWeb2";
private static final String baseURL = "http://gis.geo.tu-dresden.de/gpfeed/";
private static final String feedFileName = "gpfeed.xml";
private static final String feedTitle = "FeedTitle";
private static final String feedSubtitle = "FeedSubTitle";
private static final String feedAuthor = "Matthias Mueller";
@Test
public void makeFeed() {
BasicConfigurator.configure();
FeedGenerator.generate(feedFileName, webFolder, baseURL, repositoryFolder, staticFeedTemplate());
}
private static final FeedTemplate staticFeedTemplate(){
FeedTemplate ft = new FeedTemplate(baseURL + feedFileName);
ft.setFeedTitle(feedTitle);
ft.setFeedSubtitle(feedSubtitle);
ft.setFeedAuthorName(feedAuthor);
ft.setFeedAuthorEmail(null);
return ft;
}
}
|
package org.threadly.util.debug;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Iterator;
import org.junit.Before;
import org.junit.Test;
import org.threadly.util.debug.Profiler.ThreadSample;
@SuppressWarnings("javadoc")
public class FilteredStackProfilerTest extends ProfilerTest {
@Before
@Override
public void setup() {
profiler = new FilteredStackProfiler(".");
}
@Test
@Override
public void constructorTest() {
int testPollInterval = Profiler.DEFAULT_POLL_INTERVAL_IN_MILLIS * 10;
FilteredStackProfiler p;
p = new FilteredStackProfiler("^org\\.threadly\\.");
assertNotNull(p.filteredThreadStore.threadTraces);
assertTrue(p.filteredThreadStore.threadTraces.isEmpty());
assertEquals(Profiler.DEFAULT_POLL_INTERVAL_IN_MILLIS, p.filteredThreadStore.pollIntervalInMs);
assertNull(p.filteredThreadStore.collectorThread.get());
assertNull(p.filteredThreadStore.dumpingThread);
assertNotNull(p.startStopLock);
assertTrue(p.filteredThreadStore.filter.test(
new StackTraceElement[] { new StackTraceElement("org.threadly.SomeClass", "run", null, 42) }));
assertFalse(p.filteredThreadStore.filter.test(
new StackTraceElement[] { new StackTraceElement("java.lang.Thread", "run", null, 456) }));
p = new FilteredStackProfiler(stack -> Arrays.stream(stack).anyMatch(e -> e.getClassName().startsWith("org.threadly.")));
assertNotNull(p.filteredThreadStore.threadTraces);
assertTrue(p.filteredThreadStore.threadTraces.isEmpty());
assertEquals(Profiler.DEFAULT_POLL_INTERVAL_IN_MILLIS, p.filteredThreadStore.pollIntervalInMs);
assertNull(p.filteredThreadStore.collectorThread.get());
assertNull(p.filteredThreadStore.dumpingThread);
assertNotNull(p.startStopLock);
assertTrue(p.filteredThreadStore.filter.test(
new StackTraceElement[] { new StackTraceElement("org.threadly.SomeClass", "run", null, 42) }));
assertFalse(p.filteredThreadStore.filter.test(
new StackTraceElement[] { new StackTraceElement("java.lang.Thread", "run", null, 456) }));
p = new FilteredStackProfiler(testPollInterval, "^org\\.threadly\\.");
assertNotNull(p.filteredThreadStore.threadTraces);
assertTrue(p.filteredThreadStore.threadTraces.isEmpty());
assertEquals(testPollInterval, p.filteredThreadStore.pollIntervalInMs);
assertNull(p.filteredThreadStore.collectorThread.get());
assertNull(p.filteredThreadStore.dumpingThread);
assertNotNull(p.startStopLock);
assertTrue(p.filteredThreadStore.filter.test(
new StackTraceElement[] { new StackTraceElement("org.threadly.SomeClass", "run", null, 42) }));
assertFalse(p.filteredThreadStore.filter.test(
new StackTraceElement[] { new StackTraceElement("java.lang.Thread", "run", null, 456) }));
p = new FilteredStackProfiler(
testPollInterval, stack -> Arrays.stream(stack).anyMatch(e -> e.getClassName().startsWith("org.threadly.")));
assertNotNull(p.filteredThreadStore.threadTraces);
assertTrue(p.filteredThreadStore.threadTraces.isEmpty());
assertEquals(testPollInterval, p.filteredThreadStore.pollIntervalInMs);
assertNull(p.filteredThreadStore.collectorThread.get());
assertNull(p.filteredThreadStore.dumpingThread);
assertNotNull(p.startStopLock);
assertTrue(p.filteredThreadStore.filter.test(
new StackTraceElement[] { new StackTraceElement("org.threadly.SomeClass", "run", null, 42) }));
assertFalse(p.filteredThreadStore.filter.test(
new StackTraceElement[] { new StackTraceElement("java.lang.Thread", "run", null, 456) }));
}
@Test
public void getProfileThreadsIteratorEmptyTest() {
FilteredStackProfiler profiler = new FilteredStackProfiler("^no matching stack frames$");
Iterator<?> it = profiler.pStore.getProfileThreadsIterator();
assertNotNull(it);
assertFalse(it.hasNext());
}
@Override
@Test
public void getProfileThreadsIteratorTest() {
// This should only see this one thread executing this one particular test
FilteredStackProfiler profiler = new FilteredStackProfiler(
"^(app//)?org\\.threadly\\.util\\.debug\\.FilteredStackProfilerTest\\.getProfileThreadsIteratorTest");
Iterator<? extends ThreadSample> it = profiler.pStore.getProfileThreadsIterator();
assertNotNull(it);
assertTrue(it.hasNext());
assertTrue(it.next().getThread() == Thread.currentThread());
assertFalse(it.hasNext());
}
@Override
@SuppressWarnings("unused")
@Test(expected = IllegalArgumentException.class)
public void constructorFail() {
new FilteredStackProfiler(-1, ".");
}
}
|
/*
* StubbornNetworkReliabiltyTest.java
*
*
*/
package org.prevayler.foundation;
import java.io.IOException;
import junit.framework.TestCase;
import org.prevayler.foundation.network.Network;
import org.prevayler.foundation.network.NetworkImpl;
import org.prevayler.foundation.network.ObjectReceiver;
import org.prevayler.foundation.network.Service;
import org.prevayler.foundation.network.StubbornNetworkImpl;
/**
* Test the reliabilty of the Stubborn Network.
*
* This test creates 2 "mock instances of prevayler". 1 acting
* as a primary prevayler, and the other acting as a slave
* (replicator).
*
* It sits on top of a Network Proxy Implementation that can break
* and recover.
*/
public class StubbornNetworkReliabiltyTest extends TestCase {
private MockService serverService;
private Network serverNetwork;
private Network clientNetwork1;
private Network clientNetwork2;
private ClientReceiver client1Receiver;
private ClientReceiver client2Receiver;
private NetworkProxy networkProxy;
private final boolean printing = true;
public void setUp() {
serverService = new MockService();
// NewNetworkMock mockNetwork = new NewNetworkMock();
serverNetwork = new StubbornNetworkImpl();
clientNetwork1 = new StubbornNetworkImpl();
clientNetwork2 = new StubbornNetworkImpl();
networkProxy = new NetworkProxy();
client1Receiver = new ClientReceiver("client1");
client2Receiver = new ClientReceiver("client2");
}
public void testNormal() throws Exception {
String testSequence = "ABCDEFGHIJKL";
int serverPort = 8765;
int proxyPort = 5678;
networkProxy.startProxy(proxyPort, serverPort);
serverService.setObjectsToSend(testSequence);
serverService.setFrequency(100);
serverService.commenceService(serverNetwork, serverPort);
client1Receiver.commenceReceiving(clientNetwork1, proxyPort, testSequence.length());
client2Receiver.commenceReceiving(clientNetwork2, proxyPort, testSequence.length());
//while ((client1Receiver.getState() != Thread.State.TERMINATED) ||
// (client2Receiver.getState() != Thread.State.TERMINATED)) {
Thread.sleep(1000);
client1Receiver.checkReceived(testSequence);
client2Receiver.checkReceived(testSequence);
serverService.closeDown();
}
public class MockService implements Service {
private String objectsToSend;
private int frequency;
private Network network;
private int port;
public void setObjectsToSend (String objectsToSend) {
this.objectsToSend = objectsToSend;
}
public void setFrequency(int millisecs) {
this.frequency = millisecs;
}
public void commenceService(Network network, int port) throws Exception {
this.network = network;
this.port = port;
network.startService(this, port);
}
public ObjectReceiver serverFor(ObjectReceiver client) {
return new MockObjectReceiver(objectsToSend, frequency, client);
}
public void closeDown() throws Exception {
network.stopService(port);
}
}
public class MockObjectReceiver extends Thread implements ObjectReceiver {
private final String objectsToSend;
private final int frequency;
private final ObjectReceiver networkClient;
private int sent = 0;
private boolean openForBusiness;
MockObjectReceiver (String objectsToSend, int frequency, ObjectReceiver networkClient) {
this.objectsToSend = objectsToSend;
this.frequency = frequency;
this.networkClient = networkClient;
this.setName("Server Service Thread");
start();
}
public void run () {
openForBusiness = true;
for (sent = 0; sent < objectsToSend.length(); sent++) {
rest();
send();
}
openForBusiness = false;
}
private void rest() {
try {sleep(frequency);}
catch (InterruptedException unEx) {};
}
private void send() {
try {
networkClient.receive(objectsToSend.substring(sent, sent+1));
} catch (IOException unex) {
fail("Server received an IOException");
}
}
public void receive(Object object) throws IOException {
fail("receive called on server");
}
/* (non-Javadoc)
* @see org.prevayler.foundation.network.ObjectReceiver#close()
*/
public void close() throws IOException {
if (openForBusiness) {
fail("close called unexpectedly");
}
}
}
public class ClientReceiver extends Thread implements ObjectReceiver {
private StringBuffer received;
private int expectedLth;
private Network network;
private int port;
private ObjectReceiver networkProvider;
private String threadName;
ClientReceiver (String threadName) {
received = new StringBuffer();
this.threadName = threadName;
}
public void checkReceived (String sent) {
assertEquals("Received " + received + " Expected " + sent,
sent.length(), received.length());
for (int i = 0; i < sent.length(); i++) {
assertEquals("Received " + received + " Expected " + sent,
sent.charAt(i),received.charAt(i));
}
}
public void commenceReceiving(Network network, int port, int expectedLth) {
this.expectedLth = expectedLth;
this.port = port;
this.network = network;
this.setName(threadName);
this.setDaemon(true);
start();
}
public void run() {
connect();
sleepTillFinished();
shutdown();
}
private void connect() {
try {
networkProvider = network.findServer("localhost", port, this);
} catch (IOException unex) {
fail("Client received an IO Exception " + unex);
}
}
private void shutdown() {
try {
networkProvider.close();
} catch (IOException unex) {
fail("Client received an Exception on close " + unex);
}
}
private synchronized void sleepTillFinished() {
try {
wait();
} catch (InterruptedException expected) {
}
}
public void receive(Object object) throws IOException {
if (object instanceof String) {
String s = (String) object;
received.append(s);
if (printing) {
System.out.println(this.getName() + " received " + s);
}
if (received.length() >= expectedLth) {
finished();
}
} else {
fail("Unexpected object received " + object);
}
}
private synchronized void finished() {
notify();
}
public void close() throws IOException {
}
}
public class NetworkProxy implements Service {
private Network network;
private int targetPort;
NetworkProxy() {
network = new NetworkImpl();
}
public void startProxy (int listeningPort, int targetPort) throws IOException {
this.targetPort = targetPort;
network.startService(this, listeningPort);
}
/* (non-Javadoc)
* @see org.prevayler.foundation.network.Service#serverFor(org.prevayler.foundation.network.ObjectReceiver)
*/
public ObjectReceiver serverFor(ObjectReceiver client) {
return new ProxyReceiver(network, targetPort, client);
}
}
public class ProxyReceiver extends Thread implements ObjectReceiver {
private Network network;
private ObjectReceiver proxyServer;
private int port;
private ObjectReceiver proxyClient;
ProxyReceiver (Network network, int port, ObjectReceiver client) {
this.network = network;
this.port = port;
this.proxyServer = client;
start();
waitConnected();
}
private synchronized void waitConnected() {
try {
wait();
} catch (InterruptedException unex) {
throw new RuntimeException(unex);
}
}
public void run() {
connect();
finishConnect();
monitorMessages();
}
private synchronized void finishConnect() {
notify();
}
private synchronized void monitorMessages() {
while (true) {
try {
wait();
} catch (InterruptedException ex) {}
}
}
public void connect() {
try {
proxyClient = network.findServer("localhost",port,new MockClient(this));
} catch (IOException unex) {
throw new RuntimeException(unex);
}
}
public void receive(Object object) throws IOException {
messageFromClientForServer(object);
}
public void close() throws IOException {
// TODO Auto-generated method stub
}
public void messageFromServerForClient(Object object) {
try {
proxyServer.receive(object);
} catch (IOException ioex) {
}
}
public void messageFromClientForServer(Object object) {
try {
proxyClient.receive(object);
} catch (IOException ioex) {
}
}
}
public class MockClient implements ObjectReceiver {
private ProxyReceiver proxy;
MockClient(ProxyReceiver proxy) {
this.proxy = proxy;
}
public void receive(Object object) throws IOException {
proxy.messageFromServerForClient(object);
}
public void close() throws IOException {
}
}
}
|
package com.health.input;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Objects;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import com.health.Record;
import com.health.Table;
/**
* Implements a parser for xls input files.
*
*/
public final class XlsParser implements Parser {
/**
* Given a path to a xls file and an input descriptor, parses the input file into a {@link Table}.
*
* @param path
* the path of the input file.
* @param config
* the input descriptor.
* @return a table representing the parsed input file.
* @throws IOException
* if any IO errors occur.
* @throws InputException
* if any input errors occur.
*/
@Override
public Table parse(final String path, final InputDescriptor config) throws InputException,
IOException {
Objects.requireNonNull(path);
Objects.requireNonNull(config);
Table table = config.buildTable();
FileInputStream io = new FileInputStream(path);
HSSFWorkbook wb = new HSSFWorkbook(io);
StartCell startCell = config.getStartCell();
int rowCount = 0;
int columnsCount = config.getColumns().size();
Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
// if at start row or beyond
if (rowCount >= startCell.getStartRow()) {
Record tableRow = new Record(table);
int columnCountTableRow = 0;
for (int i = startCell.getStartColumn() - 1; i < columnsCount + startCell.getStartColumn()
- 1; i++) {
switch (table.getColumn(columnCountTableRow).getType()) {
case String:
tableRow.setValue(columnCountTableRow, row.getCell(i).toString());
break;
case Number:
tableRow.setValue(columnCountTableRow, Double.parseDouble(row.getCell(i).toString()));
break;
case Date:
if (config.getDateFormat() != null) {
try {
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern(config.getDateFormat());
LocalDate dateValue = LocalDate.parse(row.getCell(i).toString(), formatter);
tableRow.setValue(columnCountTableRow, dateValue);
} catch (DateTimeParseException e) {
break;
}
}
break;
default:
// The type was null, this should never happen
assert false;
throw new InputException("Internal error.", new Exception(
"Column.getType() returned null."));
}
columnCountTableRow++;
}
}
rowCount++;
}
wb.close();
table = InputFunctions.deleteLastLines(table, config);
return table;
}
}
|
package app.hongs.dh;
import app.hongs.util.Dict;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
*
* @author Hongs
*/
public class MergeMore
{
protected List<Map> rows;
public MergeMore(List<Map> rows)
{
this.rows = rows;
}
/**
* ID
*
* @param map
* @param keys
*/
private void maping(Map<Object, List> map, List rows, String... keys)
{
Iterator it = rows.iterator();
W:while (it.hasNext())
{
Object row = it.next();
Object obj = row;
for (int i = 0; i < keys.length; i ++)
{
if (obj instanceof Map )
{
obj = ((Map)obj).get(keys[i]);
}
else
if (obj instanceof List)
{
int j = keys.length - i;
String[] keyz = new String[j];
System.arraycopy(keys,i, keyz,0,j);
this.maping(map, (List) obj, keyz);
continue W;
}
else
{
continue W;
}
}
if (obj == null)
{
continue;
}
/**
*
*
*
* append
*/
if (obj instanceof Collection)
{
for (Object xbj : ( Collection) obj)
{
if (map.containsKey(xbj))
{
map.get(xbj ).add(row);
}
else
{
List lst = new ArrayList();
map.put(xbj , lst);
lst.add(row);
}
}
}
else
if (obj instanceof Object [ ])
{
for (Object xbj : ( Object [ ]) obj)
{
if (map.containsKey(xbj))
{
map.get(xbj ).add(row);
}
else
{
List lst = new ArrayList();
map.put(xbj , lst);
lst.add(row);
}
}
}
else
{
if (map.containsKey(obj))
{
map.get(obj ).add(row);
}
else
{
List lst = new ArrayList();
map.put(obj , lst);
lst.add(row);
}
}
}
}
/**
* ID
*
* @param keys
* @return
*/
public Map<Object, List> maping(String... keys)
{
Map<Object, List> map = new HashMap();
maping(map, rows, keys);
return map;
}
/**
* ID
*
* @param key "."
* @return
*/
public Map<Object, List> mapped(String key)
{
Map<Object, List> map = new HashMap();
maping(map, rows, key.split( "\\." ));
return map;
}
/**
*
* mixing,extend,append
*
* @param map
* @param sub ,
*/
public void pading(Map<Object, List> map, String... sub)
{
Object raw = new HashMap();
// null List
for (int i = 0 ; i < sub.length ; i ++)
{
if(sub[i] == null && i != 0)
{
sub = Arrays.copyOfRange(sub, 0, i);
raw = new ArrayList();
break;
}
}
for (Map.Entry<Object, List> t : map.entrySet())
{
List<Map> lst = t.getValue();
for (Map row : lst)
{
Dict.setValue(row, raw, ( Object[ ] ) sub );
}
}
}
/**
*
* mixing,extend,append
*
* @param map
* @param sub "."
*/
public void padded(Map<Object, List> map, String sub)
{
pading(map, sub.split("\\."));
}
/**
*
* @param iter
* @param map
* @param col
* @param sub , , null
*/
public void mixing(Iterator iter, Map<Object, List> map, String col, String... sub)
{
Map row, raw;
List lst;
Object rid;
// while (sub.length != 0 && sub[ 0 ] == null )
// sub = Arrays.copyOfRange(sub, 1, sub.length);
/**
* null
* null
*
*/
if (sub.length == 0 || sub[0] == null)
{
sub = null;
}
while (iter.hasNext())
{
raw = ( Map ) iter.next( );
rid = raw.get(col);
lst = ( List ) map.get(rid);
if (lst == null)
{
//throw new HongsException(0x10c0, "Line nums is null");
continue;
}
Iterator it = lst.iterator();
while (it.hasNext())
{
row = (Map) it.next();
if ( null != sub )
{
Dict.setValue(row, raw, (Object[]) sub);
}
else
{
raw.putAll(row);
row.putAll(raw);
}
}
}
}
public void mixing(List<Map> rows, Map<Object, List > map, String col, String... sub)
{
mixing(rows.iterator(), map, col, sub);
}
public void mixing(List<Map> rows, String key, String col, String... sub)
{
mixing(rows, mapped ( key ), col, sub);
}
/**
*
* @param iter
* @param map
* @param col
* @param sub ,
*/
public void extend(Iterator iter, Map<Object, List> map, String col, String sub)
{
Map row, raw;
List lst;
Object rid;
while (iter.hasNext())
{
raw = ( Map ) iter.next( );
rid = raw.get(col);
lst = ( List ) map.get(rid);
if (lst == null)
{
//throw new HongsException(0x10c0, "Line nums is null");
continue;
}
Iterator it = lst.iterator();
while (it.hasNext())
{
row = (Map) it.next();
if ( null != sub )
{
row.put(sub, raw);
}
else
{
raw.putAll(row);
row.putAll(raw);
}
}
}
}
public void extend(List<Map> rows, Map<Object, List > map, String col, String sub)
{
extend(rows.iterator(), map, col, sub);
}
public void extend(List<Map> rows, String key, String col, String sub)
{
extend(rows, mapped ( key ), col, sub);
}
/**
*
* @param iter
* @param map
* @param col
* @param sub ,
*/
public void append(Iterator iter, Map<Object, List> map, String col, String sub)
{
Map row, raw;
List lst;
Object rid;
while (iter.hasNext())
{
raw = ( Map ) iter.next( );
rid = raw.get(col);
lst = ( List ) map.get(rid);
if (lst == null)
{
//throw new HongsException(0x10c0, "Line nums is null");
continue;
}
Iterator it = lst.iterator();
while (it.hasNext())
{
row = (Map) it.next();
if (row.containsKey(sub))
{
(( List ) row.get(sub)).add(raw);
}
else
{
List lzt = new ArrayList();
row.put(sub , lzt);
lzt.add(raw);
}
}
}
}
public void append(List<Map> rows, Map<Object, List > map, String col, String sub)
{
append(rows.iterator(), map, col, sub);
}
public void append(List<Map> rows, String key, String col, String sub)
{
append(rows, mapped ( key ), col, sub);
}
}
|
// This file is part of Serleena.
// Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle.
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
package com.kyloth.serleena.presentation;
/**
* E' l'interfaccia realizzata dal Presenter della schermata di selezione
* del percorso.
*
* @author Tobia Tesan <tobia.tesan@gmail.com>
* @version 1.0
* @since 1.0
*/
public interface ITrackSelectionPresenter extends IPresenter {
void activateTrack(int index) throws IllegalArgumentException;
}
|
package org.gluu.oxtrust.service.scim2.interceptor;
import org.apache.commons.lang.StringUtils;
import org.gluu.oxtrust.ldap.service.IPersonService;
import org.gluu.oxtrust.model.GluuCustomPerson;
import org.gluu.oxtrust.model.exception.SCIMException;
import org.gluu.oxtrust.model.scim2.*;
import org.gluu.oxtrust.model.scim2.extensions.Extension;
import org.gluu.oxtrust.model.scim2.user.Meta;
import org.gluu.oxtrust.model.scim2.user.UserResource;
import org.gluu.oxtrust.model.scim2.util.IntrospectUtil;
import org.gluu.oxtrust.service.scim2.ExtensionService;
import org.gluu.oxtrust.ws.rs.scim2.BaseScimWebService;
import org.gluu.oxtrust.ws.rs.scim2.UserService;
import org.gluu.oxtrust.model.scim2.util.ResourceValidator;
import org.joda.time.format.ISODateTimeFormat;
import org.slf4j.Logger;
import org.xdi.ldap.model.SortOrder;
import javax.annotation.Priority;
import javax.decorator.Decorator;
import javax.decorator.Delegate;
import javax.enterprise.inject.Any;
import javax.inject.Inject;
import javax.interceptor.Interceptor;
import javax.ws.rs.core.Response;
import java.lang.reflect.Field;
import java.util.*;
import static org.gluu.oxtrust.model.scim2.Constants.MAX_COUNT;
@Priority(Interceptor.Priority.APPLICATION)
@Decorator
public class UserServiceDecorator extends BaseScimWebService implements UserService {
@Inject
private Logger log;
@Inject @Delegate @Any
UserService userService;
@Inject
private IPersonService personService;
@Inject
private ExtensionService extService;
private void assignMetaInformation(BaseScimResource resource){
//Generate some meta information (this replaces the info client passed in the request)
long now=new Date().getTime();
String val= ISODateTimeFormat.dateTime().withZoneUTC().print(now);
Meta meta=new Meta();
meta.setResourceType(BaseScimResource.getType(resource.getClass()));
meta.setCreated(val);
meta.setLastModified(val);
//For version attritute: Service provider support for this attribute is optional and subject to the service provider's support for versioning
//For location attribute: this will be set after current user creation at LDAP
resource.setMeta(meta);
}
private String executeDefaultValidation(BaseScimResource resource){
String error=null;
try {
ResourceValidator rv=new ResourceValidator(resource, extService.getResourceExtensions(resource.getClass()));
rv.validateRequiredAttributes();
rv.validateSchemasAttribute();
rv.validateValidableAttributes();
//By section 7 of RFC 7643, we are not forced to constrain attribute values when they have a list of canonical values associated
//rv.validateCanonicalizedAttributes();
rv.validateExtendedAttributes();
}
catch (SCIMException e){
error=e.getMessage();
}
return error;
}
private Response validateExistenceOfUser(String id){
Response response=null;
GluuCustomPerson person = personService.getPersonByInum(id);
if (person==null) {
log.info("Person with inum {} not found", id);
response = getErrorResponse(Response.Status.NOT_FOUND, "Resource " + id + " not found");
}
return response;
}
public Response createUser(UserResource user, String attrsList, String excludedAttrsList, String authorization) {
Response response;
String error=executeDefaultValidation(user);
if (error==null) {
assignMetaInformation(user);
//Proceed with actual implementation of createUser method
response = userService.createUser(user, attrsList, excludedAttrsList, authorization);
}
else {
log.error("Validation check at createUser returned: {}", error);
response = getErrorResponse(Response.Status.BAD_REQUEST, ErrorScimType.INVALID_VALUE, error);
}
return response;
}
public Response updateUser(UserResource user, String id, String attrsList, String excludedAttrsList, String authorization) {
Response response;
String error=executeDefaultValidation(user);
if (error==null) {
//Proceed with actual implementation of updateUser method
response = userService.updateUser(user, id, attrsList, excludedAttrsList, authorization);
}
else {
log.error("Validation check at updateUser returned: {}", error);
response = getErrorResponse(Response.Status.BAD_REQUEST, ErrorScimType.INVALID_VALUE, error);
}
return response;
}
public Response deleteUser(String id, String authorization){
Response response=validateExistenceOfUser(id);
if (response==null)
//Proceed with actual implementation of deleteUser method
response=userService.deleteUser(id, authorization);
return response;
}
public Response getUserById(String id, String attrsList, String excludedAttrsList, String authorization){
Response response=validateExistenceOfUser(id);
if (response==null)
//Proceed with actual implementation of getUserById method
response=userService.getUserById(id, attrsList, excludedAttrsList, authorization);
return response;
}
private boolean isAttributeRecognized(Class<? extends BaseScimResource> cls, String attribute){
boolean valid;
Extension ext=extService.extensionOfAttribute(cls, attribute);
valid=ext!=null;
if (!valid) {
attribute = extService.stripDefaultSchema(cls, attribute);
Field f=IntrospectUtil.findFieldFromPath(cls, attribute);
valid= f!=null;
}
return valid;
}
private Response prepareSearchRequest(String filter, String sortBy, String sortOrder, Integer startIndex, Integer count,
String attrsList, String excludedAttrsList, SearchRequest request){
Response response;
count=count==null ? MAX_COUNT : count;
if (count>=0){
if (count <= MAX_COUNT) {
startIndex = (startIndex == null || startIndex < 1) ? 1 : startIndex;
sortBy = StringUtils.isEmpty(sortBy) ? "userName" : sortBy;
if (isAttributeRecognized(UserResource.class, sortBy)) {
if (StringUtils.isEmpty(sortOrder) || !sortOrder.equals(SortOrder.DESCENDING.getValue()))
sortOrder = SortOrder.ASCENDING.getValue();
request.setAttributes(attrsList);
request.setExcludedAttributes(excludedAttrsList);
request.setFilter(filter);
request.setSortBy(sortBy);
request.setSortOrder(sortOrder);
request.setStartIndex(startIndex);
request.setCount(count);
response=null;
}
else
response = getErrorResponse(Response.Status.BAD_REQUEST, ErrorScimType.INVALID_PATH, "sortBy parameter value not recognized");
}
else
response = getErrorResponse(Response.Status.BAD_REQUEST, ErrorScimType.TOO_MANY, "Maximum number of results per page is " + MAX_COUNT);
}
else
response=getErrorResponse(Response.Status.BAD_REQUEST, ErrorScimType.INVALID_VALUE, "count parameter must be non-negative");
return response;
}
public Response searchUsers(String filter, String sortBy, String sortOrder, Integer startIndex, Integer count,
String attrsList, String excludedAttrsList, String authorization){
SearchRequest searchReq=new SearchRequest();
Response response=prepareSearchRequest(filter, sortBy, sortOrder, startIndex, count, attrsList, excludedAttrsList, searchReq);
if (response==null)
response = userService.searchUsers(searchReq.getFilter(), searchReq.getSortBy(), searchReq.getSortOrder(),
searchReq.getStartIndex(), searchReq.getCount(), searchReq.getAttributes(),
searchReq.getExcludedAttributes(), authorization);
return response;
}
public Response searchUsersPost(SearchRequest searchRequest, String authorization){
SearchRequest searchReq=new SearchRequest();
Response response=prepareSearchRequest(searchRequest.getFilter(), searchRequest.getSortBy(), searchRequest.getSortOrder(),
searchRequest.getStartIndex(), searchRequest.getCount(), searchRequest.getAttributes(), searchRequest.getExcludedAttributes(), searchReq);
if (response==null)
response = userService.searchUsersPost(searchReq, authorization);
return response;
}
}
|
package com.jme3.scene;
import com.jme3.bounding.BoundingBox;
import com.jme3.bounding.BoundingVolume;
import com.jme3.collision.Collidable;
import com.jme3.collision.CollisionResults;
import com.jme3.collision.bih.BIHTree;
import com.jme3.export.*;
import com.jme3.material.Material;
import com.jme3.material.RenderState;
import com.jme3.math.*;
import com.jme3.scene.VertexBuffer.*;
import com.jme3.scene.mesh.*;
import com.jme3.util.*;
import com.jme3.util.IntMap.Entry;
import com.jme3.util.clone.Cloner;
import com.jme3.util.clone.JmeCloneable;
import java.io.IOException;
import java.nio.*;
import java.util.ArrayList;
/**
* <code>Mesh</code> is used to store rendering data.
* <p>
* All visible elements in a scene are represented by meshes.
* Meshes may contain three types of geometric primitives:
* <ul>
* <li>Points - Every vertex represents a single point in space.
* Points can also be used for {@link RenderState#setPointSprite(boolean) point
* sprite} mode.</li>
* <li>Lines - 2 vertices represent a line segment, with the width specified
* via {@link Material#getAdditionalRenderState()} and {@link RenderState#setLineWidth(float)}.</li>
* <li>Triangles - 3 vertices represent a solid triangle primitive. </li>
* </ul>
*
* @author Kirill Vainer
*/
public class Mesh implements Savable, Cloneable, JmeCloneable {
/**
* The mode of the Mesh specifies both the type of primitive represented
* by the mesh and how the data should be interpreted.
*/
public enum Mode {
/**
* A primitive is a single point in space. The size of {@link Mode#Points points} are
* determined via the vertex shader's <code>gl_PointSize</code> output.
*/
Points(true),
/**
* A primitive is a line segment. Every two vertices specify
* a single line. {@link Material#getAdditionalRenderState()}
* and {@link RenderState#setLineWidth(float)} can be used
* to set the width of the lines.
*/
Lines(true),
/**
* A primitive is a line segment. The first two vertices specify
* a single line, while subsequent vertices are combined with the
* previous vertex to make a line. {@link Material#getAdditionalRenderState()}
* and {@link RenderState#setLineWidth(float)} can
* be used to set the width of the lines.
*/
LineStrip(false),
/**
* Identical to {@link #LineStrip} except that at the end
* the last vertex is connected with the first to form a line.
* {@link Material#getAdditionalRenderState()}
* and {@link RenderState#setLineWidth(float)} can be used
* to set the width of the lines.
*/
LineLoop(false),
/**
* A primitive is a triangle. Each 3 vertices specify a single
* triangle.
*/
Triangles(true),
/**
* Similar to {@link #Triangles}, the first 3 vertices
* specify a triangle, while subsequent vertices are combined with
* the previous two to form a triangle.
*/
TriangleStrip(false),
/**
* Similar to {@link #Triangles}, the first 3 vertices
* specify a triangle, each 2 subsequent vertices are combined
* with the very first vertex to make a triangle.
*/
TriangleFan(false),
/**
* A combination of various triangle modes. It is best to avoid
* using this mode as it may not be supported by all renderers.
* The {@link Mesh#setModeStart(int[]) mode start points} and
* {@link Mesh#setElementLengths(int[]) element lengths} must
* be specified for this mode.
*/
Hybrid(false),
/**
* Used for Tessellation only. Requires to set the number of vertices
* for each patch (default is 3 for triangle tessellation)
*/
Patch(true);
private boolean listMode = false;
private Mode(boolean listMode) {
this.listMode = listMode;
}
/**
* Returns true if the specified mode is a list mode (meaning
* ,it specifies the indices as a linear list and not some special
* format).
* Will return true for the types {@link #Points}, {@link #Lines} and
* {@link #Triangles}.
*
* @return true if the mode is a list type mode
*/
public boolean isListMode() {
return listMode;
}
}
/**
* The bounding volume that contains the mesh entirely.
* By default a BoundingBox (AABB).
*/
private BoundingVolume meshBound = new BoundingBox();
private CollisionData collisionTree = null;
private SafeArrayList<VertexBuffer> buffersList = new SafeArrayList<>(VertexBuffer.class);
private IntMap<VertexBuffer> buffers = new IntMap<>();
private VertexBuffer[] lodLevels;
private float pointSize = 1;
private float lineWidth = 1;
private transient int vertexArrayID = -1;
private int vertCount = -1;
private int elementCount = -1;
private int instanceCount = -1;
private int patchVertexCount = 3; //only used for tessellation
private int maxNumWeights = -1; // only if using skeletal animation
private int[] elementLengths;
private int[] modeStart;
private Mode mode = Mode.Triangles;
private SafeArrayList<MorphTarget> morphTargets;
/**
* Creates a new mesh with no {@link VertexBuffer vertex buffers}.
*/
public Mesh() {
}
/**
* Create a shallow clone of this Mesh. The {@link VertexBuffer vertex
* buffers} are shared between this and the clone mesh, the rest
* of the data is cloned.
*
* @return A shallow clone of the mesh
*/
@Override
public Mesh clone() {
try {
Mesh clone = (Mesh) super.clone();
clone.meshBound = meshBound.clone();
clone.collisionTree = collisionTree != null ? collisionTree : null;
clone.buffers = buffers.clone();
clone.buffersList = new SafeArrayList<>(VertexBuffer.class, buffersList);
clone.vertexArrayID = -1;
if (elementLengths != null) {
clone.elementLengths = elementLengths.clone();
}
if (modeStart != null) {
clone.modeStart = modeStart.clone();
}
return clone;
} catch (CloneNotSupportedException ex) {
throw new AssertionError();
}
}
/**
* Creates a deep clone of this mesh.
* The {@link VertexBuffer vertex buffers} and the data inside them
* is cloned.
*
* @return a deep clone of this mesh.
*/
public Mesh deepClone() {
try {
Mesh clone = (Mesh) super.clone();
clone.meshBound = meshBound != null ? meshBound.clone() : null;
// TODO: Collision tree cloning
//clone.collisionTree = collisionTree != null ? collisionTree : null;
clone.collisionTree = null; // it will get re-generated in any case
clone.buffers = new IntMap<>();
clone.buffersList = new SafeArrayList<>(VertexBuffer.class);
for (VertexBuffer vb : buffersList.getArray()) {
VertexBuffer bufClone = vb.clone();
clone.buffers.put(vb.getBufferType().ordinal(), bufClone);
clone.buffersList.add(bufClone);
}
clone.vertexArrayID = -1;
clone.vertCount = vertCount;
clone.elementCount = elementCount;
clone.instanceCount = instanceCount;
// although this could change
// if the bone weight/index buffers are modified
clone.maxNumWeights = maxNumWeights;
clone.elementLengths = elementLengths != null ? elementLengths.clone() : null;
clone.modeStart = modeStart != null ? modeStart.clone() : null;
return clone;
} catch (CloneNotSupportedException ex) {
throw new AssertionError();
}
}
/**
* Clone the mesh for animation use.
* This creates a shallow clone of the mesh, sharing most
* of the {@link VertexBuffer vertex buffer} data, however the
* {@link Type#Position}, {@link Type#Normal}, and {@link Type#Tangent} buffers
* are deeply cloned.
*
* @return A clone of the mesh for animation use.
*/
public Mesh cloneForAnim() {
Mesh clone = clone();
if (getBuffer(Type.BindPosePosition) != null) {
VertexBuffer oldPos = getBuffer(Type.Position);
// NOTE: creates deep clone
VertexBuffer newPos = oldPos.clone();
clone.clearBuffer(Type.Position);
clone.setBuffer(newPos);
if (getBuffer(Type.BindPoseNormal) != null) {
VertexBuffer oldNorm = getBuffer(Type.Normal);
VertexBuffer newNorm = oldNorm.clone();
clone.clearBuffer(Type.Normal);
clone.setBuffer(newNorm);
if (getBuffer(Type.BindPoseTangent) != null) {
VertexBuffer oldTang = getBuffer(Type.Tangent);
VertexBuffer newTang = oldTang.clone();
clone.clearBuffer(Type.Tangent);
clone.setBuffer(newTang);
}
}
}
return clone;
}
/**
* Called internally by com.jme3.util.clone.Cloner. Do not call directly.
*/
@Override
public Mesh jmeClone() {
try {
Mesh clone = (Mesh) super.clone();
clone.vertexArrayID = -1;
return clone;
} catch (CloneNotSupportedException ex) {
throw new AssertionError();
}
}
/**
* Called internally by com.jme3.util.clone.Cloner. Do not call directly.
*/
@Override
public void cloneFields(Cloner cloner, Object original) {
// Probably could clone this now but it will get regenerated anyway.
this.collisionTree = null;
this.meshBound = cloner.clone(meshBound);
this.buffersList = cloner.clone(buffersList);
this.buffers = cloner.clone(buffers);
this.lodLevels = cloner.clone(lodLevels);
this.elementLengths = cloner.clone(elementLengths);
this.modeStart = cloner.clone(modeStart);
}
/**
* @param forSoftwareAnim
* @deprecated use generateBindPose();
*/
@Deprecated
public void generateBindPose(boolean forSoftwareAnim) {
generateBindPose();
}
/**
* Generates the {@link Type#BindPosePosition}, {@link Type#BindPoseNormal},
* and {@link Type#BindPoseTangent}
* buffers for this mesh by duplicating them based on the position and normal
* buffers already set on the mesh.
* This method does nothing if the mesh has no bone weight or index
* buffers.
*/
public void generateBindPose() {
VertexBuffer pos = getBuffer(Type.Position);
if (pos == null || getBuffer(Type.BoneIndex) == null) {
// ignore, this mesh doesn't have positional data
// or it doesn't have bone-vertex assignments, so it's not animated
return;
}
VertexBuffer bindPos = new VertexBuffer(Type.BindPosePosition);
bindPos.setupData(Usage.CpuOnly,
pos.getNumComponents(),
pos.getFormat(),
BufferUtils.clone(pos.getData()));
setBuffer(bindPos);
// XXX: note that this method also sets stream mode
// so that animation is faster. this is not needed for hardware skinning
pos.setUsage(Usage.Stream);
VertexBuffer norm = getBuffer(Type.Normal);
if (norm != null) {
VertexBuffer bindNorm = new VertexBuffer(Type.BindPoseNormal);
bindNorm.setupData(Usage.CpuOnly,
norm.getNumComponents(),
norm.getFormat(),
BufferUtils.clone(norm.getData()));
setBuffer(bindNorm);
norm.setUsage(Usage.Stream);
}
VertexBuffer tangents = getBuffer(Type.Tangent);
if (tangents != null) {
VertexBuffer bindTangents = new VertexBuffer(Type.BindPoseTangent);
bindTangents.setupData(Usage.CpuOnly,
tangents.getNumComponents(),
tangents.getFormat(),
BufferUtils.clone(tangents.getData()));
setBuffer(bindTangents);
tangents.setUsage(Usage.Stream);
}// else hardware setup does nothing, mesh already in bind pose
}
/**
* Prepares the mesh for software skinning by converting the bone index
* and weight buffers to heap buffers.
*
* @param forSoftwareAnim Should be true to enable the conversion.
*/
public void prepareForAnim(boolean forSoftwareAnim) {
if (forSoftwareAnim) {
// convert indices to ubytes on the heap
VertexBuffer indices = getBuffer(Type.BoneIndex);
if (!indices.getData().hasArray()) {
if (indices.getFormat() == Format.UnsignedByte) {
ByteBuffer originalIndex = (ByteBuffer) indices.getData();
ByteBuffer arrayIndex = ByteBuffer.allocate(originalIndex.capacity());
originalIndex.clear();
arrayIndex.put(originalIndex);
indices.updateData(arrayIndex);
} else {
//bone indices can be stored in an UnsignedShort buffer
ShortBuffer originalIndex = (ShortBuffer) indices.getData();
ShortBuffer arrayIndex = ShortBuffer.allocate(originalIndex.capacity());
originalIndex.clear();
arrayIndex.put(originalIndex);
indices.updateData(arrayIndex);
}
}
indices.setUsage(Usage.CpuOnly);
// convert weights on the heap
VertexBuffer weights = getBuffer(Type.BoneWeight);
if (!weights.getData().hasArray()) {
FloatBuffer originalWeight = (FloatBuffer) weights.getData();
FloatBuffer arrayWeight = FloatBuffer.allocate(originalWeight.capacity());
originalWeight.clear();
arrayWeight.put(originalWeight);
weights.updateData(arrayWeight);
}
weights.setUsage(Usage.CpuOnly);
// position, normal, and tanget buffers to be in "Stream" mode
VertexBuffer positions = getBuffer(Type.Position);
VertexBuffer normals = getBuffer(Type.Normal);
VertexBuffer tangents = getBuffer(Type.Tangent);
positions.setUsage(Usage.Stream);
if (normals != null) {
normals.setUsage(Usage.Stream);
}
if (tangents != null) {
tangents.setUsage(Usage.Stream);
}
} else {
//if HWBoneIndex and HWBoneWeight are empty, we setup them as direct
//buffers with software anim buffers data
VertexBuffer indicesHW = getBuffer(Type.HWBoneIndex);
Buffer result;
if (indicesHW.getData() == null) {
VertexBuffer indices = getBuffer(Type.BoneIndex);
if (indices.getFormat() == Format.UnsignedByte) {
ByteBuffer originalIndex = (ByteBuffer) indices.getData();
ByteBuffer directIndex
= BufferUtils.createByteBuffer(originalIndex.capacity());
originalIndex.clear();
directIndex.put(originalIndex);
result = directIndex;
} else {
//bone indices can be stored in an UnsignedShort buffer
ShortBuffer originalIndex = (ShortBuffer) indices.getData();
ShortBuffer directIndex
= BufferUtils.createShortBuffer(originalIndex.capacity());
originalIndex.clear();
directIndex.put(originalIndex);
result = directIndex;
}
indicesHW.setupData(Usage.Static, indices.getNumComponents(),
indices.getFormat(), result);
}
VertexBuffer weightsHW = getBuffer(Type.HWBoneWeight);
if (weightsHW.getData() == null) {
VertexBuffer weights = getBuffer(Type.BoneWeight);
FloatBuffer originalWeight = (FloatBuffer) weights.getData();
FloatBuffer directWeight
= BufferUtils.createFloatBuffer(originalWeight.capacity());
originalWeight.clear();
directWeight.put(originalWeight);
weightsHW.setupData(Usage.Static, weights.getNumComponents(),
weights.getFormat(), directWeight);
}
// position, normal, and tanget buffers to be in "Static" mode
VertexBuffer positions = getBuffer(Type.Position);
VertexBuffer normals = getBuffer(Type.Normal);
VertexBuffer tangents = getBuffer(Type.Tangent);
VertexBuffer positionsBP = getBuffer(Type.BindPosePosition);
VertexBuffer normalsBP = getBuffer(Type.BindPoseNormal);
VertexBuffer tangentsBP = getBuffer(Type.BindPoseTangent);
positions.setUsage(Usage.Static);
positionsBP.copyElements(0, positions, 0, positionsBP.getNumElements());
positions.setUpdateNeeded();
if (normals != null) {
normals.setUsage(Usage.Static);
normalsBP.copyElements(0, normals, 0, normalsBP.getNumElements());
normals.setUpdateNeeded();
}
if (tangents != null) {
tangents.setUsage(Usage.Static);
tangentsBP.copyElements(0, tangents, 0, tangentsBP.getNumElements());
tangents.setUpdateNeeded();
}
}
}
/**
* Set the LOD (level of detail) index buffers on this mesh.
*
* @param lodLevels The LOD levels to set
*/
public void setLodLevels(VertexBuffer[] lodLevels) {
this.lodLevels = lodLevels;
}
/**
* @return The number of LOD levels set on this mesh, including the main
* index buffer, returns zero if there are no lod levels.
*/
public int getNumLodLevels() {
return lodLevels != null ? lodLevels.length : 0;
}
/**
* Returns the lod level at the given index.
*
* @param lod The lod level index, this does not include
* the main index buffer.
* @return The LOD index buffer at the index
*
* @throws IndexOutOfBoundsException If the index is outside of the
* range [0, {@link #getNumLodLevels()}].
*
* @see #setLodLevels(com.jme3.scene.VertexBuffer[])
*/
public VertexBuffer getLodLevel(int lod) {
return lodLevels[lod];
}
/**
* Get the element lengths for {@link Mode#Hybrid} mesh mode.
*
* @return element lengths
*/
public int[] getElementLengths() {
return elementLengths;
}
/**
* Set the element lengths for {@link Mode#Hybrid} mesh mode.
*
* @param elementLengths The element lengths to set
*/
public void setElementLengths(int[] elementLengths) {
this.elementLengths = elementLengths;
}
/**
* Set the mode start indices for {@link Mode#Hybrid} mesh mode.
*
* @return mode start indices
*/
public int[] getModeStart() {
return modeStart;
}
/**
* Get the mode start indices for {@link Mode#Hybrid} mesh mode.
*/
public void setModeStart(int[] modeStart) {
this.modeStart = modeStart;
}
/**
* Returns the mesh mode
*
* @return the mesh mode
*
* @see #setMode(com.jme3.scene.Mesh.Mode)
*/
public Mode getMode() {
return mode;
}
/**
* Change the Mesh's mode. By default the mode is {@link Mode#Triangles}.
*
* @param mode The new mode to set
*
* @see Mode
*/
public void setMode(Mode mode) {
this.mode = mode;
updateCounts();
}
/**
* Returns the maximum number of weights per vertex on this mesh.
*
* @return maximum number of weights per vertex
*
* @see #setMaxNumWeights(int)
*/
public int getMaxNumWeights() {
return maxNumWeights;
}
/**
* Set the maximum number of weights per vertex on this mesh.
* Only relevant if this mesh has bone index/weight buffers.
* This value should be between 0 and 4.
*
* @param maxNumWeights
*/
public void setMaxNumWeights(int maxNumWeights) {
this.maxNumWeights = maxNumWeights;
}
/**
* @deprecated Always returns <code>1.0</code> since point size is
* determined in the vertex shader.
*
* @return <code>1.0</code>
*
* @see #setPointSize(float)
*/
@Deprecated
public float getPointSize() {
return 1.0f;
}
/**
* @deprecated Does nothing, since the size of {@link Mode#Points points} is
* determined via the vertex shader's <code>gl_PointSize</code> output.
*
* @param pointSize ignored
*/
@Deprecated
public void setPointSize(float pointSize) {
}
/**
* Returns the line width for line meshes.
*
* @return the line width
* @deprecated use {@link Material#getAdditionalRenderState()}
* and {@link RenderState#getLineWidth()}
*/
@Deprecated
public float getLineWidth() {
return lineWidth;
}
/**
* Specify the line width for meshes of the line modes, such
* as {@link Mode#Lines}. The line width is specified as on-screen pixels,
* the default value is 1.0.
*
* @param lineWidth The line width
* @deprecated use {@link Material#getAdditionalRenderState()}
* and {@link RenderState#setLineWidth(float)}
*/
@Deprecated
public void setLineWidth(float lineWidth) {
if (lineWidth < 1f) {
throw new IllegalArgumentException("lineWidth must be greater than or equal to 1.0");
}
this.lineWidth = lineWidth;
}
/**
* Indicates to the GPU that this mesh will not be modified (a hint).
* Sets the usage mode to {@link Usage#Static}
* for all {@link VertexBuffer vertex buffers} on this Mesh.
*/
public void setStatic() {
for (VertexBuffer vb : buffersList.getArray()) {
vb.setUsage(Usage.Static);
}
}
/**
* Indicates to the GPU that this mesh will be modified occasionally (a hint).
* Sets the usage mode to {@link Usage#Dynamic}
* for all {@link VertexBuffer vertex buffers} on this Mesh.
*/
public void setDynamic() {
for (VertexBuffer vb : buffersList.getArray()) {
vb.setUsage(Usage.Dynamic);
}
}
/**
* Indicates to the GPU that this mesh will be modified every frame (a hint).
* Sets the usage mode to {@link Usage#Stream}
* for all {@link VertexBuffer vertex buffers} on this Mesh.
*/
public void setStreamed() {
for (VertexBuffer vb : buffersList.getArray()) {
vb.setUsage(Usage.Stream);
}
}
/**
* Interleaves the data in this mesh. This operation cannot be reversed.
* Some GPUs may prefer the data in this format, however it is a good idea
* to <em>avoid</em> using this method as it disables some engine features.
*/
@Deprecated
public void setInterleaved() {
ArrayList<VertexBuffer> vbs = new ArrayList<>();
vbs.addAll(buffersList);
// ArrayList<VertexBuffer> vbs = new ArrayList<VertexBuffer>(buffers.values());
// index buffer not included when interleaving
vbs.remove(getBuffer(Type.Index));
int stride = 0; // aka bytes per vertex
for (int i = 0; i < vbs.size(); i++) {
VertexBuffer vb = vbs.get(i);
// if (vb.getFormat() != Format.Float){
// throw new UnsupportedOperationException("Cannot interleave vertex buffer.\n" +
// "Contains not-float data.");
stride += vb.componentsLength;
vb.getData().clear(); // reset position & limit (used later)
}
VertexBuffer allData = new VertexBuffer(Type.InterleavedData);
ByteBuffer dataBuf = BufferUtils.createByteBuffer(stride * getVertexCount());
allData.setupData(Usage.Static, 1, Format.UnsignedByte, dataBuf);
// adding buffer directly so that no update counts is forced
buffers.put(Type.InterleavedData.ordinal(), allData);
buffersList.add(allData);
for (int vert = 0; vert < getVertexCount(); vert++) {
for (int i = 0; i < vbs.size(); i++) {
VertexBuffer vb = vbs.get(i);
switch (vb.getFormat()) {
case Float:
FloatBuffer fb = (FloatBuffer) vb.getData();
for (int comp = 0; comp < vb.components; comp++) {
dataBuf.putFloat(fb.get());
}
break;
case Byte:
case UnsignedByte:
ByteBuffer bb = (ByteBuffer) vb.getData();
for (int comp = 0; comp < vb.components; comp++) {
dataBuf.put(bb.get());
}
break;
case Half:
case Short:
case UnsignedShort:
ShortBuffer sb = (ShortBuffer) vb.getData();
for (int comp = 0; comp < vb.components; comp++) {
dataBuf.putShort(sb.get());
}
break;
case Int:
case UnsignedInt:
IntBuffer ib = (IntBuffer) vb.getData();
for (int comp = 0; comp < vb.components; comp++) {
dataBuf.putInt(ib.get());
}
break;
case Double:
DoubleBuffer db = (DoubleBuffer) vb.getData();
for (int comp = 0; comp < vb.components; comp++) {
dataBuf.putDouble(db.get());
}
break;
}
}
}
int offset = 0;
for (VertexBuffer vb : vbs) {
vb.setOffset(offset);
vb.setStride(stride);
vb.updateData(null);
//vb.setupData(vb.usage, vb.components, vb.format, null);
offset += vb.componentsLength;
}
}
private int computeNumElements(int bufSize) {
switch (mode) {
case Triangles:
return bufSize / 3;
case TriangleFan:
case TriangleStrip:
return bufSize - 2;
case Points:
return bufSize;
case Lines:
return bufSize / 2;
case LineLoop:
return bufSize;
case LineStrip:
return bufSize - 1;
case Patch:
return bufSize / patchVertexCount;
default:
throw new UnsupportedOperationException();
}
}
private int computeInstanceCount() {
// Whatever the max of the base instance counts
int max = 0;
for (VertexBuffer vb : buffersList) {
if (vb.getBaseInstanceCount() > max) {
max = vb.getBaseInstanceCount();
}
}
return max;
}
public void updateCounts() {
if (getBuffer(Type.InterleavedData) != null) {
throw new IllegalStateException("Should update counts before interleave");
}
VertexBuffer pb = getBuffer(Type.Position);
VertexBuffer ib = getBuffer(Type.Index);
if (pb != null) {
vertCount = pb.getData().limit() / pb.getNumComponents();
}
if (ib != null) {
elementCount = computeNumElements(ib.getData().limit());
} else {
elementCount = computeNumElements(vertCount);
}
instanceCount = computeInstanceCount();
}
/**
* Returns the triangle count for the given LOD level.
*
* @param lod The lod level to look up
* @return The triangle count for that LOD level
*/
public int getTriangleCount(int lod) {
if (lodLevels != null) {
if (lod < 0) {
throw new IllegalArgumentException("LOD level cannot be < 0");
}
if (lod >= lodLevels.length) {
throw new IllegalArgumentException("LOD level " + lod + " does not exist!");
}
return computeNumElements(lodLevels[lod].getData().limit());
} else if (lod == 0) {
return elementCount;
} else {
throw new IllegalArgumentException("There are no LOD levels on the mesh!");
}
}
/**
* Returns how many triangles or elements are on this Mesh.
* This value is only updated when {@link #updateCounts() } is called.
* If the mesh mode is not a triangle mode, then this returns the
* number of elements/primitives, e.g. how many lines or how many points,
* instead of how many triangles.
*
* @return how many triangles/elements are on this Mesh.
*/
public int getTriangleCount() {
return elementCount;
}
/**
* Returns the number of vertices on this mesh.
* The value is computed based on the position buffer, which
* must be set on all meshes.
*
* @return Number of vertices on the mesh
*/
public int getVertexCount() {
return vertCount;
}
/**
* Returns the number of instances this mesh contains. The instance
* count is based on any VertexBuffers with instancing set.
*/
public int getInstanceCount() {
return instanceCount;
}
/**
* Gets the triangle vertex positions at the given triangle index
* and stores them into the v1, v2, v3 arguments.
*
* @param index The index of the triangle.
* Should be between 0 and {@link #getTriangleCount()}.
*
* @param v1 Vector to contain first vertex position
* @param v2 Vector to contain second vertex position
* @param v3 Vector to contain third vertex position
*/
public void getTriangle(int index, Vector3f v1, Vector3f v2, Vector3f v3) {
VertexBuffer pb = getBuffer(Type.Position);
IndexBuffer ib = getIndicesAsList();
if (pb != null && pb.getFormat() == Format.Float && pb.getNumComponents() == 3) {
FloatBuffer fpb = (FloatBuffer) pb.getData();
// aquire triangle's vertex indices
int vertIndex = index * 3;
int vert1 = ib.get(vertIndex);
int vert2 = ib.get(vertIndex + 1);
int vert3 = ib.get(vertIndex + 2);
BufferUtils.populateFromBuffer(v1, fpb, vert1);
BufferUtils.populateFromBuffer(v2, fpb, vert2);
BufferUtils.populateFromBuffer(v3, fpb, vert3);
} else {
throw new UnsupportedOperationException("Position buffer not set or "
+ " has incompatible format");
}
}
/**
* Gets the triangle vertex positions at the given triangle index
* and stores them into the {@link Triangle} argument.
* Also sets the triangle index to the <code>index</code> argument.
*
* @param index The index of the triangle.
* Should be between 0 and {@link #getTriangleCount()}.
*
* @param tri The triangle to store the positions in
*/
public void getTriangle(int index, Triangle tri) {
getTriangle(index, tri.get1(), tri.get2(), tri.get3());
tri.setIndex(index);
tri.setNormal(null);
}
/**
* Gets the triangle vertex indices at the given triangle index
* and stores them into the given int array.
*
* @param index The index of the triangle.
* Should be between 0 and {@link #getTriangleCount()}.
*
* @param indices Indices of the triangle's vertices
*/
public void getTriangle(int index, int[] indices) {
IndexBuffer ib = getIndicesAsList();
// acquire triangle's vertex indices
int vertIndex = index * 3;
indices[0] = ib.get(vertIndex);
indices[1] = ib.get(vertIndex + 1);
indices[2] = ib.get(vertIndex + 2);
}
/**
* Returns the mesh's VAO ID. Internal use only.
*/
public int getId() {
return vertexArrayID;
}
/**
* Sets the mesh's VAO ID. Internal use only.
*/
public void setId(int id) {
if (vertexArrayID != -1) {
throw new IllegalStateException("ID has already been set.");
}
vertexArrayID = id;
}
/**
* Generates a collision tree for the mesh.
* Called automatically by {@link #collideWith(com.jme3.collision.Collidable,
* com.jme3.math.Matrix4f,
* com.jme3.bounding.BoundingVolume,
* com.jme3.collision.CollisionResults) }.
*/
public void createCollisionData() {
BIHTree tree = new BIHTree(this);
tree.construct();
collisionTree = tree;
}
/**
* Clears any previously generated collision data. Use this if
* the mesh has changed in some way that invalidates any previously
* generated BIHTree.
*/
public void clearCollisionData() {
collisionTree = null;
}
/**
* Handles collision detection, internal use only.
* User code should only use collideWith() on scene
* graph elements such as {@link Spatial}s.
*/
public int collideWith(Collidable other,
Matrix4f worldMatrix,
BoundingVolume worldBound,
CollisionResults results) {
switch (mode) {
case Points:
case Lines:
case LineStrip:
case LineLoop:
/*
* Collisions can be detected only with triangles,
* and there are no triangles in this mesh.
*/
return 0;
}
if (getVertexCount() == 0) {
return 0;
}
if (collisionTree == null) {
createCollisionData();
}
return collisionTree.collideWith(other, worldMatrix, worldBound, results);
}
public void setBuffer(VertexBuffer vb) {
if (buffers.containsKey(vb.getBufferType().ordinal())) {
throw new IllegalArgumentException("Buffer type already set: " + vb.getBufferType());
}
buffers.put(vb.getBufferType().ordinal(), vb);
buffersList.add(vb);
updateCounts();
}
/**
* Unsets the {@link VertexBuffer} set on this mesh
* with the given type. Does nothing if the vertex buffer type is not set
* initially.
*
* @param type The buffer type to remove
*/
public void clearBuffer(VertexBuffer.Type type) {
VertexBuffer vb = buffers.remove(type.ordinal());
if (vb != null) {
buffersList.remove(vb);
updateCounts();
}
}
/**
* Creates a {@link VertexBuffer} for the mesh or modifies
* the existing one per the parameters given.
*
* @param type The type of the buffer
* @param components Number of components
* @param format Data format
* @param buf The buffer data
*
* @throws UnsupportedOperationException If the buffer already set is
* incompatible with the parameters given.
*/
public void setBuffer(Type type, int components, Format format, Buffer buf) {
VertexBuffer vb = buffers.get(type.ordinal());
if (vb == null) {
vb = new VertexBuffer(type);
vb.setupData(Usage.Dynamic, components, format, buf);
setBuffer(vb);
} else {
if (vb.getNumComponents() != components || vb.getFormat() != format) {
throw new UnsupportedOperationException("The buffer already set "
+ "is incompatible with the given parameters");
}
vb.updateData(buf);
updateCounts();
}
}
/**
* Set a floating point {@link VertexBuffer} on the mesh.
*
* @param type The type of {@link VertexBuffer},
* e.g. {@link Type#Position}, {@link Type#Normal}, etc.
*
* @param components Number of components on the vertex buffer, should
* be between 1 and 4.
*
* @param buf The floating point data to contain
*/
public void setBuffer(Type type, int components, FloatBuffer buf) {
setBuffer(type, components, Format.Float, buf);
}
public void setBuffer(Type type, int components, float[] buf) {
setBuffer(type, components, BufferUtils.createFloatBuffer(buf));
}
public void setBuffer(Type type, int components, IntBuffer buf) {
setBuffer(type, components, Format.UnsignedInt, buf);
}
public void setBuffer(Type type, int components, int[] buf) {
setBuffer(type, components, BufferUtils.createIntBuffer(buf));
}
public void setBuffer(Type type, int components, ShortBuffer buf) {
setBuffer(type, components, Format.UnsignedShort, buf);
}
public void setBuffer(Type type, int components, byte[] buf) {
setBuffer(type, components, BufferUtils.createByteBuffer(buf));
}
public void setBuffer(Type type, int components, ByteBuffer buf) {
setBuffer(type, components, Format.UnsignedByte, buf);
}
public void setBuffer(Type type, int components, short[] buf) {
setBuffer(type, components, BufferUtils.createShortBuffer(buf));
}
/**
* Get the {@link VertexBuffer} stored on this mesh with the given
* type.
*
* @param type The type of VertexBuffer
* @return the VertexBuffer data, or null if not set
*/
public VertexBuffer getBuffer(Type type) {
return buffers.get(type.ordinal());
}
/**
* Get the {@link VertexBuffer} data stored on this mesh in float
* format.
*
* @param type The type of VertexBuffer
* @return the VertexBuffer data, or null if not set
*/
public FloatBuffer getFloatBuffer(Type type) {
VertexBuffer vb = getBuffer(type);
if (vb == null) {
return null;
}
return (FloatBuffer) vb.getData();
}
/**
* Get the {@link VertexBuffer} data stored on this mesh in short
* format.
*
* @param type The type of VertexBuffer
* @return the VertexBuffer data, or null if not set
*/
public ShortBuffer getShortBuffer(Type type) {
VertexBuffer vb = getBuffer(type);
if (vb == null) {
return null;
}
return (ShortBuffer) vb.getData();
}
/**
* Acquires an index buffer that will read the vertices on the mesh
* as a list.
*
* @return A virtual or wrapped index buffer to read the data as a list
*/
public IndexBuffer getIndicesAsList() {
if (mode == Mode.Hybrid) {
throw new UnsupportedOperationException("Hybrid mode not supported");
}
IndexBuffer ib = getIndexBuffer();
if (ib != null) {
if (mode.isListMode()) {
// already in list mode
return ib;
} else {
// not in list mode but it does have an index buffer
// wrap it so the data is converted to list format
return new WrappedIndexBuffer(this);
}
} else {
// return a virtual index buffer that will supply
// "fake" indices in list format
return new VirtualIndexBuffer(vertCount, mode);
}
}
/**
* Get the index buffer for this mesh.
* Will return <code>null</code> if no index buffer is set.
*
* @return The index buffer of this mesh.
*
* @see Type#Index
*/
public IndexBuffer getIndexBuffer() {
VertexBuffer vb = getBuffer(Type.Index);
if (vb == null) {
return null;
}
return IndexBuffer.wrapIndexBuffer(vb.getData());
}
/**
* Extracts the vertex attributes from the given mesh into
* this mesh, by using this mesh's {@link #getIndexBuffer() index buffer}
* to index into the attributes of the other mesh.
* Note that this will also change this mesh's index buffer so that
* the references to the vertex data match the new indices.
*
* @param other The mesh to extract the vertex data from
*/
public void extractVertexData(Mesh other) {
// Determine the number of unique vertices need to
// be created. Also determine the mappings
// between old indices to new indices (since we avoid duplicating
// vertices, this is a map and not an array).
VertexBuffer oldIdxBuf = getBuffer(Type.Index);
IndexBuffer indexBuf = getIndexBuffer();
int numIndices = indexBuf.size();
IntMap<Integer> oldIndicesToNewIndices = new IntMap<>(numIndices);
ArrayList<Integer> newIndicesToOldIndices = new ArrayList<>();
int newIndex = 0;
for (int i = 0; i < numIndices; i++) {
int oldIndex = indexBuf.get(i);
if (!oldIndicesToNewIndices.containsKey(oldIndex)) {
// this vertex has not been added, so allocate a
// new index for it and add it to the map
oldIndicesToNewIndices.put(oldIndex, newIndex);
newIndicesToOldIndices.add(oldIndex);
// increment to have the next index
newIndex++;
}
}
// Number of unique verts to be created now available
int newNumVerts = newIndicesToOldIndices.size();
if (newIndex != newNumVerts) {
throw new AssertionError();
}
// Create the new index buffer.
// Do not overwrite the old one because we might be able to
// convert from int index buffer to short index buffer
IndexBuffer newIndexBuf;
if (newNumVerts >= 65536) {
newIndexBuf = new IndexIntBuffer(BufferUtils.createIntBuffer(numIndices));
} else {
newIndexBuf = new IndexShortBuffer(BufferUtils.createShortBuffer(numIndices));
}
for (int i = 0; i < numIndices; i++) {
// Map the old indices to the new indices
int oldIndex = indexBuf.get(i);
newIndex = oldIndicesToNewIndices.get(oldIndex);
newIndexBuf.put(i, newIndex);
}
VertexBuffer newIdxBuf = new VertexBuffer(Type.Index);
newIdxBuf.setupData(oldIdxBuf.getUsage(),
oldIdxBuf.getNumComponents(),
newIndexBuf instanceof IndexIntBuffer ? Format.UnsignedInt : Format.UnsignedShort,
newIndexBuf.getBuffer());
clearBuffer(Type.Index);
setBuffer(newIdxBuf);
// Now, create the vertex buffers
SafeArrayList<VertexBuffer> oldVertexData = other.getBufferList();
for (VertexBuffer oldVb : oldVertexData) {
if (oldVb.getBufferType() == VertexBuffer.Type.Index) {
// ignore the index buffer
continue;
}
VertexBuffer newVb = new VertexBuffer(oldVb.getBufferType());
newVb.setNormalized(oldVb.isNormalized());
//check for data before copying, some buffers are just empty shells
//for caching purpose (HW skinning buffers), and will be filled when
//needed
if (oldVb.getData() != null) {
// Create a new vertex buffer with similar configuration, but
// with the capacity of number of unique vertices
Buffer buffer = VertexBuffer.createBuffer(oldVb.getFormat(),
oldVb.getNumComponents(), newNumVerts);
newVb.setupData(oldVb.getUsage(), oldVb.getNumComponents(),
oldVb.getFormat(), buffer);
// Copy the vertex data from the old buffer into the new buffer
for (int i = 0; i < newNumVerts; i++) {
int oldIndex = newIndicesToOldIndices.get(i);
// Copy the vertex attribute from the old index
// to the new index
oldVb.copyElement(oldIndex, newVb, i);
}
}
// Set the buffer on the mesh
clearBuffer(newVb.getBufferType());
setBuffer(newVb);
}
// Copy max weights per vertex as well
setMaxNumWeights(other.getMaxNumWeights());
// The data has been copied over, update informations
updateCounts();
updateBound();
}
public void scaleTextureCoordinates(Vector2f scaleFactor) {
VertexBuffer tc = getBuffer(Type.TexCoord);
if (tc == null) {
throw new IllegalStateException("The mesh has no texture coordinates");
}
if (tc.getFormat() != VertexBuffer.Format.Float) {
throw new UnsupportedOperationException("Only float texture coord format is supported");
}
if (tc.getNumComponents() != 2) {
throw new UnsupportedOperationException("Only 2D texture coords are supported");
}
FloatBuffer fb = (FloatBuffer) tc.getData();
fb.clear();
for (int i = 0; i < fb.limit() / 2; i++) {
float x = fb.get();
float y = fb.get();
fb.position(fb.position() - 2);
x *= scaleFactor.getX();
y *= scaleFactor.getY();
fb.put(x).put(y);
}
fb.clear();
tc.updateData(fb);
}
/**
* Updates the bounding volume of this mesh.
* The method does nothing if the mesh has no {@link Type#Position} buffer.
* It is expected that the position buffer is a float buffer with 3 components.
*/
public void updateBound() {
VertexBuffer posBuf = getBuffer(VertexBuffer.Type.Position);
if (meshBound != null && posBuf != null) {
meshBound.computeFromPoints((FloatBuffer) posBuf.getData());
}
}
/**
* Returns the {@link BoundingVolume} of this Mesh.
* By default the bounding volume is a {@link BoundingBox}.
*
* @return the bounding volume of this mesh
*/
public BoundingVolume getBound() {
return meshBound;
}
/**
* Sets the {@link BoundingVolume} for this Mesh.
* The bounding volume is recomputed by calling {@link #updateBound() }.
*
* @param modelBound The model bound to set
*/
public void setBound(BoundingVolume modelBound) {
meshBound = modelBound;
}
/**
* Returns a map of all {@link VertexBuffer vertex buffers} on this Mesh.
* The integer key for the map is the {@link Enum#ordinal() ordinal}
* of the vertex buffer's {@link Type}.
* Note that the returned map is a reference to the map used internally,
* modifying it will cause undefined results.
*
* @return map of vertex buffers on this mesh.
*/
public IntMap<VertexBuffer> getBuffers() {
return buffers;
}
/**
* Returns a list of all {@link VertexBuffer vertex buffers} on this Mesh.
* Using a list instead an IntMap via the {@link #getBuffers() } method is
* better for iteration as there's no need to create an iterator instance.
* Note that the returned list is a reference to the list used internally,
* modifying it will cause undefined results.
*
* @return list of vertex buffers on this mesh.
*/
public SafeArrayList<VertexBuffer> getBufferList() {
return buffersList;
}
/**
* Determines if the mesh uses bone animation.
*
* A mesh uses bone animation if it has bone index / weight buffers
* such as {@link Type#BoneIndex} or {@link Type#HWBoneIndex}.
*
* @return true if the mesh uses bone animation, false otherwise
*/
public boolean isAnimated() {
return getBuffer(Type.BoneIndex) != null
|| getBuffer(Type.HWBoneIndex) != null;
}
/**
* @deprecated use isAnimatedByJoint
* @param boneIndex
* @return true if animated by that bone, otherwise false
*/
@Deprecated
public boolean isAnimatedByBone(int boneIndex) {
return isAnimatedByJoint(boneIndex);
}
/**
* Test whether the specified bone animates this mesh.
*
* @param jointIndex the bone's index in its skeleton
* @return true if the specified bone animates this mesh, otherwise false
*/
public boolean isAnimatedByJoint(int jointIndex) {
VertexBuffer biBuf = getBuffer(VertexBuffer.Type.BoneIndex);
VertexBuffer wBuf = getBuffer(VertexBuffer.Type.BoneWeight);
if (biBuf == null || wBuf == null) {
return false; // no bone animation data
}
IndexBuffer boneIndexBuffer = IndexBuffer.wrapIndexBuffer(biBuf.getData());
boneIndexBuffer.rewind();
int numBoneIndices = boneIndexBuffer.remaining();
assert numBoneIndices % 4 == 0 : numBoneIndices;
int numVertices = boneIndexBuffer.remaining() / 4;
FloatBuffer weightBuffer = (FloatBuffer) wBuf.getData();
weightBuffer.rewind();
int numWeights = weightBuffer.remaining();
assert numWeights == numVertices * 4 : numWeights;
/*
* Test each vertex to determine whether the bone affects it.
*/
int biByte = jointIndex;
for (int vIndex = 0; vIndex < numVertices; vIndex++) {
for (int wIndex = 0; wIndex < 4; wIndex++) {
int bIndex = boneIndexBuffer.get();
float weight = weightBuffer.get();
if (wIndex < maxNumWeights && bIndex == biByte && weight != 0f) {
return true;
}
}
}
return false;
}
/**
* Sets the count of vertices used for each tessellation patch
*
* @param patchVertexCount
*/
public void setPatchVertexCount(int patchVertexCount) {
this.patchVertexCount = patchVertexCount;
}
/**
* Gets the amount of vertices used for each patch;
*
* @return the count (≥0)
*/
public int getPatchVertexCount() {
return patchVertexCount;
}
public void addMorphTarget(MorphTarget target) {
if (morphTargets == null) {
morphTargets = new SafeArrayList<>(MorphTarget.class);
}
morphTargets.add(target);
}
/**
* Remove the given MorphTarget from the Mesh
* @param target The MorphTarget to remove
* @return If the MorphTarget was removed
*/
public boolean removeMorphTarget(MorphTarget target) {
return morphTargets != null ? morphTargets.remove(target) : false;
}
/**
* Remove the MorphTarget from the Mesh at the given index
* @throws IndexOutOfBoundsException if the index outside the number of morph targets
* @param index Index of the MorphTarget to remove
* @return The MorphTarget that was removed
*/
public MorphTarget removeMorphTarget(int index) {
if (morphTargets == null) {
throw new IndexOutOfBoundsException("Index:" + index + ", Size:0");
}
return morphTargets.remove(index);
}
/**
* Get the MorphTarget at the given index
* @throws IndexOutOfBoundsException if the index outside the number of morph targets
* @param index The index of the morph target to get
* @return The MorphTarget at the index
*/
public MorphTarget getMorphTarget(int index) {
if (morphTargets == null) {
throw new IndexOutOfBoundsException("Index:" + index + ", Size:0");
}
return morphTargets.get(index);
}
public MorphTarget[] getMorphTargets() {
if (morphTargets == null) {
return new MorphTarget[0];
} else {
return morphTargets.getArray();
}
}
/**
* Get the name of all morphs in order.
* Morphs without names will be null
* @return an array
*/
public String[] getMorphTargetNames() {
MorphTarget[] nbMorphTargets = getMorphTargets();
if (nbMorphTargets.length == 0) {
return new String[0];
}
String[] targets = new String[nbMorphTargets.length];
for (int index = 0; index < nbMorphTargets.length; index++) {
targets[index] = nbMorphTargets[index].getName();
}
return targets;
}
public boolean hasMorphTargets() {
return morphTargets != null && !morphTargets.isEmpty();
}
/**
* Get the index of the morph that has the given name.
*
* @param morphName The name of the morph to search for
* @return The index of the morph, or -1 if not found.
*/
public int getMorphIndex(String morphName) {
int index = -1;
MorphTarget[] nbMorphTargets = getMorphTargets();
for (int i = 0; i < nbMorphTargets.length; i++) {
if (nbMorphTargets[i].getName().equals(morphName)) {
index = i;
break;
}
}
return index;
}
@Override
@SuppressWarnings("unchecked")
public void write(JmeExporter ex) throws IOException {
OutputCapsule out = ex.getCapsule(this);
out.write(meshBound, "modelBound", null);
out.write(vertCount, "vertCount", -1);
out.write(elementCount, "elementCount", -1);
out.write(instanceCount, "instanceCount", -1);
out.write(maxNumWeights, "max_num_weights", -1);
out.write(mode, "mode", Mode.Triangles);
out.write(collisionTree, "collisionTree", null);
out.write(elementLengths, "elementLengths", null);
out.write(modeStart, "modeStart", null);
out.write(pointSize, "pointSize", 1f);
//Removing HW skinning buffers to not save them
VertexBuffer hwBoneIndex = null;
VertexBuffer hwBoneWeight = null;
hwBoneIndex = getBuffer(Type.HWBoneIndex);
if (hwBoneIndex != null) {
buffers.remove(Type.HWBoneIndex.ordinal());
}
hwBoneWeight = getBuffer(Type.HWBoneWeight);
if (hwBoneWeight != null) {
buffers.remove(Type.HWBoneWeight.ordinal());
}
out.writeIntSavableMap(buffers, "buffers", null);
//restoring Hw skinning buffers.
if (hwBoneIndex != null) {
buffers.put(hwBoneIndex.getBufferType().ordinal(), hwBoneIndex);
}
if (hwBoneWeight != null) {
buffers.put(hwBoneWeight.getBufferType().ordinal(), hwBoneWeight);
}
out.write(lodLevels, "lodLevels", null);
if (morphTargets != null) {
out.writeSavableArrayList(new ArrayList(morphTargets), "morphTargets", null);
}
}
@Override
@SuppressWarnings("unchecked")
public void read(JmeImporter im) throws IOException {
InputCapsule in = im.getCapsule(this);
meshBound = (BoundingVolume) in.readSavable("modelBound", null);
vertCount = in.readInt("vertCount", -1);
elementCount = in.readInt("elementCount", -1);
instanceCount = in.readInt("instanceCount", -1);
maxNumWeights = in.readInt("max_num_weights", -1);
mode = in.readEnum("mode", Mode.class, Mode.Triangles);
elementLengths = in.readIntArray("elementLengths", null);
modeStart = in.readIntArray("modeStart", null);
collisionTree = (BIHTree) in.readSavable("collisionTree", null);
elementLengths = in.readIntArray("elementLengths", null);
modeStart = in.readIntArray("modeStart", null);
pointSize = in.readFloat("pointSize", 1f);
// in.readStringSavableMap("buffers", null);
buffers = (IntMap<VertexBuffer>) in.readIntSavableMap("buffers", null);
for (Entry<VertexBuffer> entry : buffers) {
buffersList.add(entry.getValue());
}
//creating hw animation buffers empty so that they are put in the cache
if (isAnimated()) {
VertexBuffer hwBoneIndex = new VertexBuffer(Type.HWBoneIndex);
hwBoneIndex.setUsage(Usage.CpuOnly);
setBuffer(hwBoneIndex);
VertexBuffer hwBoneWeight = new VertexBuffer(Type.HWBoneWeight);
hwBoneWeight.setUsage(Usage.CpuOnly);
setBuffer(hwBoneWeight);
}
Savable[] lodLevelsSavable = in.readSavableArray("lodLevels", null);
if (lodLevelsSavable != null) {
lodLevels = new VertexBuffer[lodLevelsSavable.length];
System.arraycopy(lodLevelsSavable, 0, lodLevels, 0, lodLevels.length);
}
ArrayList<Savable> l = in.readSavableArrayList("morphTargets", null);
if (l != null) {
morphTargets = new SafeArrayList(MorphTarget.class, l);
}
}
}
|
package net.ellitron.ldbcsnbimpls.interactive.torc;
import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.*;
import static org.apache.tinkerpop.gremlin.process.traversal.Order.incr;
import static org.apache.tinkerpop.gremlin.process.traversal.Order.decr;
import static org.apache.tinkerpop.gremlin.process.traversal.P.*;
import static org.apache.tinkerpop.gremlin.process.traversal.Operator.assign;
import static org.apache.tinkerpop.gremlin.process.traversal.Operator.mult;
import static org.apache.tinkerpop.gremlin.process.traversal.Operator.minus;
import static org.apache.tinkerpop.gremlin.process.traversal.Scope.local;
import net.ellitron.torc.util.UInt128;
import com.ldbc.driver.control.LoggingService;
import com.ldbc.driver.Db;
import com.ldbc.driver.DbConnectionState;
import com.ldbc.driver.DbException;
import com.ldbc.driver.OperationHandler;
import com.ldbc.driver.ResultReporter;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcNoResult;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery1;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery1Result;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery2;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery2Result;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery3;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery3Result;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery4;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery4Result;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery5;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery5Result;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery6;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery6Result;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery7;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery7Result;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery8;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery8Result;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery9;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery9Result;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery10;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery10Result;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery11;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery11Result;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery12;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery12Result;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery13;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery13Result;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery14;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcQuery14Result;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcShortQuery1PersonProfile;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcShortQuery1PersonProfileResult;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcShortQuery2PersonPosts;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcShortQuery2PersonPostsResult;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcShortQuery3PersonFriends;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcShortQuery3PersonFriendsResult;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcShortQuery4MessageContent;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcShortQuery4MessageContentResult;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcShortQuery5MessageCreator;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcShortQuery5MessageCreatorResult;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcShortQuery6MessageForum;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcShortQuery6MessageForumResult;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcShortQuery7MessageReplies;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcShortQuery7MessageRepliesResult;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcUpdate1AddPerson;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcUpdate2AddPostLike;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcUpdate3AddCommentLike;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcUpdate4AddForum;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcUpdate5AddForumMembership;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcUpdate6AddPost;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcUpdate7AddComment;
import com.ldbc.driver.workloads.ldbc.snb.interactive.LdbcUpdate8AddFriendship;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.Scope;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
public class TorcDb extends Db {
private TorcDbConnectionState connectionState = null;
private static boolean doTransactionalReads = false;
// Maximum number of times to try a transaction before giving up.
private static int MAX_TX_ATTEMPTS = 100;
@Override
protected void onInit(Map<String, String> properties,
LoggingService loggingService) throws DbException {
connectionState = new TorcDbConnectionState(properties);
if (properties.containsKey("txReads")) {
doTransactionalReads = true;
}
/*
* Register operation handlers with the benchmark.
*/
registerOperationHandler(LdbcQuery1.class,
LdbcQuery1Handler.class);
registerOperationHandler(LdbcQuery2.class,
LdbcQuery2Handler.class);
registerOperationHandler(LdbcQuery7.class,
LdbcQuery7Handler.class);
registerOperationHandler(LdbcQuery8.class,
LdbcQuery8Handler.class);
registerOperationHandler(LdbcQuery10.class,
LdbcQuery10Handler.class);
registerOperationHandler(LdbcQuery11.class,
LdbcQuery11Handler.class);
registerOperationHandler(LdbcQuery13.class,
LdbcQuery13Handler.class);
registerOperationHandler(LdbcShortQuery1PersonProfile.class,
LdbcShortQuery1PersonProfileHandler.class);
registerOperationHandler(LdbcShortQuery2PersonPosts.class,
LdbcShortQuery2PersonPostsHandler.class);
registerOperationHandler(LdbcShortQuery3PersonFriends.class,
LdbcShortQuery3PersonFriendsHandler.class);
registerOperationHandler(LdbcShortQuery4MessageContent.class,
LdbcShortQuery4MessageContentHandler.class);
registerOperationHandler(LdbcShortQuery5MessageCreator.class,
LdbcShortQuery5MessageCreatorHandler.class);
registerOperationHandler(LdbcShortQuery6MessageForum.class,
LdbcShortQuery6MessageForumHandler.class);
registerOperationHandler(LdbcShortQuery7MessageReplies.class,
LdbcShortQuery7MessageRepliesHandler.class);
registerOperationHandler(LdbcUpdate1AddPerson.class,
LdbcUpdate1AddPersonHandler.class);
registerOperationHandler(LdbcUpdate2AddPostLike.class,
LdbcUpdate2AddPostLikeHandler.class);
registerOperationHandler(LdbcUpdate3AddCommentLike.class,
LdbcUpdate3AddCommentLikeHandler.class);
registerOperationHandler(LdbcUpdate4AddForum.class,
LdbcUpdate4AddForumHandler.class);
registerOperationHandler(LdbcUpdate5AddForumMembership.class,
LdbcUpdate5AddForumMembershipHandler.class);
registerOperationHandler(LdbcUpdate6AddPost.class,
LdbcUpdate6AddPostHandler.class);
registerOperationHandler(LdbcUpdate7AddComment.class,
LdbcUpdate7AddCommentHandler.class);
registerOperationHandler(LdbcUpdate8AddFriendship.class,
LdbcUpdate8AddFriendshipHandler.class);
}
@Override
protected void onClose() throws IOException {
connectionState.close();
}
@Override
protected DbConnectionState getConnectionState() throws DbException {
return connectionState;
}
/**
* Given a start Person, find up to 20 Persons with a given first name that
* the start Person is connected to (excluding start Person) by at most 3
* steps via Knows relationships. Return Persons, including summaries of the
* Persons workplaces and places of study. Sort results ascending by their
* distance from the start Person, for Persons within the same distance sort
* ascending by their last name, and for Persons with same last name
* ascending by their identifier.[1]
*/
public static class LdbcQuery1Handler
implements OperationHandler<LdbcQuery1, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcQuery1Handler.class);
@Override
public void executeOperation(final LdbcQuery1 operation,
DbConnectionState dbConnectionState,
ResultReporter resultReporter) throws DbException {
executeOperationGremlin2(operation, dbConnectionState, resultReporter);
}
public void executeOperationGremlin2(final LdbcQuery1 operation,
DbConnectionState dbConnectionState,
ResultReporter resultReporter) throws DbException {
int txAttempts = 0;
while (txAttempts < MAX_TX_ATTEMPTS) {
long personId = operation.personId();
String firstName = operation.firstName();
int resultLimit = operation.limit();
int maxLevels = 3;
Graph graph = ((TorcDbConnectionState) dbConnectionState).getClient();
GraphTraversalSource g = graph.traversal();
List<Long> distList = new ArrayList<>(resultLimit);
List<Vertex> matchList = new ArrayList<>(resultLimit);
Vertex root = g.V(new UInt128(TorcEntity.PERSON.idSpace, personId))
.next();
g.withSideEffect("x", matchList).withSideEffect("d", distList)
.V(root).aggregate("done").out("knows")
.where(without("done")).dedup().fold().sideEffect(
unfold().has("firstName", firstName).order()
.by("lastName", incr).by(id(), incr).limit(resultLimit)
.as("person")
.select("x").by(count(Scope.local)).is(lt(resultLimit))
.store("x").by(select("person"))
).filter(select("x").count(Scope.local).is(lt(resultLimit))
.store("d")).unfold().aggregate("done").out("knows")
.where(without("done")).dedup().fold().sideEffect(
unfold().has("firstName", firstName).order()
.by("lastName", incr).by(id(), incr).limit(resultLimit)
.as("person")
.select("x").by(count(Scope.local)).is(lt(resultLimit))
.store("x").by(select("person"))
).filter(select("x").count(Scope.local).is(lt(resultLimit))
.store("d")).unfold().aggregate("done").out("knows")
.where(without("done")).dedup().fold().sideEffect(
unfold().has("firstName", firstName).order()
.by("lastName", incr).by(id(), incr).limit(resultLimit)
.as("person")
.select("x").by(count(Scope.local)).is(lt(resultLimit))
.store("x").by(select("person"))
).select("x").count(Scope.local)
.store("d").iterate();
Map<Vertex, Map<String, List<String>>> propertiesMap =
new HashMap<>(matchList.size());
g.V(matchList.toArray()).as("person")
.<List<String>>valueMap().as("props")
.select("person", "props")
.forEachRemaining(map -> {
propertiesMap.put((Vertex) map.get("person"),
(Map<String, List<String>>) map.get("props"));
});
Map<Vertex, String> placeNameMap = new HashMap<>(matchList.size());
g.V(matchList.toArray()).as("person")
.out("isLocatedIn")
.<String>values("name")
.as("placeName")
.select("person", "placeName")
.forEachRemaining(map -> {
placeNameMap.put((Vertex) map.get("person"),
(String) map.get("placeName"));
});
Map<Vertex, List<List<Object>>> universityInfoMap =
new HashMap<>(matchList.size());
g.V(matchList.toArray()).as("person")
.outE("studyAt").as("classYear")
.inV().as("universityName")
.out("isLocatedIn").as("cityName")
.select("person", "universityName", "classYear", "cityName")
.by().by("name").by("classYear").by("name")
.forEachRemaining(map -> {
Vertex v = (Vertex) map.get("person");
List<Object> tuple = new ArrayList<>(3);
tuple.add(map.get("universityName"));
tuple.add(Integer.decode((String) map.get("classYear")));
tuple.add(map.get("cityName"));
if (universityInfoMap.containsKey(v)) {
universityInfoMap.get(v).add(tuple);
} else {
List<List<Object>> tupleList = new ArrayList<>();
tupleList.add(tuple);
universityInfoMap.put(v, tupleList);
}
});
Map<Vertex, List<List<Object>>> companyInfoMap =
new HashMap<>(matchList.size());
g.V(matchList.toArray()).as("person")
.outE("workAt").as("workFrom")
.inV().as("companyName")
.out("isLocatedIn").as("cityName")
.select("person", "companyName", "workFrom", "cityName")
.by().by("name").by("workFrom").by("name")
.forEachRemaining(map -> {
Vertex v = (Vertex) map.get("person");
List<Object> tuple = new ArrayList<>(3);
tuple.add(map.get("companyName"));
tuple.add(Integer.decode((String) map.get("workFrom")));
tuple.add(map.get("cityName"));
if (companyInfoMap.containsKey(v)) {
companyInfoMap.get(v).add(tuple);
} else {
List<List<Object>> tupleList = new ArrayList<>();
tupleList.add(tuple);
companyInfoMap.put(v, tupleList);
}
});
List<LdbcQuery1Result> result = new ArrayList<>();
for (int i = 0; i < matchList.size(); i++) {
Vertex match = matchList.get(i);
int distance = (i < distList.get(0)) ? 1
: (i < distList.get(1)) ? 2 : 3;
Map<String, List<String>> properties = propertiesMap.get(match);
List<String> emails = properties.get("email");
if (emails == null) {
emails = new ArrayList<>();
}
List<String> languages = properties.get("language");
if (languages == null) {
languages = new ArrayList<>();
}
String placeName = placeNameMap.get(match);
List<List<Object>> universityInfo = universityInfoMap.get(match);
if (universityInfo == null) {
universityInfo = new ArrayList<>();
}
List<List<Object>> companyInfo = companyInfoMap.get(match);
if (companyInfo == null) {
companyInfo = new ArrayList<>();
}
result.add(new LdbcQuery1Result(
((UInt128) match.id()).getLowerLong(),
properties.get("lastName").get(0),
distance,
Long.decode(properties.get("birthday").get(0)),
Long.decode(properties.get("creationDate").get(0)),
properties.get("gender").get(0),
properties.get("browserUsed").get(0),
properties.get("locationIP").get(0),
emails,
languages,
placeName,
universityInfo,
companyInfo));
}
if (doTransactionalReads) {
try {
graph.tx().commit();
} catch (RuntimeException e) {
txAttempts++;
continue;
}
} else {
graph.tx().rollback();
}
resultReporter.report(result.size(), result, operation);
break;
}
}
public void executeOperationGremlin1(final LdbcQuery1 operation,
DbConnectionState dbConnectionState,
ResultReporter resultReporter) throws DbException {
int txAttempts = 0;
while (txAttempts < MAX_TX_ATTEMPTS) {
long personId = operation.personId();
String firstName = operation.firstName();
int resultLimit = operation.limit();
int maxLevels = 3;
Graph graph = ((TorcDbConnectionState) dbConnectionState).getClient();
GraphTraversalSource g = graph.traversal();
List<Integer> distList = new ArrayList<>(resultLimit);
List<Vertex> matchList = new ArrayList<>(resultLimit);
Vertex root = g.V(new UInt128(TorcEntity.PERSON.idSpace, personId))
.next();
List<Vertex> l1Friends = new ArrayList<>();
g.V(root).out("knows")
.sideEffect(v -> l1Friends.add(v.get()))
.has("firstName", firstName)
.order()
.by("lastName", incr)
.by(id(), incr)
.sideEffect(v -> {
if (matchList.size() < resultLimit) {
matchList.add(v.get());
distList.add(1);
}
})
.iterate();
if (matchList.size() < resultLimit && l1Friends.size() > 0) {
List<Vertex> l2Friends = new ArrayList<>();
g.V(l1Friends.toArray())
.out("knows")
.dedup()
.is(without(l1Friends))
.is(without(root))
.sideEffect(v -> l2Friends.add(v.get()))
.has("firstName", firstName)
.order()
.by("lastName", incr)
.by(id(), incr)
.sideEffect(v -> {
if (matchList.size() < resultLimit) {
matchList.add(v.get());
distList.add(2);
}
})
.iterate();
if (matchList.size() < resultLimit && l2Friends.size() > 0) {
g.V(l2Friends.toArray())
.out("knows")
.dedup()
.is(without(l2Friends))
.is(without(l1Friends))
.has("firstName", firstName)
.order()
.by("lastName", incr)
.by(id(), incr)
.sideEffect(v -> {
if (matchList.size() < resultLimit) {
matchList.add(v.get());
distList.add(3);
}
})
.iterate();
}
}
Map<Vertex, Map<String, List<String>>> propertiesMap =
new HashMap<>(matchList.size());
g.V(matchList.toArray()).as("person")
.<List<String>>valueMap().as("props")
.select("person", "props")
.forEachRemaining(map -> {
propertiesMap.put((Vertex) map.get("person"),
(Map<String, List<String>>) map.get("props"));
});
Map<Vertex, String> placeNameMap = new HashMap<>(matchList.size());
g.V(matchList.toArray()).as("person")
.out("isLocatedIn")
.<String>values("name")
.as("placeName")
.select("person", "placeName")
.forEachRemaining(map -> {
placeNameMap.put((Vertex) map.get("person"),
(String) map.get("placeName"));
});
Map<Vertex, List<List<Object>>> universityInfoMap =
new HashMap<>(matchList.size());
g.V(matchList.toArray()).as("person")
.outE("studyAt").as("classYear")
.inV().as("universityName")
.out("isLocatedIn").as("cityName")
.select("person", "universityName", "classYear", "cityName")
.by().by("name").by("classYear").by("name")
.forEachRemaining(map -> {
Vertex v = (Vertex) map.get("person");
List<Object> tuple = new ArrayList<>(3);
tuple.add(map.get("universityName"));
tuple.add(Integer.decode((String) map.get("classYear")));
tuple.add(map.get("cityName"));
if (universityInfoMap.containsKey(v)) {
universityInfoMap.get(v).add(tuple);
} else {
List<List<Object>> tupleList = new ArrayList<>();
tupleList.add(tuple);
universityInfoMap.put(v, tupleList);
}
});
Map<Vertex, List<List<Object>>> companyInfoMap =
new HashMap<>(matchList.size());
g.V(matchList.toArray()).as("person")
.outE("workAt").as("workFrom")
.inV().as("companyName")
.out("isLocatedIn").as("cityName")
.select("person", "companyName", "workFrom", "cityName")
.by().by("name").by("workFrom").by("name")
.forEachRemaining(map -> {
Vertex v = (Vertex) map.get("person");
List<Object> tuple = new ArrayList<>(3);
tuple.add(map.get("companyName"));
tuple.add(Integer.decode((String) map.get("workFrom")));
tuple.add(map.get("cityName"));
if (companyInfoMap.containsKey(v)) {
companyInfoMap.get(v).add(tuple);
} else {
List<List<Object>> tupleList = new ArrayList<>();
tupleList.add(tuple);
companyInfoMap.put(v, tupleList);
}
});
List<LdbcQuery1Result> result = new ArrayList<>();
for (int i = 0; i < matchList.size(); i++) {
Vertex match = matchList.get(i);
Map<String, List<String>> properties = propertiesMap.get(match);
List<String> emails = properties.get("email");
if (emails == null) {
emails = new ArrayList<>();
}
List<String> languages = properties.get("language");
if (languages == null) {
languages = new ArrayList<>();
}
String placeName = placeNameMap.get(match);
List<List<Object>> universityInfo = universityInfoMap.get(match);
if (universityInfo == null) {
universityInfo = new ArrayList<>();
}
List<List<Object>> companyInfo = companyInfoMap.get(match);
if (companyInfo == null) {
companyInfo = new ArrayList<>();
}
result.add(new LdbcQuery1Result(
((UInt128) match.id()).getLowerLong(),
properties.get("lastName").get(0),
distList.get(i),
Long.decode(properties.get("birthday").get(0)),
Long.decode(properties.get("creationDate").get(0)),
properties.get("gender").get(0),
properties.get("browserUsed").get(0),
properties.get("locationIP").get(0),
emails,
languages,
placeName,
universityInfo,
companyInfo));
}
if (doTransactionalReads) {
try {
graph.tx().commit();
} catch (RuntimeException e) {
txAttempts++;
continue;
}
} else {
graph.tx().rollback();
}
resultReporter.report(result.size(), result, operation);
break;
}
}
public void executeOperationRaw(final LdbcQuery1 operation,
DbConnectionState dbConnectionState,
ResultReporter resultReporter) throws DbException {
int txAttempts = 0;
while (txAttempts < MAX_TX_ATTEMPTS) {
long personId = operation.personId();
String firstName = operation.firstName();
int maxLevels = 3;
Graph client = ((TorcDbConnectionState) dbConnectionState).getClient();
Vertex rootPerson = client.vertices(
new UInt128(TorcEntity.PERSON.idSpace, personId)).next();
List<Vertex> friends = new ArrayList<>();
List<Integer> levelIndices = new ArrayList<>();
List<Integer> matchIndices = new ArrayList<>();
friends.add(rootPerson);
levelIndices.add(friends.size());
int currentLevel = 0;
for (int i = 0; i < friends.size(); i++) {
if (i == levelIndices.get(levelIndices.size() - 1)) {
levelIndices.add(friends.size());
currentLevel++;
if (currentLevel == maxLevels) {
break;
}
if (matchIndices.size() >= operation.limit()) {
break;
}
}
Vertex person = friends.get(i);
person.edges(Direction.OUT, "knows").forEachRemaining((e) -> {
Vertex friend = e.inVertex();
if (!friends.contains(friend)) {
friends.add(friend);
if (friend.<String>property("firstName").value()
.equals(firstName)) {
matchIndices.add(friends.size() - 1);
}
}
});
}
List<LdbcQuery1Result> result = new ArrayList<>();
int matchNumber = 0;
for (int level = 1; level < levelIndices.size(); level++) {
int endIndex = levelIndices.get(level);
List<Vertex> equidistantVertices = new ArrayList<>();
while (matchNumber < matchIndices.size()
&& matchIndices.get(matchNumber) < endIndex) {
Vertex friend = friends.get(matchIndices.get(matchNumber));
equidistantVertices.add(friend);
matchNumber++;
}
equidistantVertices.sort((a, b) -> {
Vertex v1 = (Vertex) a;
Vertex v2 = (Vertex) b;
String v1LastName = v1.<String>property("lastName").value();
String v2LastName = v2.<String>property("lastName").value();
int lastNameCompareVal = v1LastName.compareTo(v2LastName);
if (lastNameCompareVal != 0) {
return lastNameCompareVal;
} else {
UInt128 v1Id = (UInt128) v1.id();
UInt128 v2Id = (UInt128) v2.id();
return v1Id.compareTo(v2Id);
}
});
for (Vertex f : equidistantVertices) {
long friendId = ((UInt128) f.id()).getLowerLong();
String friendLastName = null;
int distanceFromPerson = level;
long friendBirthday = 0;
long friendCreationDate = 0;
String friendGender = null;
String friendBrowserUsed = null;
String friendLocationIp = null;
List<String> friendEmails = new ArrayList<>();
List<String> friendLanguages = new ArrayList<>();
String friendCityName = null;
List<List<Object>> friendUniversities = new ArrayList<>();
List<List<Object>> friendCompanies = new ArrayList<>();
// Extract normal properties.
Iterator<VertexProperty<String>> props = f.properties();
while (props.hasNext()) {
VertexProperty<String> prop = props.next();
switch (prop.key()) {
case "lastName":
friendLastName = prop.value();
break;
case "birthday":
friendBirthday = Long.decode(prop.value());
break;
case "creationDate":
friendCreationDate = Long.decode(prop.value());
break;
case "gender":
friendGender = prop.value();
break;
case "browserUsed":
friendBrowserUsed = prop.value();
break;
case "locationIP":
friendLocationIp = prop.value();
break;
case "email":
friendEmails.add(prop.value());
break;
case "language":
friendLanguages.add(prop.value());
break;
}
}
// Fetch where person is located
Vertex friendPlace =
f.edges(Direction.OUT, "isLocatedIn").next().inVertex();
friendCityName = friendPlace.<String>property("name").value();
// Fetch universities studied at
f.edges(Direction.OUT, "studyAt").forEachRemaining((e) -> {
Integer classYear =
Integer.decode(e.<String>property("classYear").value());
Vertex organization = e.inVertex();
String orgName = organization.<String>property("name").value();
Vertex place = organization.edges(Direction.OUT, "isLocatedIn")
.next().inVertex();
String placeName = place.<String>property("name").value();
List<Object> universityInfo = new ArrayList<>();
universityInfo.add(orgName);
universityInfo.add(classYear);
universityInfo.add(placeName);
friendUniversities.add(universityInfo);
});
// Fetch companies worked at
f.edges(Direction.OUT, "workAt").forEachRemaining((e) -> {
Integer workFrom =
Integer.decode(e.<String>property("workFrom").value());
Vertex company = e.inVertex();
String compName = company.<String>property("name").value();
Vertex place = company.edges(Direction.OUT, "isLocatedIn")
.next().inVertex();
String placeName = place.<String>property("name").value();
List<Object> companyInfo = new ArrayList<>();
companyInfo.add(compName);
companyInfo.add(workFrom);
companyInfo.add(placeName);
friendCompanies.add(companyInfo);
});
LdbcQuery1Result res = new LdbcQuery1Result(
friendId,
friendLastName,
level,
friendBirthday,
friendCreationDate,
friendGender,
friendBrowserUsed,
friendLocationIp,
friendEmails,
friendLanguages,
friendCityName,
friendUniversities,
friendCompanies
);
result.add(res);
if (result.size() == operation.limit()) {
break;
}
}
if (result.size() == operation.limit()
|| matchNumber == matchIndices.size()) {
break;
}
}
if (doTransactionalReads) {
try {
client.tx().commit();
} catch (RuntimeException e) {
txAttempts++;
continue;
}
} else {
client.tx().rollback();
}
resultReporter.report(result.size(), result, operation);
break;
}
}
}
public static class LdbcQuery2Handler
implements OperationHandler<LdbcQuery2, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcQuery2Handler.class);
@Override
public void executeOperation(final LdbcQuery2 operation,
DbConnectionState dbConnectionState,
ResultReporter resultReporter) throws DbException {
// Parameters of this query
final long personId = operation.personId();
final long maxDate = operation.maxDate().getTime();
final int limit = operation.limit();
final UInt128 torcPersonId =
new UInt128(TorcEntity.PERSON.idSpace, personId);
Graph graph = ((TorcDbConnectionState) dbConnectionState).getClient();
int txAttempts = 0;
while (txAttempts < MAX_TX_ATTEMPTS) {
GraphTraversalSource g = graph.traversal();
List<LdbcQuery2Result> result = new ArrayList<>(limit);
g.withSideEffect("result", result).V(torcPersonId)
.out("knows").as("friend")
.in("hasCreator").as("message")
.order().by("creationDate", decr).by(id(), incr)
.filter(t ->
Long.valueOf(t.get().value("creationDate")) <= maxDate)
.limit(limit)
.project("personId", "firstName", "lastName", "messageId",
"content", "creationDate")
.by(select("friend").id())
.by(select("friend").values("firstName"))
.by(select("friend").values("lastName"))
.by(select("message").id())
.by(select("message")
.choose(values("content").is(neq("")),
values("content"),
values("imageFile")))
.by(select("message").values("creationDate"))
.map(t -> new LdbcQuery2Result(
((UInt128)t.get().get("personId")).getLowerLong(),
(String)t.get().get("firstName"),
(String)t.get().get("lastName"),
((UInt128)t.get().get("messageId")).getLowerLong(),
(String)t.get().get("content"),
Long.valueOf((String)t.get().get("creationDate"))))
.store("result").iterate();
if (doTransactionalReads) {
try {
graph.tx().commit();
} catch (RuntimeException e) {
txAttempts++;
continue;
}
} else {
graph.tx().rollback();
}
resultReporter.report(result.size(), result, operation);
break;
}
}
}
/**
* Given a start Person, find Persons that are their friends and friends of
* friends (excluding start Person) that have made Posts/Comments in both of
* the given Countries, X and Y, within a given period. Only Persons that are
* foreign to Countries X and Y are considered, that is Persons whose
* Location is not Country X or Country Y. Return top 20 Persons, and their
* Post/Comment counts, in the given countries and period. Sort results
* descending by total number of Posts/Comments, and then ascending by Person
* identifier.[1]
*/
public static class LdbcQuery3Handler
implements OperationHandler<LdbcQuery3, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcQuery3Handler.class);
@Override
public void executeOperation(final LdbcQuery3 operation,
DbConnectionState dbConnectionState,
ResultReporter resultReporter) throws DbException {
}
}
public static class LdbcQuery4Handler
implements OperationHandler<LdbcQuery4, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcQuery4Handler.class);
@Override
public void executeOperation(final LdbcQuery4 operation,
DbConnectionState dbConnectionState,
ResultReporter resultReporter) throws DbException {
}
}
public static class LdbcQuery5Handler
implements OperationHandler<LdbcQuery5, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcQuery5Handler.class);
@Override
public void executeOperation(final LdbcQuery5 operation,
DbConnectionState dbConnectionState,
ResultReporter resultReporter) throws DbException {
}
}
public static class LdbcQuery6Handler
implements OperationHandler<LdbcQuery6, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcQuery6Handler.class);
@Override
public void executeOperation(final LdbcQuery6 operation,
DbConnectionState dbConnectionState,
ResultReporter resultReporter) throws DbException {
}
}
public static class LdbcQuery7Handler
implements OperationHandler<LdbcQuery7, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcQuery7Handler.class);
@Override
public void executeOperation(final LdbcQuery7 operation,
DbConnectionState dbConnectionState,
ResultReporter resultReporter) throws DbException {
// Parameters of this query
final long personId = operation.personId();
final int limit = operation.limit();
final UInt128 torcPersonId =
new UInt128(TorcEntity.PERSON.idSpace, personId);
Graph graph = ((TorcDbConnectionState) dbConnectionState).getClient();
int txAttempts = 0;
while (txAttempts < MAX_TX_ATTEMPTS) {
GraphTraversalSource g = graph.traversal();
List<LdbcQuery7Result> result = new ArrayList<>(limit);
g.withSideEffect("result", result).V(torcPersonId).as("person")
.in("hasCreator").as("message")
.inE("likes").as("like")
.outV().as("liker")
.order()
.by(select("like").values("creationDate"), decr)
.by(select("message").id(), incr)
.dedup()
.by(select("liker"))
.limit(limit)
.project("personId",
"personFirstName",
"personLastName",
"likeCreationDate",
"commentOrPostId",
"commentOrPostContent",
"commentOrPostCreationDate",
"isNew")
.by(select("liker").id())
.by(select("liker").values("firstName"))
.by(select("liker").values("lastName"))
.by(select("like").values("creationDate")
.map(t -> Long.valueOf((String)t.get())))
.by(select("message").id())
.by(select("message")
.choose(values("content").is(neq("")),
values("content"),
values("imageFile")))
.by(select("message").values("creationDate")
.map(t -> Long.valueOf((String)t.get())))
.by(choose(
where(select("person").out("knows").as("liker")),
constant(false),
constant(true)))
.map(t -> new LdbcQuery7Result(
((UInt128)t.get().get("personId")).getLowerLong(),
(String)t.get().get("personFirstName"),
(String)t.get().get("personLastName"),
(Long)t.get().get("likeCreationDate"),
((UInt128)t.get().get("commentOrPostId")).getLowerLong(),
(String)t.get().get("commentOrPostContent"),
(int)(((Long)t.get().get("likeCreationDate")
- (Long)t.get().get("commentOrPostCreationDate"))
/ (1000l * 60l)),
(Boolean)t.get().get("isNew")))
.store("result").iterate();
if (doTransactionalReads) {
try {
graph.tx().commit();
} catch (RuntimeException e) {
txAttempts++;
continue;
}
} else {
graph.tx().rollback();
}
resultReporter.report(result.size(), result, operation);
break;
}
}
}
/**
* Given a start Person, find (most recent) Comments that are replies to
* Posts/Comments of the start Person. Only consider immediate (1-hop)
* replies, not the transitive (multi-hop) case. Return the top 20 reply
* Comments, and the Person that created each reply Comment. Sort results
* descending by creation date of reply Comment, and then ascending by
* identifier of reply Comment.[1]
*/
public static class LdbcQuery8Handler
implements OperationHandler<LdbcQuery8, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcQuery8Handler.class);
@Override
public void executeOperation(final LdbcQuery8 operation,
DbConnectionState dbConnectionState,
ResultReporter resultReporter) throws DbException {
// Parameters of this query
final long personId = operation.personId();
final int limit = operation.limit();
final UInt128 torcPersonId =
new UInt128(TorcEntity.PERSON.idSpace, personId);
Graph graph = ((TorcDbConnectionState) dbConnectionState).getClient();
int txAttempts = 0;
while (txAttempts < MAX_TX_ATTEMPTS) {
GraphTraversalSource g = graph.traversal();
List<LdbcQuery8Result> result = new ArrayList<>(limit);
g.withSideEffect("result", result).V(torcPersonId).as("person")
.in("hasCreator").as("message")
.in("replyOf").as("comment")
.order()
.by(select("comment").values("creationDate"), decr)
.by(select("comment").id(), incr)
.limit(limit)
.out("hasCreator").as("commenter")
.project("personId",
"personFirstName",
"personLastName",
"commentCreationDate",
"commentId",
"commentContent")
.by(select("commenter").id())
.by(select("commenter").values("firstName"))
.by(select("commenter").values("lastName"))
.by(select("comment").values("creationDate"))
.by(select("comment").id())
.by(select("comment")
.choose(values("content").is(neq("")),
values("content"),
values("imageFile")))
.map(t -> new LdbcQuery8Result(
((UInt128)t.get().get("personId")).getLowerLong(),
(String)t.get().get("personFirstName"),
(String)t.get().get("personLastName"),
Long.valueOf((String)t.get().get("commentCreationDate")),
((UInt128)t.get().get("commentId")).getLowerLong(),
(String)t.get().get("commentContent")))
.store("result").iterate();
if (doTransactionalReads) {
try {
graph.tx().commit();
} catch (RuntimeException e) {
txAttempts++;
continue;
}
} else {
graph.tx().rollback();
}
resultReporter.report(result.size(), result, operation);
break;
}
}
}
public static class LdbcQuery9Handler
implements OperationHandler<LdbcQuery9, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcQuery9Handler.class);
@Override
public void executeOperation(final LdbcQuery9 operation,
DbConnectionState dbConnectionState,
ResultReporter resultReporter) throws DbException {
}
}
public static class LdbcQuery10Handler
implements OperationHandler<LdbcQuery10, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcQuery10Handler.class);
@Override
public void executeOperation(final LdbcQuery10 operation,
DbConnectionState dbConnectionState,
ResultReporter resultReporter) throws DbException {
// Parameters of this query
final long personId = operation.personId();
final int month = operation.month() - 1; // make month zero based
final int limit = operation.limit();
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
final UInt128 torcPersonId =
new UInt128(TorcEntity.PERSON.idSpace, personId);
Graph graph = ((TorcDbConnectionState) dbConnectionState).getClient();
int txAttempts = 0;
while (txAttempts < MAX_TX_ATTEMPTS) {
GraphTraversalSource g = graph.traversal();
List<LdbcQuery10Result> result = new ArrayList<>(limit);
g.withSideEffect("result", result).V(torcPersonId).as("person")
.aggregate("done")
.out("hasInterest")
.aggregate("personInterests")
.select("person").out("knows")
.aggregate("done")
.out("knows").where(without("done")).dedup()
.filter(t -> {
calendar.setTimeInMillis(
Long.valueOf(t.get().value("birthday")));
int bmonth = calendar.get(Calendar.MONTH); // zero based
int bday = calendar.get(Calendar.DAY_OF_MONTH); // starts with 1
if ((bmonth == month && bday >= 21) ||
(bmonth == ((month + 1) % 12) && bday < 22)) {
return true;
}
return false;
}).as("friend2")
.sack(assign)
.by(in("hasCreator").hasLabel("Post")
.where(out("hasTag").where(within("personInterests")))
.count())
.sack(mult).by(constant(2))
.sack(minus)
.by(in("hasCreator").hasLabel("Post").count())
.order()
.by(sack(), decr)
.by(select("friend2").id(), incr)
.limit(limit)
.project("personId",
"personFirstName",
"personLastName",
"commonInterestScore",
"personGender",
"personCityName")
.by(select("friend2").id())
.by(select("friend2").values("firstName"))
.by(select("friend2").values("lastName"))
.by(sack())
.by(select("friend2").values("gender"))
.by(select("friend2").out("isLocatedIn").values("name"))
.map(t -> new LdbcQuery10Result(
((UInt128)t.get().get("personId")).getLowerLong(),
(String)t.get().get("personFirstName"),
(String)t.get().get("personLastName"),
((Long)t.get().get("commonInterestScore")).intValue(),
(String)t.get().get("personGender"),
(String)t.get().get("personCityName")))
.store("result").iterate();
if (doTransactionalReads) {
try {
graph.tx().commit();
} catch (RuntimeException e) {
txAttempts++;
continue;
}
} else {
graph.tx().rollback();
}
resultReporter.report(result.size(), result, operation);
break;
}
}
}
public static class LdbcQuery11Handler
implements OperationHandler<LdbcQuery11, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcQuery11Handler.class);
@Override
public void executeOperation(final LdbcQuery11 operation,
DbConnectionState dbConnectionState,
ResultReporter resultReporter) throws DbException {
// Parameters of this query
final long personId = operation.personId();
final String countryName = operation.countryName();
final int workFromYear = operation.workFromYear();
final int limit = operation.limit();
final UInt128 torcPersonId =
new UInt128(TorcEntity.PERSON.idSpace, personId);
Graph graph = ((TorcDbConnectionState) dbConnectionState).getClient();
int txAttempts = 0;
while (txAttempts < MAX_TX_ATTEMPTS) {
GraphTraversalSource g = graph.traversal();
List<LdbcQuery11Result> result = new ArrayList<>(limit);
g.withSideEffect("result", result).V(torcPersonId).as("person")
.aggregate("done")
.union(
out("knows"),
out("knows").out("knows"))
.dedup().where(without("done")).as("friend")
.outE("workAt").has("workFrom", lt(String.valueOf(workFromYear)))
.as("workAt")
.inV().as("company")
.out("isLocatedIn").has("name", countryName)
.order()
.by(select("workAt").values("workFrom"), incr)
.by(select("friend").id())
.by(select("company").values("name"), decr)
.limit(limit)
.project("personId",
"personFirstName",
"personLastName",
"organizationName",
"organizationWorkFromYear")
.by(select("friend").id())
.by(select("friend").values("firstName"))
.by(select("friend").values("lastName"))
.by(select("company").values("name"))
.by(select("workAt").values("workFrom"))
.map(t -> new LdbcQuery11Result(
((UInt128)t.get().get("personId")).getLowerLong(),
(String)t.get().get("personFirstName"),
(String)t.get().get("personLastName"),
(String)t.get().get("organizationName"),
Integer.valueOf((String)t.get().get("organizationWorkFromYear"))))
.store("result").iterate();
if (doTransactionalReads) {
try {
graph.tx().commit();
} catch (RuntimeException e) {
txAttempts++;
continue;
}
} else {
graph.tx().rollback();
}
resultReporter.report(result.size(), result, operation);
break;
}
}
}
public static class LdbcQuery12Handler
implements OperationHandler<LdbcQuery12, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcQuery12Handler.class);
@Override
public void executeOperation(final LdbcQuery12 operation,
DbConnectionState dbConnectionState,
ResultReporter resultReporter) throws DbException {
}
}
/**
* Given two Persons, find the shortest path between these two Persons in the
* subgraph induced by the Knows relationships. Return the length of this
* path. -1 should be returned if no path is found, and 0 should be returned
* if the start person is the same as the end person.[1]
*/
public static class LdbcQuery13Handler
implements OperationHandler<LdbcQuery13, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcQuery13Handler.class);
@Override
public void executeOperation(final LdbcQuery13 operation,
DbConnectionState dbConnectionState,
ResultReporter resultReporter) throws DbException {
// Parameters of this query
final long person1Id = operation.person1Id();
final long person2Id = operation.person2Id();
if (person1Id == person2Id) {
resultReporter.report(1, new LdbcQuery13Result(0), operation);
return;
}
final UInt128 torcPerson1Id =
new UInt128(TorcEntity.PERSON.idSpace, person1Id);
final UInt128 torcPerson2Id =
new UInt128(TorcEntity.PERSON.idSpace, person2Id);
Graph graph = ((TorcDbConnectionState) dbConnectionState).getClient();
int txAttempts = 0;
while (txAttempts < MAX_TX_ATTEMPTS) {
GraphTraversalSource g = graph.traversal();
Long pathLength = g.V(torcPerson1Id)
.choose(where(out("knows")),
repeat(out("knows").simplePath())
.until(hasId(torcPerson2Id)
.or()
.path().count(local).is(gt(5)))
.limit(1)
.choose(id().is(eq(torcPerson2Id)),
union(path().count(local), constant(-1l)).sum(),
constant(-1l)),
constant(-1l))
.next();
if (doTransactionalReads) {
try {
graph.tx().commit();
} catch (RuntimeException e) {
txAttempts++;
continue;
}
} else {
graph.tx().rollback();
}
resultReporter.report(1, new LdbcQuery13Result(pathLength.intValue()),
operation);
break;
}
}
}
/**
* Given two Persons, find all (unweighted) shortest paths between these two
* Persons, in the subgraph induced by the Knows relationship. Then, for each
* path calculate a weight. The nodes in the path are Persons, and the weight
* of a path is the sum of weights between every pair of consecutive Person
* nodes in the path. The weight for a pair of Persons is calculated such
* that every reply (by one of the Persons) to a Post (by the other Person)
* contributes 1.0, and every reply (by ones of the Persons) to a Comment (by
* the other Person) contributes 0.5. Return all the paths with shortest
* length, and their weights. Sort results descending by path weight. The
* order of paths with the same weight is unspecified.[1]
*/
public static class LdbcQuery14Handler
implements OperationHandler<LdbcQuery14, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcQuery14Handler.class);
@Override
public void executeOperation(final LdbcQuery14 operation,
DbConnectionState dbConnectionState,
ResultReporter resultReporter) throws DbException {
}
}
/**
* Given a start Person, retrieve their first name, last name, birthday, IP
* address, browser, and city of residence.[1]
*/
public static class LdbcShortQuery1PersonProfileHandler implements
OperationHandler<LdbcShortQuery1PersonProfile, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcShortQuery1PersonProfileHandler.class);
@Override
public void executeOperation(final LdbcShortQuery1PersonProfile operation,
DbConnectionState dbConnectionState,
ResultReporter resultReporter) throws DbException {
int txAttempts = 0;
while (txAttempts < MAX_TX_ATTEMPTS) {
long person_id = operation.personId();
Graph client = ((TorcDbConnectionState) dbConnectionState).getClient();
Vertex person = client.vertices(
new UInt128(TorcEntity.PERSON.idSpace, person_id)).next();
Iterator<VertexProperty<String>> props = person.properties();
Map<String, String> propertyMap = new HashMap<>();
props.forEachRemaining((prop) -> {
propertyMap.put(prop.key(), prop.value());
});
Vertex place =
person.edges(Direction.OUT, "isLocatedIn").next().inVertex();
long placeId = ((UInt128) place.id()).getLowerLong();
LdbcShortQuery1PersonProfileResult res =
new LdbcShortQuery1PersonProfileResult(
propertyMap.get("firstName"),
propertyMap.get("lastName"),
Long.parseLong(propertyMap.get("birthday")),
propertyMap.get("locationIP"),
propertyMap.get("browserUsed"),
placeId,
propertyMap.get("gender"),
Long.parseLong(propertyMap.get("creationDate")));
if (doTransactionalReads) {
try {
client.tx().commit();
} catch (RuntimeException e) {
txAttempts++;
continue;
}
} else {
client.tx().rollback();
}
resultReporter.report(0, res, operation);
break;
}
}
}
public static class LdbcShortQuery2PersonPostsHandler implements
OperationHandler<LdbcShortQuery2PersonPosts, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcShortQuery2PersonPostsHandler.class);
@Override
public void executeOperation(final LdbcShortQuery2PersonPosts operation,
DbConnectionState dbConnectionState,
ResultReporter resultReporter) throws DbException {
int txAttempts = 0;
while (txAttempts < MAX_TX_ATTEMPTS) {
Graph client = ((TorcDbConnectionState) dbConnectionState).getClient();
List<LdbcShortQuery2PersonPostsResult> result = new ArrayList<>();
Vertex person = client.vertices(
new UInt128(TorcEntity.PERSON.idSpace, operation.personId()))
.next();
Iterator<Edge> edges = person.edges(Direction.IN, "hasCreator");
List<Vertex> messageList = new ArrayList<>();
edges.forEachRemaining((e) -> messageList.add(e.outVertex()));
messageList.sort((a, b) -> {
Vertex v1 = (Vertex) a;
Vertex v2 = (Vertex) b;
long v1Date =
Long.decode(v1.<String>property("creationDate").value());
long v2Date =
Long.decode(v2.<String>property("creationDate").value());
if (v1Date > v2Date) {
return -1;
} else if (v1Date < v2Date) {
return 1;
} else {
long v1Id = ((UInt128) v1.id()).getLowerLong();
long v2Id = ((UInt128) v2.id()).getLowerLong();
if (v1Id > v2Id) {
return -1;
} else if (v1Id < v2Id) {
return 1;
} else {
return 0;
}
}
});
for (int i = 0; i < Integer.min(operation.limit(), messageList.size());
i++) {
Vertex message = messageList.get(i);
Map<String, String> propMap = new HashMap<>();
message.<String>properties().forEachRemaining((vp) -> {
propMap.put(vp.key(), vp.value());
});
long messageId = ((UInt128) message.id()).getLowerLong();
String messageContent;
if (propMap.get("content").length() != 0) {
messageContent = propMap.get("content");
} else {
messageContent = propMap.get("imageFile");
}
long messageCreationDate = Long.decode(propMap.get("creationDate"));
long originalPostId;
long originalPostAuthorId;
String originalPostAuthorFirstName;
String originalPostAuthorLastName;
if (message.label().equals(TorcEntity.POST.label)) {
originalPostId = messageId;
originalPostAuthorId = ((UInt128) person.id()).getLowerLong();
originalPostAuthorFirstName =
person.<String>property("firstName").value();
originalPostAuthorLastName =
person.<String>property("lastName").value();
} else {
Vertex parentMessage =
message.edges(Direction.OUT, "replyOf").next().inVertex();
while (true) {
if (parentMessage.label().equals(TorcEntity.POST.label)) {
originalPostId = ((UInt128) parentMessage.id()).getLowerLong();
Vertex author =
parentMessage.edges(Direction.OUT, "hasCreator")
.next().inVertex();
originalPostAuthorId = ((UInt128) author.id()).getLowerLong();
originalPostAuthorFirstName =
author.<String>property("firstName").value();
originalPostAuthorLastName =
author.<String>property("lastName").value();
break;
} else {
parentMessage =
parentMessage.edges(Direction.OUT, "replyOf")
.next().inVertex();
}
}
}
LdbcShortQuery2PersonPostsResult res =
new LdbcShortQuery2PersonPostsResult(
messageId,
messageContent,
messageCreationDate,
originalPostId,
originalPostAuthorId,
originalPostAuthorFirstName,
originalPostAuthorLastName);
result.add(res);
}
if (doTransactionalReads) {
try {
client.tx().commit();
} catch (RuntimeException e) {
txAttempts++;
continue;
}
} else {
client.tx().rollback();
}
resultReporter.report(result.size(), result, operation);
break;
}
}
}
/**
* Given a start Person, retrieve all of their friends, and the date at which
* they became friends. Order results descending by friendship creation date,
* then ascending by friend identifier.[1]
*/
public static class LdbcShortQuery3PersonFriendsHandler implements
OperationHandler<LdbcShortQuery3PersonFriends, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcShortQuery3PersonFriendsHandler.class);
@Override
public void executeOperation(final LdbcShortQuery3PersonFriends operation,
DbConnectionState dbConnectionState,
ResultReporter resultReporter) throws DbException {
int txAttempts = 0;
while (txAttempts < MAX_TX_ATTEMPTS) {
Graph client = ((TorcDbConnectionState) dbConnectionState).getClient();
List<LdbcShortQuery3PersonFriendsResult> result = new ArrayList<>();
Vertex person = client.vertices(
new UInt128(TorcEntity.PERSON.idSpace, operation.personId()))
.next();
Iterator<Edge> edges = person.edges(Direction.OUT, "knows");
edges.forEachRemaining((e) -> {
long creationDate = Long.decode(e.<String>property("creationDate")
.value());
Vertex friend = e.inVertex();
long personId = ((UInt128) friend.id()).getLowerLong();
String firstName = friend.<String>property("firstName").value();
String lastName = friend.<String>property("lastName").value();
LdbcShortQuery3PersonFriendsResult res =
new LdbcShortQuery3PersonFriendsResult(
personId,
firstName,
lastName,
creationDate);
result.add(res);
});
// Sort the result here.
result.sort((a, b) -> {
LdbcShortQuery3PersonFriendsResult r1 =
(LdbcShortQuery3PersonFriendsResult) a;
LdbcShortQuery3PersonFriendsResult r2 =
(LdbcShortQuery3PersonFriendsResult) b;
if (r1.friendshipCreationDate() > r2.friendshipCreationDate()) {
return -1;
} else if (r1.friendshipCreationDate()
< r2.friendshipCreationDate()) {
return 1;
} else {
if (r1.personId() > r2.personId()) {
return 1;
} else if (r1.personId() < r2.personId()) {
return -1;
} else {
return 0;
}
}
});
if (doTransactionalReads) {
try {
client.tx().commit();
} catch (RuntimeException e) {
txAttempts++;
continue;
}
} else {
client.tx().rollback();
}
resultReporter.report(result.size(), result, operation);
break;
}
}
}
/**
* Given a Message (Post or Comment), retrieve its content and creation
* date.[1]
*/
public static class LdbcShortQuery4MessageContentHandler implements
OperationHandler<LdbcShortQuery4MessageContent, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcShortQuery4MessageContentHandler.class);
@Override
public void executeOperation(final LdbcShortQuery4MessageContent operation,
DbConnectionState dbConnectionState,
ResultReporter resultReporter) throws DbException {
int txAttempts = 0;
while (txAttempts < MAX_TX_ATTEMPTS) {
Graph client = ((TorcDbConnectionState) dbConnectionState).getClient();
Vertex message = client.vertices(
new UInt128(TorcEntity.COMMENT.idSpace, operation.messageId()))
.next();
long creationDate =
Long.decode(message.<String>property("creationDate").value());
String content = message.<String>property("content").value();
if (content.length() == 0) {
content = message.<String>property("imageFile").value();
}
LdbcShortQuery4MessageContentResult result =
new LdbcShortQuery4MessageContentResult(
content,
creationDate);
if (doTransactionalReads) {
try {
client.tx().commit();
} catch (RuntimeException e) {
txAttempts++;
continue;
}
} else {
client.tx().rollback();
}
resultReporter.report(1, result, operation);
break;
}
}
}
/**
* Given a Message (Post or Comment), retrieve its author.[1]
*/
public static class LdbcShortQuery5MessageCreatorHandler implements
OperationHandler<LdbcShortQuery5MessageCreator, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcShortQuery5MessageCreatorHandler.class);
@Override
public void executeOperation(final LdbcShortQuery5MessageCreator operation,
DbConnectionState dbConnectionState,
ResultReporter resultReporter) throws DbException {
int txAttempts = 0;
while (txAttempts < MAX_TX_ATTEMPTS) {
Graph client = ((TorcDbConnectionState) dbConnectionState).getClient();
Vertex message = client.vertices(
new UInt128(TorcEntity.COMMENT.idSpace, operation.messageId()))
.next();
Vertex creator =
message.edges(Direction.OUT, "hasCreator").next().inVertex();
long creatorId = ((UInt128) creator.id()).getLowerLong();
String creatorFirstName =
creator.<String>property("firstName").value();
String creatorLastName =
creator.<String>property("lastName").value();
LdbcShortQuery5MessageCreatorResult result =
new LdbcShortQuery5MessageCreatorResult(
creatorId,
creatorFirstName,
creatorLastName);
if (doTransactionalReads) {
try {
client.tx().commit();
} catch (RuntimeException e) {
txAttempts++;
continue;
}
} else {
client.tx().rollback();
}
resultReporter.report(1, result, operation);
break;
}
}
}
/**
* Given a Message (Post or Comment), retrieve the Forum that contains it and
* the Person that moderates that forum. Since comments are not directly
* contained in forums, for comments, return the forum containing the
* original post in the thread which the comment is replying to.[1]
*/
public static class LdbcShortQuery6MessageForumHandler implements
OperationHandler<LdbcShortQuery6MessageForum, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcShortQuery6MessageForumHandler.class);
@Override
public void executeOperation(final LdbcShortQuery6MessageForum operation,
DbConnectionState dbConnectionState,
ResultReporter resultReporter) throws DbException {
int txAttempts = 0;
while (txAttempts < MAX_TX_ATTEMPTS) {
Graph client = ((TorcDbConnectionState) dbConnectionState).getClient();
Vertex vertex = client.vertices(
new UInt128(TorcEntity.COMMENT.idSpace, operation.messageId()))
.next();
LdbcShortQuery6MessageForumResult result;
while (true) {
if (vertex.label().equals(TorcEntity.FORUM.label)) {
long forumId = ((UInt128) vertex.id()).getLowerLong();
String forumTitle = vertex.<String>property("title").value();
Vertex moderator =
vertex.edges(Direction.OUT, "hasModerator").next().inVertex();
long moderatorId = ((UInt128) moderator.id()).getLowerLong();
String moderatorFirstName =
moderator.<String>property("firstName").value();
String moderatorLastName =
moderator.<String>property("lastName").value();
result = new LdbcShortQuery6MessageForumResult(
forumId,
forumTitle,
moderatorId,
moderatorFirstName,
moderatorLastName);
break;
} else if (vertex.label().equals(TorcEntity.POST.label)) {
vertex =
vertex.edges(Direction.IN, "containerOf").next().outVertex();
} else {
vertex = vertex.edges(Direction.OUT, "replyOf").next().inVertex();
}
}
if (doTransactionalReads) {
try {
client.tx().commit();
} catch (RuntimeException e) {
txAttempts++;
continue;
}
} else {
client.tx().rollback();
}
resultReporter.report(1, result, operation);
break;
}
}
}
/**
* Given a Message (Post or Comment), retrieve the (1-hop) Comments that
* reply to it. In addition, return a boolean flag indicating if the author
* of the reply knows the author of the original message. If author is same
* as original author, return false for "knows" flag. Order results
* descending by creation date, then ascending by author identifier.[1]
*/
public static class LdbcShortQuery7MessageRepliesHandler implements
OperationHandler<LdbcShortQuery7MessageReplies, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcShortQuery7MessageRepliesHandler.class);
@Override
public void executeOperation(final LdbcShortQuery7MessageReplies operation,
DbConnectionState dbConnectionState,
ResultReporter resultReporter) throws DbException {
int txAttempts = 0;
while (txAttempts < MAX_TX_ATTEMPTS) {
Graph client = ((TorcDbConnectionState) dbConnectionState).getClient();
Vertex message = client.vertices(
new UInt128(TorcEntity.COMMENT.idSpace, operation.messageId()))
.next();
Vertex messageAuthor =
message.edges(Direction.OUT, "hasCreator").next().inVertex();
long messageAuthorId = ((UInt128) messageAuthor.id()).getLowerLong();
List<Vertex> replies = new ArrayList<>();
message.edges(Direction.IN, "replyOf").forEachRemaining((e) -> {
replies.add(e.outVertex());
});
List<Long> messageAuthorFriendIds = new ArrayList<>();
messageAuthor.edges(Direction.OUT, "knows").forEachRemaining((e) -> {
messageAuthorFriendIds.add(((UInt128) e.inVertex().id())
.getLowerLong());
});
List<LdbcShortQuery7MessageRepliesResult> result = new ArrayList<>();
for (Vertex reply : replies) {
long replyId = ((UInt128) reply.id()).getLowerLong();
String replyContent = reply.<String>property("content").value();
long replyCreationDate =
Long.decode(reply.<String>property("creationDate").value());
Vertex replyAuthor =
reply.edges(Direction.OUT, "hasCreator").next().inVertex();
long replyAuthorId = ((UInt128) replyAuthor.id()).getLowerLong();
String replyAuthorFirstName =
replyAuthor.<String>property("firstName").value();
String replyAuthorLastName =
replyAuthor.<String>property("lastName").value();
boolean knows = false;
if (messageAuthorId != replyAuthorId) {
knows = messageAuthorFriendIds.contains(replyAuthorId);
}
LdbcShortQuery7MessageRepliesResult res =
new LdbcShortQuery7MessageRepliesResult(
replyId,
replyContent,
replyCreationDate,
replyAuthorId,
replyAuthorFirstName,
replyAuthorLastName,
knows
);
result.add(res);
}
// Sort the result here.
result.sort((a, b) -> {
LdbcShortQuery7MessageRepliesResult r1 =
(LdbcShortQuery7MessageRepliesResult) a;
LdbcShortQuery7MessageRepliesResult r2 =
(LdbcShortQuery7MessageRepliesResult) b;
if (r1.commentCreationDate() > r2.commentCreationDate()) {
return -1;
} else if (r1.commentCreationDate() < r2.commentCreationDate()) {
return 1;
} else {
if (r1.replyAuthorId() > r2.replyAuthorId()) {
return 1;
} else if (r1.replyAuthorId() < r2.replyAuthorId()) {
return -1;
} else {
return 0;
}
}
});
if (doTransactionalReads) {
try {
client.tx().commit();
} catch (RuntimeException e) {
txAttempts++;
continue;
}
} else {
client.tx().rollback();
}
resultReporter.report(result.size(), result, operation);
break;
}
}
}
/**
* Add a Person to the social network. [1]
*/
public static class LdbcUpdate1AddPersonHandler implements
OperationHandler<LdbcUpdate1AddPerson, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcUpdate1AddPersonHandler.class);
private final Calendar calendar;
public LdbcUpdate1AddPersonHandler() {
this.calendar = new GregorianCalendar();
}
@Override
public void executeOperation(LdbcUpdate1AddPerson operation,
DbConnectionState dbConnectionState,
ResultReporter reporter) throws DbException {
Graph client = ((TorcDbConnectionState) dbConnectionState).getClient();
// Build key value properties array
List<Object> personKeyValues =
new ArrayList<>(18 + 2 * operation.languages().size()
+ 2 * operation.emails().size());
personKeyValues.add(T.id);
personKeyValues.add(
new UInt128(TorcEntity.PERSON.idSpace, operation.personId()));
personKeyValues.add(T.label);
personKeyValues.add(TorcEntity.PERSON.label);
personKeyValues.add("firstName");
personKeyValues.add(operation.personFirstName());
personKeyValues.add("lastName");
personKeyValues.add(operation.personLastName());
personKeyValues.add("gender");
personKeyValues.add(operation.gender());
personKeyValues.add("birthday");
personKeyValues.add(String.valueOf(operation.birthday().getTime()));
personKeyValues.add("creationDate");
personKeyValues.add(String.valueOf(operation.creationDate().getTime()));
personKeyValues.add("locationIP");
personKeyValues.add(operation.locationIp());
personKeyValues.add("browserUsed");
personKeyValues.add(operation.browserUsed());
for (String language : operation.languages()) {
personKeyValues.add("language");
personKeyValues.add(language);
}
for (String email : operation.emails()) {
personKeyValues.add("email");
personKeyValues.add(email);
}
boolean txSucceeded = false;
int txFailCount = 0;
do {
// Add person
Vertex person = client.addVertex(personKeyValues.toArray());
// Add edge to place
Vertex place = client.vertices(
new UInt128(TorcEntity.PLACE.idSpace, operation.cityId())).next();
person.addEdge("isLocatedIn", place);
// Add edges to tags
List<UInt128> tagIds = new ArrayList<>(operation.tagIds().size());
operation.tagIds().forEach((id) ->
tagIds.add(new UInt128(TorcEntity.TAG.idSpace, id)));
Iterator<Vertex> tagVItr = client.vertices(tagIds.toArray());
tagVItr.forEachRemaining((tag) -> {
person.addEdge("hasInterest", tag);
});
// Add edges to universities
List<Object> studiedAtKeyValues = new ArrayList<>(2);
for (LdbcUpdate1AddPerson.Organization org : operation.studyAt()) {
studiedAtKeyValues.clear();
studiedAtKeyValues.add("classYear");
studiedAtKeyValues.add(String.valueOf(org.year()));
Vertex orgV = client.vertices(
new UInt128(TorcEntity.ORGANISATION.idSpace,
org.organizationId()))
.next();
person.addEdge("studyAt", orgV, studiedAtKeyValues.toArray());
}
// Add edges to companies
List<Object> workedAtKeyValues = new ArrayList<>(2);
for (LdbcUpdate1AddPerson.Organization org : operation.workAt()) {
workedAtKeyValues.clear();
workedAtKeyValues.add("workFrom");
workedAtKeyValues.add(String.valueOf(org.year()));
Vertex orgV = client.vertices(
new UInt128(TorcEntity.ORGANISATION.idSpace,
org.organizationId())).next();
person.addEdge("workAt", orgV, workedAtKeyValues.toArray());
}
try {
client.tx().commit();
txSucceeded = true;
} catch (Exception e) {
txFailCount++;
}
if (txFailCount >= MAX_TX_ATTEMPTS) {
throw new RuntimeException(String.format(
"ERROR: Transaction failed %d times, aborting...",
txFailCount));
}
} while (!txSucceeded);
reporter.report(0, LdbcNoResult.INSTANCE, operation);
}
}
/**
* Add a Like to a Post of the social network.[1]
*/
public static class LdbcUpdate2AddPostLikeHandler implements
OperationHandler<LdbcUpdate2AddPostLike, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcUpdate2AddPostLikeHandler.class);
@Override
public void executeOperation(LdbcUpdate2AddPostLike operation,
DbConnectionState dbConnectionState,
ResultReporter reporter) throws DbException {
Graph client = ((TorcDbConnectionState) dbConnectionState).getClient();
UInt128 personId =
new UInt128(TorcEntity.PERSON.idSpace, operation.personId());
UInt128 postId =
new UInt128(TorcEntity.POST.idSpace, operation.postId());
boolean txSucceeded = false;
int txFailCount = 0;
do {
Iterator<Vertex> results = client.vertices(personId, postId);
Vertex person = results.next();
Vertex post = results.next();
List<Object> keyValues = new ArrayList<>(2);
keyValues.add("creationDate");
keyValues.add(String.valueOf(operation.creationDate().getTime()));
person.addEdge("likes", post, keyValues.toArray());
try {
client.tx().commit();
txSucceeded = true;
} catch (Exception e) {
txFailCount++;
}
if (txFailCount >= MAX_TX_ATTEMPTS) {
throw new RuntimeException(String.format(
"ERROR: Transaction failed %d times, aborting...",
txFailCount));
}
} while (!txSucceeded);
reporter.report(0, LdbcNoResult.INSTANCE, operation);
}
}
/**
* Add a Like to a Comment of the social network.[1]
*/
public static class LdbcUpdate3AddCommentLikeHandler implements
OperationHandler<LdbcUpdate3AddCommentLike, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcUpdate3AddCommentLikeHandler.class);
@Override
public void executeOperation(LdbcUpdate3AddCommentLike operation,
DbConnectionState dbConnectionState,
ResultReporter reporter) throws DbException {
Graph client = ((TorcDbConnectionState) dbConnectionState).getClient();
UInt128 personId =
new UInt128(TorcEntity.PERSON.idSpace, operation.personId());
UInt128 commentId =
new UInt128(TorcEntity.COMMENT.idSpace, operation.commentId());
boolean txSucceeded = false;
int txFailCount = 0;
do {
Iterator<Vertex> results = client.vertices(personId, commentId);
Vertex person = results.next();
Vertex comment = results.next();
List<Object> keyValues = new ArrayList<>(2);
keyValues.add("creationDate");
keyValues.add(String.valueOf(operation.creationDate().getTime()));
person.addEdge("likes", comment, keyValues.toArray());
try {
client.tx().commit();
txSucceeded = true;
} catch (Exception e) {
txFailCount++;
}
if (txFailCount >= MAX_TX_ATTEMPTS) {
throw new RuntimeException(String.format(
"ERROR: Transaction failed %d times, aborting...",
txFailCount));
}
} while (!txSucceeded);
reporter.report(0, LdbcNoResult.INSTANCE, operation);
}
}
/**
* Add a Forum to the social network.[1]
*/
public static class LdbcUpdate4AddForumHandler implements
OperationHandler<LdbcUpdate4AddForum, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcUpdate4AddForum.class);
@Override
public void executeOperation(LdbcUpdate4AddForum operation,
DbConnectionState dbConnectionState,
ResultReporter reporter) throws DbException {
Graph client = ((TorcDbConnectionState) dbConnectionState).getClient();
List<Object> forumKeyValues = new ArrayList<>(8);
forumKeyValues.add(T.id);
forumKeyValues.add(
new UInt128(TorcEntity.FORUM.idSpace, operation.forumId()));
forumKeyValues.add(T.label);
forumKeyValues.add(TorcEntity.FORUM.label);
forumKeyValues.add("title");
forumKeyValues.add(operation.forumTitle());
forumKeyValues.add("creationDate");
forumKeyValues.add(String.valueOf(operation.creationDate().getTime()));
boolean txSucceeded = false;
int txFailCount = 0;
do {
Vertex forum = client.addVertex(forumKeyValues.toArray());
List<UInt128> ids = new ArrayList<>(operation.tagIds().size() + 1);
operation.tagIds().forEach((id) -> {
ids.add(new UInt128(TorcEntity.TAG.idSpace, id));
});
ids.add(new UInt128(TorcEntity.PERSON.idSpace,
operation.moderatorPersonId()));
client.vertices(ids.toArray()).forEachRemaining((v) -> {
if (v.label().equals(TorcEntity.TAG.label)) {
forum.addEdge("hasTag", v);
} else if (v.label().equals(TorcEntity.PERSON.label)) {
forum.addEdge("hasModerator", v);
} else {
throw new RuntimeException(String.format(
"ERROR: LdbcUpdate4AddForum query read a vertex with an "
+ "unexpected label: %s", v.label()));
}
});
try {
client.tx().commit();
txSucceeded = true;
} catch (Exception e) {
txFailCount++;
}
if (txFailCount >= MAX_TX_ATTEMPTS) {
throw new RuntimeException(String.format(
"ERROR: Transaction failed %d times, aborting...",
txFailCount));
}
} while (!txSucceeded);
reporter.report(0, LdbcNoResult.INSTANCE, operation);
}
}
/**
* Add a Forum membership to the social network.[1]
*/
public static class LdbcUpdate5AddForumMembershipHandler implements
OperationHandler<LdbcUpdate5AddForumMembership, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcUpdate4AddForum.class);
@Override
public void executeOperation(LdbcUpdate5AddForumMembership operation,
DbConnectionState dbConnectionState,
ResultReporter reporter) throws DbException {
Graph client = ((TorcDbConnectionState) dbConnectionState).getClient();
List<UInt128> ids = new ArrayList<>(2);
ids.add(new UInt128(TorcEntity.FORUM.idSpace, operation.forumId()));
ids.add(new UInt128(TorcEntity.PERSON.idSpace, operation.personId()));
boolean txSucceeded = false;
int txFailCount = 0;
do {
Iterator<Vertex> vItr = client.vertices(ids.toArray());
Vertex forum = vItr.next();
Vertex member = vItr.next();
List<Object> edgeKeyValues = new ArrayList<>(2);
edgeKeyValues.add("joinDate");
edgeKeyValues.add(String.valueOf(operation.joinDate().getTime()));
forum.addEdge("hasMember", member, edgeKeyValues.toArray());
try {
client.tx().commit();
txSucceeded = true;
} catch (Exception e) {
txFailCount++;
}
if (txFailCount >= MAX_TX_ATTEMPTS) {
throw new RuntimeException(String.format(
"ERROR: Transaction failed %d times, aborting...",
txFailCount));
}
} while (!txSucceeded);
reporter.report(0, LdbcNoResult.INSTANCE, operation);
}
}
/**
* Add a Post to the social network.[1]
*/
public static class LdbcUpdate6AddPostHandler implements
OperationHandler<LdbcUpdate6AddPost, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcUpdate4AddForum.class);
@Override
public void executeOperation(LdbcUpdate6AddPost operation,
DbConnectionState dbConnectionState,
ResultReporter reporter) throws DbException {
Graph client = ((TorcDbConnectionState) dbConnectionState).getClient();
List<Object> postKeyValues = new ArrayList<>(18);
postKeyValues.add(T.id);
postKeyValues.add(
new UInt128(TorcEntity.POST.idSpace, operation.postId()));
postKeyValues.add(T.label);
postKeyValues.add(TorcEntity.POST.label);
postKeyValues.add("imageFile");
postKeyValues.add(operation.imageFile());
postKeyValues.add("creationDate");
postKeyValues.add(String.valueOf(operation.creationDate().getTime()));
postKeyValues.add("locationIP");
postKeyValues.add(operation.locationIp());
postKeyValues.add("browserUsed");
postKeyValues.add(operation.browserUsed());
postKeyValues.add("language");
postKeyValues.add(operation.language());
postKeyValues.add("content");
postKeyValues.add(operation.content());
postKeyValues.add("length");
postKeyValues.add(String.valueOf(operation.length()));
boolean txSucceeded = false;
int txFailCount = 0;
do {
Vertex post = client.addVertex(postKeyValues.toArray());
List<UInt128> ids = new ArrayList<>(2);
ids.add(new UInt128(TorcEntity.PERSON.idSpace,
operation.authorPersonId()));
ids.add(new UInt128(TorcEntity.FORUM.idSpace, operation.forumId()));
ids.add(new UInt128(TorcEntity.PLACE.idSpace, operation.countryId()));
operation.tagIds().forEach((id) -> {
ids.add(new UInt128(TorcEntity.TAG.idSpace, id));
});
client.vertices(ids.toArray()).forEachRemaining((v) -> {
if (v.label().equals(TorcEntity.PERSON.label)) {
post.addEdge("hasCreator", v);
} else if (v.label().equals(TorcEntity.FORUM.label)) {
v.addEdge("containerOf", post);
} else if (v.label().equals(TorcEntity.PLACE.label)) {
post.addEdge("isLocatedIn", v);
} else if (v.label().equals(TorcEntity.TAG.label)) {
post.addEdge("hasTag", v);
} else {
throw new RuntimeException(String.format(
"ERROR: LdbcUpdate6AddPostHandler query read a vertex with an "
+ "unexpected label: %s", v.label()));
}
});
try {
client.tx().commit();
txSucceeded = true;
} catch (Exception e) {
txFailCount++;
}
if (txFailCount >= MAX_TX_ATTEMPTS) {
throw new RuntimeException(String.format(
"ERROR: Transaction failed %d times, aborting...",
txFailCount));
}
} while (!txSucceeded);
reporter.report(0, LdbcNoResult.INSTANCE, operation);
}
}
/**
* Add a Comment replying to a Post/Comment to the social network.[1]
*/
public static class LdbcUpdate7AddCommentHandler implements
OperationHandler<LdbcUpdate7AddComment, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcUpdate4AddForum.class);
@Override
public void executeOperation(LdbcUpdate7AddComment operation,
DbConnectionState dbConnectionState,
ResultReporter reporter) throws DbException {
Graph client = ((TorcDbConnectionState) dbConnectionState).getClient();
List<Object> commentKeyValues = new ArrayList<>(14);
commentKeyValues.add(T.id);
commentKeyValues.add(
new UInt128(TorcEntity.COMMENT.idSpace, operation.commentId()));
commentKeyValues.add(T.label);
commentKeyValues.add(TorcEntity.COMMENT.label);
commentKeyValues.add("creationDate");
commentKeyValues.add(String.valueOf(operation.creationDate().getTime()));
commentKeyValues.add("locationIP");
commentKeyValues.add(operation.locationIp());
commentKeyValues.add("browserUsed");
commentKeyValues.add(operation.browserUsed());
commentKeyValues.add("content");
commentKeyValues.add(operation.content());
commentKeyValues.add("length");
commentKeyValues.add(String.valueOf(operation.length()));
boolean txSucceeded = false;
int txFailCount = 0;
do {
Vertex comment = client.addVertex(commentKeyValues.toArray());
List<UInt128> ids = new ArrayList<>(2);
ids.add(new UInt128(TorcEntity.PERSON.idSpace,
operation.authorPersonId()));
ids.add(new UInt128(TorcEntity.PLACE.idSpace, operation.countryId()));
operation.tagIds().forEach((id) -> {
ids.add(new UInt128(TorcEntity.TAG.idSpace, id));
});
if (operation.replyToCommentId() != -1) {
ids.add(new UInt128(TorcEntity.COMMENT.idSpace,
operation.replyToCommentId()));
}
if (operation.replyToPostId() != -1) {
ids.add(
new UInt128(TorcEntity.POST.idSpace, operation.replyToPostId()));
}
client.vertices(ids.toArray()).forEachRemaining((v) -> {
if (v.label().equals(TorcEntity.PERSON.label)) {
comment.addEdge("hasCreator", v);
} else if (v.label().equals(TorcEntity.PLACE.label)) {
comment.addEdge("isLocatedIn", v);
} else if (v.label().equals(TorcEntity.COMMENT.label)) {
comment.addEdge("replyOf", v);
} else if (v.label().equals(TorcEntity.POST.label)) {
comment.addEdge("replyOf", v);
} else if (v.label().equals(TorcEntity.TAG.label)) {
comment.addEdge("hasTag", v);
} else {
throw new RuntimeException(String.format(
"ERROR: LdbcUpdate7AddCommentHandler query read a vertex with "
+ "an unexpected label: %s", v.label()));
}
});
try {
client.tx().commit();
txSucceeded = true;
} catch (Exception e) {
txFailCount++;
}
if (txFailCount >= MAX_TX_ATTEMPTS) {
throw new RuntimeException(String.format(
"ERROR: Transaction failed %d times, aborting...",
txFailCount));
}
} while (!txSucceeded);
reporter.report(0, LdbcNoResult.INSTANCE, operation);
}
}
/**
* Add a friendship relation to the social network.[1]
*/
public static class LdbcUpdate8AddFriendshipHandler implements
OperationHandler<LdbcUpdate8AddFriendship, DbConnectionState> {
final static Logger logger =
LoggerFactory.getLogger(LdbcUpdate4AddForum.class);
@Override
public void executeOperation(LdbcUpdate8AddFriendship operation,
DbConnectionState dbConnectionState,
ResultReporter reporter) throws DbException {
Graph client = ((TorcDbConnectionState) dbConnectionState).getClient();
List<Object> knowsEdgeKeyValues = new ArrayList<>(2);
knowsEdgeKeyValues.add("creationDate");
knowsEdgeKeyValues.add(
String.valueOf(operation.creationDate().getTime()));
List<UInt128> ids = new ArrayList<>(2);
ids.add(new UInt128(TorcEntity.PERSON.idSpace, operation.person1Id()));
ids.add(new UInt128(TorcEntity.PERSON.idSpace, operation.person2Id()));
boolean txSucceeded = false;
int txFailCount = 0;
do {
Iterator<Vertex> vItr = client.vertices(ids.toArray());
Vertex person1 = vItr.next();
Vertex person2 = vItr.next();
person1.addEdge("knows", person2, knowsEdgeKeyValues.toArray());
person2.addEdge("knows", person1, knowsEdgeKeyValues.toArray());
try {
client.tx().commit();
txSucceeded = true;
} catch (Exception e) {
txFailCount++;
}
if (txFailCount >= MAX_TX_ATTEMPTS) {
throw new RuntimeException(String.format(
"ERROR: Transaction failed %d times, aborting...",
txFailCount));
}
} while (!txSucceeded);
reporter.report(0, LdbcNoResult.INSTANCE, operation);
}
}
}
|
// modification, are permitted provided that the following conditions are met:
// documentation and/or other materials provided with the distribution.
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// 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 jodd.mail;
import jodd.io.StreamUtil;
import jodd.util.StringPool;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
/**
* Developer-friendly class for parsing EML files.
*/
public class EMLParser {
/**
* Starts EML parsing with provided EML content.
*/
public static EMLParser loadEML(String emlContent, String charset) throws UnsupportedEncodingException {
byte[] bytes = emlContent.getBytes(charset);
return loadEML(bytes);
}
/**
* Starts EML parsing with provided EML content, assuming UTF-8 charset.
*/
public static EMLParser loadEML(String emlContent) throws UnsupportedEncodingException {
return loadEML(emlContent, StringPool.UTF_8);
}
/**
* Starts EML parsing with provided EML content.
*/
public static EMLParser loadEML(byte[] content) {
return new EMLParser(new ByteArrayInputStream(content));
}
/**
* Starts EML parsing with provided EML file.
*/
public static EMLParser loadEML(File emlFile) throws FileNotFoundException {
return new EMLParser(new FileInputStream(emlFile));
}
protected final InputStream emlContentInputStream;
protected Session session;
protected EMLParser(InputStream emlContent) {
this.emlContentInputStream = emlContent;
}
/**
* Sets the custom session.
*/
public EMLParser session(Session session) {
this.session = session;
return this;
}
/**
* Creates new session with given properties.
*/
public EMLParser session(Properties properties) {
this.session = createSession(properties);
return this;
}
/**
* Uses default session.
*/
public EMLParser defaultSession() {
this.session = Session.getDefaultInstance(System.getProperties());
return this;
}
/**
* Parses the EML content. If session is not created, default one
* will be used.
*/
public ReceivedEmail parse() throws MessagingException {
if (session == null) {
session = createSession(null);
}
Message message;
try {
message = new MimeMessage(session, emlContentInputStream);
} finally {
StreamUtil.close(emlContentInputStream);
}
return new ReceivedEmail(message);
}
/**
* Creates new session with or without custom properties.
*/
protected Session createSession(Properties properties) {
if (properties == null) {
properties = System.getProperties();
}
return Session.getInstance(properties);
}
}
|
package gov.nih.nci.cananolab.ui.sample;
import gov.nih.nci.cananolab.dto.common.ColumnHeader;
import gov.nih.nci.cananolab.dto.common.ExperimentConfigBean;
import gov.nih.nci.cananolab.dto.common.FileBean;
import gov.nih.nci.cananolab.dto.common.FindingBean;
import gov.nih.nci.cananolab.dto.particle.SampleBean;
import gov.nih.nci.cananolab.dto.particle.characterization.CharacterizationBean;
import gov.nih.nci.cananolab.dto.particle.characterization.CharacterizationSummaryViewBean;
import gov.nih.nci.cananolab.exception.SecurityException;
import gov.nih.nci.cananolab.service.protocol.ProtocolService;
import gov.nih.nci.cananolab.service.protocol.impl.ProtocolServiceLocalImpl;
import gov.nih.nci.cananolab.service.sample.CharacterizationService;
import gov.nih.nci.cananolab.service.sample.SampleService;
import gov.nih.nci.cananolab.service.sample.impl.CharacterizationExporter;
import gov.nih.nci.cananolab.service.sample.impl.CharacterizationServiceLocalImpl;
import gov.nih.nci.cananolab.service.sample.impl.SampleServiceLocalImpl;
import gov.nih.nci.cananolab.service.security.SecurityService;
import gov.nih.nci.cananolab.service.security.UserBean;
import gov.nih.nci.cananolab.ui.core.BaseAnnotationAction;
import gov.nih.nci.cananolab.ui.core.InitSetup;
import gov.nih.nci.cananolab.ui.protocol.InitProtocolSetup;
import gov.nih.nci.cananolab.util.Constants;
import gov.nih.nci.cananolab.util.ExportUtils;
import gov.nih.nci.cananolab.util.SampleConstants;
import gov.nih.nci.cananolab.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorForm;
/**
* Base action for characterization actions
*
* @author pansu
*/
public class CharacterizationAction extends BaseAnnotationAction {
/**
* Add or update the data to database
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward create(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean charBean = (CharacterizationBean) theForm
.get("achar");
this.setServicesInSession(request);
// Copy "isSoluble" property from char bean to mapping bean.
this.copyIsSoluble(charBean);
InitCharacterizationSetup.getInstance()
.persistCharacterizationDropdowns(request, charBean);
if (!validateInputs(request, charBean)) {
return mapping.getInputForward();
}
this.saveCharacterization(request, theForm, charBean);
ActionMessages msgs = new ActionMessages();
ActionMessage msg = new ActionMessage("message.addCharacterization",
charBean.getCharacterizationName());
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
saveMessages(request, msgs);
// to preselect the same characterization type after returning to the
// summary page
List<String> allCharacterizationTypes = InitCharacterizationSetup
.getInstance().getCharacterizationTypes(request);
int ind = allCharacterizationTypes.indexOf(charBean
.getCharacterizationType()) + 1;
request.getSession().setAttribute("tab", String.valueOf(ind));
return summaryEdit(mapping, form, request, response);
}
public ActionForward input(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean charBean = (CharacterizationBean) theForm
.get("achar");
charBean.updateEmptyFieldsToNull();
this.checkOpenForms(charBean, theForm, request);
// Save uploaded data in session to avoid asking user to upload again.
FileBean theFile = charBean.getTheFinding().getTheFile();
escapeXmlForFileUri(theFile);
String charName = StringUtils.getOneWordLowerCaseFirstLetter(charBean
.getCharacterizationName());
preserveUploadedFile(request, theFile, charName);
return mapping.findForward("inputForm");
}
/**
* Set up the input form for adding new characterization
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setupNew(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
this.setServicesInSession(request);
setupInputForm(request, theForm);
// reset characterizationBean
CharacterizationBean charBean = new CharacterizationBean();
theForm.set("achar", charBean);
String charType = request.getParameter("charType");
if (!StringUtils.isEmpty(charType)) {
charBean.setCharacterizationType(charType);
SortedSet<String> charNames = InitCharacterizationSetup
.getInstance().getCharNamesByCharType(request,
charBean.getCharacterizationType());
request.getSession().setAttribute("charTypeChars", charNames);
}
this.checkOpenForms(charBean, theForm, request);
// clear copy to otherSamples
clearCopy(theForm);
return mapping.findForward("inputForm");
}
/**
* Set up drop-downs need for the input form
*
* @param request
* @param theForm
* @throws Exception
*/
private void setupInputForm(HttpServletRequest request,
DynaValidatorForm theForm) throws Exception {
String sampleId = theForm.getString("sampleId");
String charType = request.getParameter("charType");
if (charType == null) {
charType = (String) request.getAttribute("charType");
}
if (!StringUtils.isEmpty(charType))
InitProtocolSetup.getInstance().getProtocolsByChar(request,
charType);
InitCharacterizationSetup.getInstance().setPOCDropdown(request,
sampleId);
InitCharacterizationSetup.getInstance().setCharacterizationDropdowns(
request);
// String detailPage = setupDetailPage(charBean);
// request.getSession().setAttribute("characterizationDetailPage",
// detailPage);
// set up other samples with the same primary point of contact
InitSampleSetup.getInstance().getOtherSampleNames(request, sampleId);
// // clear the session list that stores other column names for the
// // characterization
// request.getSession().removeAttribute("otherCharDatumNames");
// request.getSession().removeAttribute("otherCharConditionNames");
// request.getSession().removeAttribute("otherCharConditionProperties");
// request.getSession().removeAttribute("otherCharValueUnits");
// request.getSession().removeAttribute("otherCharValueTypes");
}
/**
* Set up the input form for editing existing characterization
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setupUpdate(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationService charService = this
.setServicesInSession(request);
String charId = super.validateId(request, "charId");
CharacterizationBean charBean = charService
.findCharacterizationById(charId);
// setup Characterization Name drop down.
InitCharacterizationSetup.getInstance().getCharNamesByCharType(request,
charBean.getCharacterizationType());
// setup Assay Type drop down.
InitSetup.getInstance().getDefaultAndOtherTypesByLookup(request,
"charNameAssays", charBean.getCharacterizationName(),
"assayType", "otherAssayType", true);
// TODO: Find out usage of "charNameDatumNames", not used in any JSPs.
InitCharacterizationSetup.getInstance().getDatumNamesByCharName(
request, charBean.getCharacterizationType(),
charBean.getCharacterizationName(), charBean.getAssayType());
request.setAttribute("achar", charBean);
theForm.set("achar", charBean);
this.setupInputForm(request, theForm);
this.setupIsSoluble(charBean); // setup "isSoluble" property.
this.checkOpenForms(charBean, theForm, request);
// clear copy to otherSamples
clearCopy(theForm);
return mapping.findForward("inputForm");
}
private void clearCopy(DynaValidatorForm theForm) {
theForm.set("otherSamples", new String[0]);
theForm.set("copyData", false);
}
/**
* Setup, prepare and save characterization.
*
* @param request
* @param theForm
* @param charBean
* @throws Exception
*/
private void saveCharacterization(HttpServletRequest request,
DynaValidatorForm theForm, CharacterizationBean charBean)
throws Exception {
SampleBean sampleBean = setupSample(theForm, request);
UserBean user = (UserBean) request.getSession().getAttribute("user");
charBean.setupDomain(user.getLoginName());
Boolean newChar = true;
if (charBean.getDomainChar().getId() != null) {
newChar = false;
}
// reuse the existing char service
CharacterizationService charService = (CharacterizationService) request
.getSession().getAttribute("characterizationService");
charService.saveCharacterization(sampleBean, charBean);
// retract from public if updating an existing public record and not
// curator
if (!newChar && !user.isCurator() && sampleBean.getPublicStatus()) {
retractFromPublic(theForm, request, sampleBean.getDomain().getId()
.toString(), sampleBean.getDomain().getName(), "sample");
ActionMessages messages = new ActionMessages();
ActionMessage msg = null;
msg = new ActionMessage("message.updateSample.retractFromPublic");
messages.add(ActionMessages.GLOBAL_MESSAGE, msg);
saveMessages(request, messages);
}
// save to other samples (only when user click [Submit] button.)
String dispatch = (String) theForm.get("dispatch");
if ("create".equals(dispatch)) {
SampleBean[] otherSampleBeans = prepareCopy(request, theForm,
sampleBean);
if (otherSampleBeans != null) {
Boolean copyData = (Boolean) theForm.get("copyData");
charService.copyAndSaveCharacterization(charBean, sampleBean,
otherSampleBeans, copyData);
}
}
sampleBean = setupSample(theForm, request);
request.setAttribute("sampleId", sampleBean.getDomain().getId()
.toString());
}
private void deleteCharacterization(HttpServletRequest request,
DynaValidatorForm theForm, CharacterizationBean charBean,
String createdBy) throws Exception {
charBean.setupDomain(createdBy);
CharacterizationService service = this.setServicesInSession(request);
service.deleteCharacterization(charBean.getDomainChar());
service.removeAccesses(charBean.getDomainChar());
}
public ActionForward delete(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean charBean = (CharacterizationBean) theForm
.get("achar");
UserBean user = (UserBean) request.getSession().getAttribute("user");
deleteCharacterization(request, theForm, charBean, user.getLoginName());
ActionMessages msgs = new ActionMessages();
ActionMessage msg = new ActionMessage("message.deleteCharacterization");
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
saveMessages(request, msgs);
ActionForward forward = mapping.findForward("success");
return forward;
}
/**
* summaryEdit() handles Edit request for Characterization Summary view.
*
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
* @throws Exception
*/
public ActionForward summaryEdit(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
// Prepare data.
this.prepareSummary(mapping, form, request, response);
// prepare characterization tabs and forward to appropriate tab
List<String> allCharacterizationTypes = InitCharacterizationSetup
.getInstance().getCharacterizationTypes(request);
setSummaryTab(request, allCharacterizationTypes.size());
return mapping.findForward("summaryEdit");
}
/**
* summaryView() handles View request for Characterization Summary report.
*
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
* @throws Exception
* if error occurred.
*/
public ActionForward summaryView(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
// Prepare data.
prepareSummary(mapping, form, request, response);
List<String> charTypes = prepareCharacterizationTypes(mapping, form,
request, response);
setSummaryTab(request, charTypes.size());
return mapping.findForward("summaryView");
}
public ActionForward setupView(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationService service = this.setServicesInSession(request);
String charId = super.validateId(request, "charId");
setupSample(theForm, request);
CharacterizationBean charBean = service
.findCharacterizationById(charId);
request.setAttribute("charBean", charBean);
return mapping.findForward("singleSummaryView");
}
/**
* Shared function for summaryView(), summaryPrint() and summaryEdit().
* Prepare CharacterizationBean based on Sample Id.
*
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
* @throws Exception
*/
private void prepareSummary(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
// Remove previous result from session.
request.getSession().removeAttribute("characterizationSummaryView");
request.getSession().removeAttribute("theSample");
DynaValidatorForm theForm = (DynaValidatorForm) form;
String sampleId = theForm.getString(SampleConstants.SAMPLE_ID);
CharacterizationService service = this.setServicesInSession(request);
SampleBean sampleBean = setupSample(theForm, request);
List<CharacterizationBean> charBeans = service
.findCharacterizationsBySampleId(sampleId);
CharacterizationSummaryViewBean summaryView = new CharacterizationSummaryViewBean(
charBeans);
// Save result bean in session for later use - export/print.
request.getSession().setAttribute("characterizationSummaryView",
summaryView);
// Save sample bean in session for sample name in export/print.
request.getSession().setAttribute("theSample", sampleBean);
}
/**
* Shared function for summaryView() and summaryPrint(). Keep submitted
* characterization types in the correct display order. Should be called
* after calling prepareSummary(), to avoid session timeout issue.
*
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
* @throws Exception
*/
private List<String> prepareCharacterizationTypes(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
CharacterizationSummaryViewBean summaryView = (CharacterizationSummaryViewBean) request
.getSession().getAttribute("characterizationSummaryView");
// Keep submitted characterization types in the correct display order
// prepare characterization tabs and forward to appropriate tab
List<String> allCharacterizationTypes = InitCharacterizationSetup
.getInstance().getCharacterizationTypes(request);
Set<String> foundTypes = summaryView.getCharacterizationTypes();
List<String> characterizationTypes = new ArrayList<String>();
for (String charType : allCharacterizationTypes) {
if (foundTypes.contains(charType)
&& !characterizationTypes.contains(charType)) {
characterizationTypes.add(charType);
}
}
// other types that are not in allCharacterizationTypes, e.g. other
// types from grid search
for (String type : foundTypes) {
if (!characterizationTypes.contains(type)) {
characterizationTypes.add(type);
}
}
request.setAttribute("characterizationTypes", characterizationTypes);
return characterizationTypes;
}
/**
* summaryPrint() handles Print request for Characterization Summary report.
*
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
* @throws Exception
*/
public ActionForward summaryPrint(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
CharacterizationSummaryViewBean charSummaryBean = (CharacterizationSummaryViewBean) request
.getSession().getAttribute("characterizationSummaryView");
if (charSummaryBean == null) {
// Retrieve data again when session timeout.
this.prepareSummary(mapping, form, request, response);
charSummaryBean = (CharacterizationSummaryViewBean) request
.getSession().getAttribute("characterizationSummaryView");
}
List<String> charTypes = prepareCharacterizationTypes(mapping, form,
request, response);
this.filterType(request, charTypes); // Filter out un-selected types.
// Marker that indicates page is for printing only, hide tabs/links.
request.setAttribute("printView", Boolean.TRUE);
return mapping.findForward("summaryPrintView");
}
/**
* Export Characterization Summary report.
*
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
* @throws Exception
*/
public ActionForward summaryExport(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
SampleBean sampleBean = (SampleBean) request.getSession().getAttribute(
"theSample");
CharacterizationSummaryViewBean charSummaryBean = (CharacterizationSummaryViewBean) request
.getSession().getAttribute("characterizationSummaryView");
if (sampleBean == null || charSummaryBean == null) {
// Prepare data.
this.prepareSummary(mapping, form, request, response);
sampleBean = (SampleBean) request.getSession().getAttribute(
"theSample");
charSummaryBean = (CharacterizationSummaryViewBean) request
.getSession().getAttribute("characterizationSummaryView");
}
List<String> charTypes = prepareCharacterizationTypes(mapping, form,
request, response);
List<String> filteredCharTypes = this.filterType(request, charTypes);
String type = request.getParameter("type");
// per app scan
if (!StringUtils.xssValidate(type)) {
type = "";
}
String sampleName = sampleBean.getDomain().getName();
String fileName = ExportUtils.getExportFileName(sampleName,
"CharacterizationSummaryView", type);
ExportUtils.prepareReponseForExcel(response, fileName);
StringBuilder sb = getDownloadUrl(request);
CharacterizationExporter.exportSummary(filteredCharTypes,
charSummaryBean, sb.toString(), response.getOutputStream());
return null;
}
public ActionForward saveExperimentConfig(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
ExperimentConfigBean configBean = achar.getTheExperimentConfig();
UserBean user = (UserBean) request.getSession().getAttribute("user");
configBean.setupDomain(user.getLoginName());
CharacterizationService service = this.setServicesInSession(request);
service.saveExperimentConfig(configBean);
achar.addExperimentConfig(configBean);
// also save characterization
if (!validateInputs(request, achar)) {
return mapping.getInputForward();
}
this.saveCharacterization(request, theForm, achar);
service.assignAccesses(achar.getDomainChar(), configBean.getDomain());
this.checkOpenForms(achar, theForm, request);
// return to setupUpdate to retrieve the data matrix in the correct
// form from database
// after saving to database.
request.setAttribute("charId", achar.getDomainChar().getId().toString());
request.setAttribute("charType", achar.getCharacterizationType());
return setupUpdate(mapping, form, request, response);
}
public ActionForward getFinding(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
String theFindingId = request.getParameter("findingId");
CharacterizationService service = this.setServicesInSession(request);
FindingBean findingBean = service.findFindingById(theFindingId);
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
achar.setTheFinding(findingBean);
request.setAttribute("anchor", "submitFinding");
this.checkOpenForms(achar, theForm, request);
// Feature request [26487] Deeper Edit Links.
if (findingBean.getFiles().size() == 1) {
request.setAttribute("onloadJavascript", "setTheFile(0)");
}
request.setAttribute("disableOuterButtons", true);
// remove columnHeaders stored in the session;
request.getSession().removeAttribute("columnHeaders");
return mapping.findForward("inputForm");
}
public ActionForward resetFinding(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
FindingBean theFinding = new FindingBean();
// theFinding.setNumberOfColumns(1);
// theFinding.setNumberOfRows(1);
// theFinding.updateMatrix(theFinding.getNumberOfColumns(), theFinding
// .getNumberOfRows());
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
achar.setTheFinding(theFinding);
request.setAttribute("anchor", "submitFinding");
this.checkOpenForms(achar, theForm, request);
request.setAttribute("disableOuterButtons", true);
request.getSession().removeAttribute("columnHeaders");
return mapping.findForward("inputForm");
}
public ActionForward saveFinding(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationService service = this.setServicesInSession(request);
SampleBean sampleBean = setupSample(theForm, request);
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
FindingBean findingBean = achar.getTheFinding();
String theFindingId = (String) request.getAttribute("theFindingId");
if (!StringUtils.isEmpty(theFindingId)) {
findingBean.getDomain().setId(Long.valueOf(theFindingId));
}
if (!validateEmptyFinding(request, findingBean)) {
return mapping.getInputForward();
}
UserBean user = (UserBean) request.getSession().getAttribute("user");
// setup domainFile uri for fileBeans
String internalUriPath = Constants.FOLDER_PARTICLE
+ '/'
+ sampleBean.getDomain().getName()
+ '/'
+ StringUtils.getOneWordLowerCaseFirstLetter(achar
.getCharacterizationName());
findingBean.setupDomain(internalUriPath, user.getLoginName());
service.saveFinding(findingBean);
achar.addFinding(findingBean);
// also save characterization
if (!validateInputs(request, achar)) {
return mapping.getInputForward();
}
this.saveCharacterization(request, theForm, achar);
service.assignAccesses(achar.getDomainChar(), findingBean.getDomain());
this.checkOpenForms(achar, theForm, request);
request.setAttribute("anchor", "result");
// return to setupUpdate to retrieve the data matrix in the correct
// form from database
// after saving to database.
request.setAttribute("charId", achar.getDomainChar().getId().toString());
request.setAttribute("charType", achar.getCharacterizationType());
return setupUpdate(mapping, form, request, response);
}
public ActionForward addFile(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
FindingBean findingBean = achar.getTheFinding();
FileBean theFile = findingBean.getTheFile();
int theFileIndex = findingBean.getTheFileIndex();
// restore previously uploaded file from session.
restoreUploadedFile(request, theFile);
this.setServicesInSession(request);
// create a new copy before adding to finding
FileBean newFile = theFile.copy();
SampleBean sampleBean = setupSample(theForm, request);
// setup domainFile uri for fileBeans
String internalUriPath = Constants.FOLDER_PARTICLE
+ '/'
+ sampleBean.getDomain().getName()
+ '/'
+ StringUtils.getOneWordLowerCaseFirstLetter(achar
.getCharacterizationName());
UserBean user = (UserBean) request.getSession().getAttribute("user");
newFile.setupDomainFile(internalUriPath, user.getLoginName());
findingBean.addFile(newFile, theFileIndex);
request.setAttribute("anchor", "submitFinding");
this.checkOpenForms(achar, theForm, request);
return mapping.findForward("inputForm");
}
public ActionForward removeFile(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
FindingBean findingBean = achar.getTheFinding();
int theFileIndex = findingBean.getTheFileIndex();
findingBean.removeFile(theFileIndex);
findingBean.setTheFile(new FileBean());
request.setAttribute("anchor", "submitFinding");
this.checkOpenForms(achar, theForm, request);
return mapping.findForward("inputForm");
}
public ActionForward drawMatrix(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
request.setAttribute("anchor", "result");
FindingBean findingBean = achar.getTheFinding();
if (request.getParameter("removeColumn") != null) {
int columnToRemove = Integer.parseInt(request
.getParameter("removeColumn"));
findingBean.removeColumn(columnToRemove);
this.checkOpenForms(achar, theForm, request);
return mapping.findForward("inputForm");
} else if (request.getParameter("removeRow") != null) {
int rowToRemove = Integer.parseInt(request
.getParameter("removeRow"));
findingBean.removeRow(rowToRemove);
this.checkOpenForms(achar, theForm, request);
return mapping.findForward("inputForm");
}
int existingNumberOfColumns = findingBean.getColumnHeaders().size();
int existingNumberOfRows = findingBean.getRows().size();
if (existingNumberOfColumns > findingBean.getNumberOfColumns()) {
ActionMessages msgs = new ActionMessages();
ActionMessage msg = new ActionMessage(
"message.addCharacterization.removeMatrixColumn");
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
saveMessages(request, msgs);
findingBean.setNumberOfColumns(existingNumberOfColumns);
this.checkOpenForms(achar, theForm, request);
return mapping.getInputForward();
}
if (existingNumberOfRows > findingBean.getNumberOfRows()) {
ActionMessages msgs = new ActionMessages();
ActionMessage msg = new ActionMessage(
"message.addCharacterization.removeMatrixRow");
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
saveMessages(request, msgs);
findingBean.setNumberOfRows(existingNumberOfRows);
this.checkOpenForms(achar, theForm, request);
return mapping.getInputForward();
}
findingBean.updateMatrix(findingBean.getNumberOfColumns(),
findingBean.getNumberOfRows());
request.setAttribute("anchor", "submitFinding");
this.checkOpenForms(achar, theForm, request);
// set columnHeaders in the session so jsp can check duplicate columns
request.getSession().setAttribute("columnHeaders",
findingBean.getColumnHeaders());
return mapping.findForward("inputForm");
}
public ActionForward deleteFinding(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
FindingBean dataSetBean = achar.getTheFinding();
CharacterizationService service = this.setServicesInSession(request);
service.deleteFinding(dataSetBean.getDomain());
service.removeAccesses(achar.getDomainChar(), dataSetBean.getDomain());
achar.removeFinding(dataSetBean);
request.setAttribute("anchor", "result");
this.checkOpenForms(achar, theForm, request);
return mapping.findForward("inputForm");
}
public ActionForward deleteExperimentConfig(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
ExperimentConfigBean configBean = achar.getTheExperimentConfig();
CharacterizationService service = this.setServicesInSession(request);
service.deleteExperimentConfig(configBean.getDomain());
// TODO remove accessibility
achar.removeExperimentConfig(configBean);
// also save characterization
if (!validateInputs(request, achar)) {
return mapping.getInputForward();
}
this.saveCharacterization(request, theForm, achar);
service.removeAccesses(achar.getDomainChar(), configBean.getDomain());
this.checkOpenForms(achar, theForm, request);
return mapping.findForward("inputForm");
}
// FR# [26194], matrix column order.
public ActionForward updateColumnOrder(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
FindingBean findingBean = achar.getTheFinding();
findingBean.updateColumnOrder();
request.setAttribute("anchor", "submitFinding");
this.checkOpenForms(achar, theForm, request);
return mapping.findForward("inputForm");
}
private void checkOpenForms(CharacterizationBean achar,
DynaValidatorForm theForm, HttpServletRequest request)
throws Exception {
achar.updateEmptyFieldsToNull();
String dispatch = request.getParameter("dispatch");
String browserDispatch = getBrowserDispatch(request);
HttpSession session = request.getSession();
Boolean openFile = false, openExperimentConfig = false, openFinding = false;
if (dispatch.equals("input") && browserDispatch.equals("addFile")) {
openFile = true;
}
session.setAttribute("openFile", openFile);
if (dispatch.equals("input")
&& browserDispatch.equals("saveExperimentConfig")) {
openExperimentConfig = true;
}
session.setAttribute("openExperimentConfig", openExperimentConfig);
if (dispatch.equals("input")
&& (browserDispatch.equals("saveFinding") || browserDispatch
.equals("addFile")) || dispatch.equals("addFile")
|| dispatch.equals("removeFile")
|| dispatch.equals("drawMatrix")
|| dispatch.equals("getFinding")
|| dispatch.equals("resetFinding")
|| dispatch.equals("updateColumnOrder")) {
openFinding = true;
}
session.setAttribute("openFinding", openFinding);
InitCharacterizationSetup.getInstance()
.persistCharacterizationDropdowns(request, achar);
/**
* If user entered customized Char Type/Name, Assay Type by selecting
* [other], we should show and highlight the value on the edit page.
*/
String currentCharType = achar.getCharacterizationType();
setOtherValueOption(request, currentCharType, "characterizationTypes");
String currentCharName = achar.getCharacterizationName();
setOtherValueOption(request, currentCharName, "charTypeChars");
String currentAssayType = achar.getAssayType();
setOtherValueOption(request, currentAssayType, "charNameAssays");
// setup detail page
String detailPage = null;
if (!StringUtils.isEmpty(achar.getCharacterizationType())
&& !StringUtils.isEmpty(achar.getCharacterizationName())) {
detailPage = InitCharacterizationSetup.getInstance().getDetailPage(
achar.getCharacterizationType(),
achar.getCharacterizationName());
}
request.setAttribute("characterizationDetailPage", detailPage);
// if finding contains more than one column, set disableSetColumnOrder
// false
if (achar.getTheFinding().getNumberOfColumns() > 1
&& dataMatrixSaved(achar.getTheFinding())) {
request.setAttribute("setColumnOrder", true);
} else {
request.setAttribute("setColumnOrder", false);
}
}
private Boolean dataMatrixSaved(FindingBean theFinding) {
if (theFinding.getColumnHeaders() != null) {
for (ColumnHeader header : theFinding.getColumnHeaders()) {
if (header.getCreatedDate() == null) {
return false;
}
}
}
return true;
}
/**
* Shared function for summaryExport() and summaryPrint(). Filter out
* unselected types when user selected one type for print/export.
*
* @param request
* @param compBean
*/
private List<String> filterType(HttpServletRequest request,
List<String> charTypes) {
String type = request.getParameter("type");
List<String> filteredTypes = new ArrayList<String>();
if (!StringUtils.isEmpty(type) && charTypes.contains(type)) {
filteredTypes.add(type);
}
request.setAttribute("characterizationTypes", filteredTypes);
return charTypes;
}
private boolean validateCharacterization(HttpServletRequest request,
CharacterizationBean achar) {
ActionMessages msgs = new ActionMessages();
boolean status = true;
if (achar.getCharacterizationName().equalsIgnoreCase("shape")) {
if (achar.getShape().getType() != null
&& !StringUtils.xssValidate(achar.getShape().getType())) {
ActionMessage msg = new ActionMessage(
"achar.shape.type.invalid");
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
saveErrors(request, msgs);
status = false;
}
if (achar.getShape().getMaxDimensionUnit() != null
&& !achar.getShape().getMaxDimensionUnit()
.matches(Constants.UNIT_PATTERN)) {
ActionMessage msg = new ActionMessage(
"achar.shape.maxDimensionUnit.invalid");
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
saveErrors(request, msgs);
status = false;
}
if (achar.getShape().getMinDimensionUnit() != null
&& !achar.getShape().getMinDimensionUnit()
.matches(Constants.UNIT_PATTERN)) {
ActionMessage msg = new ActionMessage(
"achar.shape.minDimensionUnit.invalid");
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
saveErrors(request, msgs);
status = false;
}
} else if (achar.getCharacterizationName().equalsIgnoreCase(
"physical state")) {
if (achar.getPhysicalState().getType() != null
&& !StringUtils.xssValidate(achar.getPhysicalState()
.getType())) {
ActionMessage msg = new ActionMessage(
"achar.physicalState.type.invalid");
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
saveErrors(request, msgs);
status = false;
}
} else if (achar.getCharacterizationName().equalsIgnoreCase(
"solubility")) {
if (achar.getSolubility().getSolvent() != null
&& !StringUtils.xssValidate(achar.getSolubility()
.getSolvent())) {
ActionMessage msg = new ActionMessage(
"achar.solubility.solvent.invalid");
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
saveErrors(request, msgs);
status = false;
}
if (achar.getSolubility().getCriticalConcentrationUnit() != null
&& !achar.getSolubility().getCriticalConcentrationUnit()
.matches(Constants.UNIT_PATTERN)) {
ActionMessage msg = new ActionMessage(
"achar.solubility.criticalConcentrationUnit.invalid");
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
saveErrors(request, msgs);
status = false;
}
} else if (achar.getCharacterizationName().equalsIgnoreCase(
"enzyme induction")) {
if (achar.getEnzymeInduction().getEnzyme() != null
&& !StringUtils.xssValidate(achar.getSolubility()
.getSolvent())) {
ActionMessage msg = new ActionMessage(
"achar.enzymeInduction.enzyme.invalid");
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
saveErrors(request, msgs);
status = false;
}
}
return status;
}
private Boolean validateInputs(HttpServletRequest request,
CharacterizationBean achar) {
if (!validateCharacterization(request, achar)) {
return false;
}
return true;
}
private boolean validateEmptyFinding(HttpServletRequest request,
FindingBean finding) {
if (finding.getFiles().isEmpty()
&& finding.getColumnHeaders().isEmpty()) {
ActionMessages msgs = new ActionMessages();
ActionMessage msg = new ActionMessage(
"achar.theFinding.emptyFinding");
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
saveErrors(request, msgs);
return false;
} else {
return true;
}
}
/**
* Copy "isSoluble" property from achar to Solubility entity.
*
* @param achar
*/
private void copyIsSoluble(CharacterizationBean achar) {
Boolean soluble = null;
String isSoluble = achar.getIsSoluble();
if (!StringUtils.isEmpty(isSoluble)) {
soluble = Boolean.valueOf(isSoluble);
}
if ("Solubility".equals(achar.getClassName())) {
achar.getSolubility().setIsSoluble(soluble);
}
}
/**
* Setup "isSoluble" property in achar from Solubility entity.
*
* @param achar
*/
private void setupIsSoluble(CharacterizationBean achar) {
Boolean soluble = null;
if ("Solubility".equals(achar.getClassName())) {
soluble = achar.getSolubility().getIsSoluble();
}
if (soluble == null) {
achar.setIsSoluble(null);
} else {
achar.setIsSoluble(soluble.toString());
}
}
public Boolean canUserExecutePrivateDispatch(UserBean user)
throws SecurityException {
if (user == null) {
return false;
}
return true;
}
private CharacterizationService setServicesInSession(
HttpServletRequest request) throws Exception {
SecurityService securityService = super
.getSecurityServiceFromSession(request);
CharacterizationService charService = new CharacterizationServiceLocalImpl(
securityService);
request.getSession().setAttribute("characterizationService",
charService);
ProtocolService protocolService = new ProtocolServiceLocalImpl(
securityService);
request.getSession().setAttribute("protocolService", protocolService);
SampleService sampleService = new SampleServiceLocalImpl(
securityService);
request.getSession().setAttribute("sampleService", sampleService);
return charService;
}
public ActionForward download(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
CharacterizationService service = setServicesInSession(request);
return downloadFile(service, mapping, form, request, response);
}
}
|
package joliex.io;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Pattern;
import javax.activation.FileTypeMap;
import javax.activation.MimetypesFileTypeMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import jolie.jap.JapURLConnection;
import jolie.runtime.AndJarDeps;
import jolie.runtime.ByteArray;
import jolie.runtime.FaultException;
import jolie.runtime.JavaService;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import jolie.runtime.embedding.RequestResponse;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
*
* @author Fabrizio Montesi
*/
@AndJarDeps({"jolie-xml.jar"})
public class FileService extends JavaService
{
private final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
private final TransformerFactory transformerFactory = TransformerFactory.newInstance();
private FileTypeMap fileTypeMap = FileTypeMap.getDefaultFileTypeMap();
public FileService()
{
super();
documentBuilderFactory.setIgnoringElementContentWhitespace( true );
}
public void setMimeTypeFile( String filename )
throws FaultException
{
try {
fileTypeMap = new MimetypesFileTypeMap( filename );
} catch( IOException e ) {
throw new FaultException( "IOException", e );
}
}
private static void readBase64IntoValue( InputStream istream, long size, Value value )
throws IOException
{
byte[] buffer = new byte[ (int)size ];
istream.read( buffer );
istream.close();
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
value.setValue( encoder.encode( buffer ) );
}
private static void readBinaryIntoValue( InputStream istream, long size, Value value )
throws IOException
{
byte[] buffer = new byte[ (int)size ];
istream.read( buffer );
istream.close();
value.setValue( new ByteArray( buffer ) );
}
private void readXMLIntoValue( InputStream istream, Value value )
throws IOException
{
try {
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
InputSource src = new InputSource( new InputStreamReader( istream ) );
Document doc = builder.parse( src );
value = value.getFirstChild( doc.getDocumentElement().getNodeName() );
jolie.xml.XmlUtils.documentToValue( doc, value );
} catch( ParserConfigurationException e ) {
throw new IOException( e );
} catch( SAXException e ) {
throw new IOException( e );
}
}
private static void readTextIntoValue( InputStream istream, long size, Value value )
throws IOException
{
byte[] buffer = new byte[ (int)size ];
istream.read( buffer );
istream.close();
value.setValue( new String( buffer ) );
/*String separator = System.getProperty( "line.separator" );
StringBuffer buffer = new StringBuffer();
String line;
BufferedReader reader = new BufferedReader( new InputStreamReader( istream ) );
while( (line=reader.readLine()) != null ) {
buffer.append( line );
buffer.append( separator );
}
reader.close();
value.setValue( buffer.toString() );*/
}
public Value readFile( Value request )
throws FaultException
{
Value filenameValue = request.getFirstChild( "filename" );
Value retValue = Value.create();
String format = request.getFirstChild( "format" ).strValue();
File file = new File( filenameValue.strValue() );
InputStream istream = null;
long size;
try {
if ( file.exists() ) {
istream = new FileInputStream( file );
size = file.length();
} else {
URL fileURL = interpreter().getClassLoader().findResource( filenameValue.strValue() );
if ( fileURL != null && fileURL.getProtocol().equals( "jap" ) ) {
URLConnection conn = fileURL.openConnection();
if ( conn instanceof JapURLConnection ) {
JapURLConnection jarConn = (JapURLConnection)conn;
size = jarConn.getEntrySize();
if ( size < 0 ) {
throw new IOException( "File dimension is negative for file " + fileURL.toString() );
}
istream = jarConn.getInputStream();
} else {
throw new FileNotFoundException( filenameValue.strValue() );
}
} else {
throw new FileNotFoundException( filenameValue.strValue() );
}
}
istream = new BufferedInputStream( istream );
try {
if ( "base64".equals( format ) ) {
readBase64IntoValue( istream, size, retValue );
} else if ( "binary".equals( format ) ) {
readBinaryIntoValue( istream, size, retValue );
} else if ( "xml".equals( format ) ) {
readXMLIntoValue( istream, retValue );
} else {
readTextIntoValue( istream, size, retValue );
}
} finally {
istream.close();
}
} catch( FileNotFoundException e ) {
throw new FaultException( "FileNotFound" );
} catch( IOException e ) {
throw new FaultException( "IOException", e );
}
return retValue;
}
public String getMimeType( String filename )
throws FaultException
{
File file = new File( filename );
if ( file.exists() == false ) {
throw new FaultException( "FileNotFound" );
}
return fileTypeMap.getContentType( file );
}
public String getServiceDirectory()
{
String dir = null;
try {
dir = interpreter().programDirectory().getCanonicalPath();
} catch( IOException e ) {
e.printStackTrace();
}
if ( dir == null || dir.isEmpty() ) {
dir = ".";
}
return dir;
}
public String getFileSeparator()
{
return jolie.lang.Constants.fileSeparator;
}
private void writeXML( File file, Value value, boolean append )
throws IOException
{
if ( value.children().isEmpty() ) {
return; // TODO: perhaps we should erase the content of the file before returning.
}
try {
Document doc = documentBuilderFactory.newDocumentBuilder().newDocument();
String rootName = value.children().keySet().iterator().next();
jolie.xml.XmlUtils.valueToDocument(
value.getFirstChild( rootName ),
rootName,
doc
);
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
Writer writer = new FileWriter( file, append );
StreamResult result = new StreamResult( writer );
transformer.transform( new DOMSource( doc ), result );
} catch( ParserConfigurationException e ) {
throw new IOException( e );
} catch( TransformerConfigurationException e ) {
throw new IOException( e );
} catch( TransformerException e ) {
throw new IOException( e );
}
}
private static void writeBinary( File file, Value value, boolean append )
throws IOException
{
FileOutputStream os = new FileOutputStream( file, append );
os.write( value.byteArrayValue().getBytes() );
os.flush();
os.close();
}
private static void writeText( File file, Value value, boolean append )
throws IOException
{
FileWriter writer = new FileWriter( file, append );
writer.write( value.strValue() );
writer.flush();
writer.close();
}
@RequestResponse
public void writeFile( Value request )
throws FaultException
{
boolean append = false;
Value content = request.getFirstChild( "content" );
String format = request.getFirstChild( "format" ).strValue();
File file = new File( request.getFirstChild( "filename" ).strValue() );
if ( request.getFirstChild( "append" ).intValue() > 0 ) {
append = true;
}
try {
if ( "text".equals( format ) ) {
writeText( file, content, append );
} else if ( "binary".equals( format ) ) {
writeBinary( file, content, append );
} else if ( "xml".equals( format ) ) {
writeXML( file, content, append );
} else if ( format.isEmpty() ) {
if ( content.isByteArray() ) {
writeBinary( file, content, append );
} else {
writeText( file, content, append );
}
}
} catch( IOException e ) {
throw new FaultException( "IOException", e );
}
}
public Boolean delete( Value request )
{
String filename = request.strValue();
boolean isRegex = request.getFirstChild( "isRegex" ).intValue() > 0;
boolean ret = true;
if ( isRegex ) {
File dir = new File( filename ).getAbsoluteFile().getParentFile();
String[] files = dir.list( new ListFilter( filename ) );
if ( files != null ) {
for( String file : files ) {
new File( file ).delete();
}
}
} else {
if ( new File( filename ).delete() == false ) {
ret = false;
}
}
return ret;
}
@RequestResponse
public void rename( Value request )
throws FaultException
{
String filename = request.getFirstChild( "filename" ).strValue();
String toFilename = request.getFirstChild( "to" ).strValue();
if ( new File( filename ).renameTo( new File( toFilename ) ) == false ) {
throw new FaultException( "IOException" );
}
}
public Value list( Value request )
{
File dir = new File( request.getFirstChild( "directory" ).strValue() );
String[] files = dir.list( new ListFilter( request.getFirstChild( "regex" ).strValue() ) );
Value response = Value.create();
if ( files != null ) {
ValueVector results = response.getChildren( "result" );
for( String file : files ) {
results.add( Value.create( file ) );
}
}
return response;
}
private static class ListFilter implements FilenameFilter
{
final private Pattern pattern;
public ListFilter( String regex )
{
this.pattern = Pattern.compile( regex );
}
public boolean accept( File file, String name )
{
return pattern.matcher( name ).matches();
}
}
}
|
package datastructs;
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayListIpod {
public static ArrayList<String> songs = new ArrayList<String>();
public static ArrayList<String> artists = new ArrayList<String>();
public static ArrayList<String> myplaylistsongs = new ArrayList<String>();
public static ArrayList<String> myplaylistartists = new ArrayList<String>();
//The four public arrays that will hold the songs, the artists of those songs, and the users playlist
public static int y = 10; //Used to recognize how many songs the user has
public static int z = 0; //Used to recognize how many songs are in the users playlist
public static void main(String[] args) {
songs.add("Meow"); artists.add("Meow");
songs.add("dfg"); artists.add("ghghg");
songs.add("gfgggg"); artists.add("ghghgh");
songs.add("gggg"); artists.add("hghgh");
songs.add("gggg"); artists.add("ssssss");
songs.add("fdfg"); artists.add("hghgh");
songs.add("dfhjjj"); artists.add("ghghk");
songs.add("drt"); artists.add("kkkk");
songs.add("dfg"); artists.add("uukf");
songs.add("hgfhf"); artists.add("fghfgh");
//The ten songs and their artists
Scanner in = new Scanner(System.in);
int choice, removal, addition; //Used to store the user's choice, what songs they want to remove, and what songs they want to add to their playlist
String songchoice, artistchoice;//Used to store what songs the user what like to add to the list
System.out.format("Hello! This is your music center. Below the currently available songs for playback are listed.");
PrintSongs();
//Runs the method that prints all of the users songs
do{
System.out.format("%n %nWhat would you like to do?"
+ "%n1. Add a new song"
+ "%n2. Delete a song"
+ "%n3. Add a song to your playlist"
+ "%n4. Exit%n %n");
choice = in.nextInt();
if(choice == 1){
//If the user chose to add a song
System.out.format("%nPlease enter the name of the song you would like to add: ");
in.nextLine();
songchoice = in.nextLine();
System.out.format("%nPlease enter the name of the artist of the song you just entered: ");
artistchoice = in.nextLine();
System.out.format("%nThe updated song list is available below:%n");
songs.add(songchoice); artists.add(artistchoice);
//adds the song and it's artist to the list of songs
y++;
//Increases the recognized amount of songs on the list
PrintSongs();
//Re-lists the songs on the list
}else if(choice == 2){
//If the user chose to remove a song from their list
System.out.format("Please enter the number next to the song you would like to delete: ");
removal = in.nextInt();
songs.remove(removal-1); //Removes the selected song and decreases the recognized amount of songs on the list
artists.remove(removal-1);
y
System.out.format("%nThe updated song list is available below:%n");
PrintSongs();
//Re-lists the songs on the list
}else if(choice == 3){
//If the user chose to add a song to their playlist
System.out.format("Please enter the number next to the song you would like to add to your playlist: ");
addition = in.nextInt();
myplaylistsongs.add(songs.get(addition-1)); //Adds the song and it's artist to the playlist and increases the song count by one
myplaylistartists.add(artists.get(addition-1));
z++;
System.out.format("%nYour updated playlist list is available below:%n");
PrintPlaylist();
//Re-lists the songs on the list
}else if(choice == 4) //If the user chose to exit
break;
}while(true);
//Until the user exits
System.out.format("Goodbye!");
in.close();
}//End main
public static void PrintSongs(){
//The method that is used to prints all of the songs the user has
System.out.format("%nSong List:%n %n Song Artist%n
for(int x = 0; x < y; x++){
//Uses y to determine how many songs to print
System.out.format("%n%d. %-10s %s", (x+1), songs.get(x), artists.get(x));
}
}//End PrintSongs
public static void PrintPlaylist(){
//The method used to list all of the songs in the user's playlist
System.out.format("%nSong List:%n %n Song Artist%n
for(int x = 0; x < z; x++){
//Uses z to determine how many songs to prnt
System.out.format("%n%d. %-10s %s", (x+1), myplaylistsongs.get(x), myplaylistartists.get(x));
}
}//End PrintPlayList
}
|
package ca.corefacility.bioinformatics.irida.ria.web.cart;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import ca.corefacility.bioinformatics.irida.model.project.Project;
import ca.corefacility.bioinformatics.irida.model.sample.Sample;
import ca.corefacility.bioinformatics.irida.ria.config.GalaxySessionInterceptor;
import ca.corefacility.bioinformatics.irida.ria.web.cart.dto.GalaxyExportSample;
import ca.corefacility.bioinformatics.irida.ria.web.services.UICartService;
import ca.corefacility.bioinformatics.irida.service.sample.SampleService;
/**
* Controller to handle all ajax requests made to the cart that have to do with Galaxy.
*/
@RestController
@Scope("session")
@RequestMapping("/ajax/galaxy-export")
public class CartGalaxyController {
private final SampleService sampleService;
private final UICartService cartService;
@Autowired
public CartGalaxyController(SampleService sampleService, UICartService cartService) {
this.sampleService = sampleService;
this.cartService = cartService;
}
/**
* Get a list of links for all {@link Sample} to be exported to the Galaxy Client.
* @return {@link List} of {@link Sample} links.
*/
@RequestMapping("/samples")
public List<GalaxyExportSample> getGalaxyExportForm() {
Map<Project, List<Sample>> contents = cartService.getFullCart();
return contents.entrySet().stream().map(entry -> entry.getValue().stream().map(sample -> new GalaxyExportSample(sample, entry.getKey().getId()))).flatMap(
Stream::distinct).collect(Collectors.toList());
}
/**
* Remove the Galaxy attributes from the session.
*
* @param request - the current {@link HttpServletRequest}
*/
@RequestMapping("remove")
public void removeGalaxySession(HttpServletRequest request) {
HttpSession session = request.getSession();
session.removeAttribute(GalaxySessionInterceptor.GALAXY_CALLBACK_URL);
session.removeAttribute(GalaxySessionInterceptor.GALAXY_CLIENT_ID);
}
}
|
package ca.corefacility.bioinformatics.irida.service;
import ca.corefacility.bioinformatics.irida.model.IridaClientDetails;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.NoSuchClientException;
/**
* Service for storing and reading {@link IridaClientDetails} objects
*
*
*/
public interface IridaClientDetailsService extends ClientDetailsService, CRUDService<Long, IridaClientDetails> {
/**
* {@inheritDoc}
*/
public ClientDetails loadClientByClientId(String clientId) throws NoSuchClientException;
/**
* Get the number of tokens issued for a given {@link IridaClientDetails}
*
* @param client
* Client to count tokens for
* @return Number of tokens issued for the given client
*/
public int countTokensForClient(IridaClientDetails client);
/**
* Revoke all OAuth2 tokens for a given {@link IridaClientDetails}
*
* @param client
* The client to revoke tokens for
*/
public void revokeTokensForClient(IridaClientDetails client);
/**
* Get the number of all tokens defined for a given
* {@link IridaClientDetails} that are valid and not expired.
*
* @param client
* the {@link IridaClientDetails} to get tokens for
* @return number of tokens defined for the client.
*/
public int countActiveTokensForClient(IridaClientDetails client);
}
|
package com.yahoo.sketches.hive.tuple;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.BytesWritable;
import com.yahoo.memory.Memory;
import com.yahoo.sketches.quantiles.DoublesSketch;
import com.yahoo.sketches.quantiles.DoublesSketchBuilder;
import com.yahoo.sketches.quantiles.UpdateDoublesSketch;
import com.yahoo.sketches.tuple.ArrayOfDoublesSketch;
import com.yahoo.sketches.tuple.ArrayOfDoublesSketchIterator;
import com.yahoo.sketches.tuple.ArrayOfDoublesSketches;
@Description(
name = "ArrayOfDoublesSketchToQuantilesSketch",
value = "_FUNC_(sketch, column, k)",
extended = "Returns a quanitles DoublesSketch constructed from a given"
+ " column of double values from a given ArrayOfDoublesSketch using parameter k"
+ " that determines the accuracy and size of the quantiles sketch."
+ " The column number is optional (the default is 1)."
+ " The parameter k is optional (the default is defined in the sketch library)."
+ " The result is a serialized quantiles sketch.")
public class ArrayOfDoublesSketchToQuantilesSketchUDF extends UDF {
/**
* Convert the first column from a given ArrayOfDoublesSketch to a quantiles DoublesSketch
* using the default parameter k.
* @param serializedSketch ArrayOfDoublesSketch in as serialized binary
* @return serialized DoublesSketch
*/
public BytesWritable evaluate(final BytesWritable serializedSketch) {
return evaluate(serializedSketch, 1, 0);
}
/**
* Convert a given column from a given ArrayOfDoublesSketch to a quantiles DoublesSketch
* using the default parameter k.
* @param serializedSketch ArrayOfDoublesSketch in as serialized binary
* @param column 1-based column number
* @return serialized DoublesSketch
*/
public BytesWritable evaluate(final BytesWritable serializedSketch, final int column) {
return evaluate(serializedSketch, column, 0);
}
/**
* Convert a given column from a given ArrayOfDoublesSketch to a quantiles DoublesSketch
* @param serializedSketch ArrayOfDoublesSketch in as serialized binary
* @param column 1-based column number
* @param k parameter that determines the accuracy and size of the quantiles sketch
* @return serialized DoublesSketch
*/
public BytesWritable evaluate(final BytesWritable serializedSketch, final int column,
final int k) {
if (serializedSketch == null) { return null; }
final ArrayOfDoublesSketch sketch = ArrayOfDoublesSketches.wrapSketch(
Memory.wrap(serializedSketch.getBytes()));
if (column < 1) {
throw new IllegalArgumentException("Column number must be greater than zero. Received: "
+ column);
}
if (column > sketch.getNumValues()) {
throw new IllegalArgumentException("Column number " + column
+ " is out of range. The given sketch has "
+ sketch.getNumValues() + " columns");
}
final DoublesSketchBuilder builder = DoublesSketch.builder();
if (k > 0) {
builder.setK(k);
}
final UpdateDoublesSketch qs = builder.build();
final ArrayOfDoublesSketchIterator it = sketch.iterator();
while (it.next()) {
qs.update(it.getValues()[column - 1]);
}
return new BytesWritable(qs.compact().toByteArray());
}
}
|
package de.hs.mannheim.modUro.controller.overview;
import de.hs.mannheim.modUro.model.MetricType;
import de.hs.mannheim.modUro.model.Simulation;
import de.hs.mannheim.modUro.model.overview.SimulationOverview;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
* SimulationOverviewController controls SimulationOverviewView.
* @author Mathuraa Pathmanathan (mathuraa@hotmail.de)
*/
public class SimulationOverviewController {
//Reference to ProjectOverview
private SimulationOverview simulationOverview;
@FXML
private Label simulationID;
@FXML
private Label simulationName;
@FXML
private Label simulationModel;
@FXML
private Label isCompleted;
@FXML
private Label isAborted;
@FXML
private Label isInSteadyState;
@FXML
private Label starttime;
@FXML
private Label duration;
@FXML
private Hyperlink directoryHyperlink;
@FXML
private Label metricType;
@FXML
private TableView tableContent;
@FXML
private ImageView firstImage;
@FXML
private ImageView secondImage;
@FXML
private ImageView thirdImage;
private ObservableList<MetricType> metricData;
public void init(Simulation simulation){
this.simulationOverview = new SimulationOverview(simulation);
metricData = FXCollections.observableArrayList(simulationOverview.getMetricTypes());
setLabel();
setImage();
createTableContent();
}
/**
* Sets Simulation Details to Label
*/
private void setLabel() {
this.simulationID.setText(String.valueOf(simulationOverview.getSimulationID()));
this.simulationName.setText(String.valueOf(simulationOverview.getSimulationName()));
this.simulationModel.setText(simulationOverview.getModelType());
this.isCompleted.setText(String.valueOf(simulationOverview.isCompleted()));
this.isAborted.setText(String.valueOf(simulationOverview.isAborted()));
this.isInSteadyState.setText(String.valueOf(simulationOverview.isInSteadyState()));
this.starttime.setText(simulationOverview.getStartTime().toString());
this.duration.setText(String.valueOf(simulationOverview.getDuration()));
this.directoryHyperlink.setText(simulationOverview.getDirectory().getAbsolutePath());
this.metricType.setText(String.valueOf(simulationOverview.getMetricTypesName()));
}
private void setImage() {
List<File> imageFiles = simulationOverview.getImages();
if(imageFiles.size() != 0) {
Image image = new Image(imageFiles.get(0).toURI().toString());
firstImage.setImage(image);
Image image2 = new Image(imageFiles.get(1).toURI().toString());
secondImage.setImage(image2);
Image image3 = new Image(imageFiles.get(2).toURI().toString());
thirdImage.setImage(image3);
}
}
/**
* Creates table content.
*/
private void createTableContent() {
TableColumn column1 = new TableColumn("MetricType");
column1.setCellValueFactory(new PropertyValueFactory<MetricType, String>("name"));
TableColumn column2 = new TableColumn("Mean");
column2.setCellValueFactory(new PropertyValueFactory<MetricType, Double>("mean"));
TableColumn column3 = new TableColumn("Standard Deviation");
column3.setCellValueFactory(new PropertyValueFactory<MetricType, Double>("deviation"));
tableContent.getColumns().setAll(column1, column2, column3);
tableContent.setItems(metricData);
}
/**
* Handel HyperlinkClicked Event.
* @param actionEvent
*/
public void handleHyperlinkOnlicked(ActionEvent actionEvent) {
Desktop desktop = Desktop.getDesktop();
File dirToOpen = null;
try {
dirToOpen = new File(directoryHyperlink.getText());
desktop.open(dirToOpen);
} catch (IllegalArgumentException iae) {
System.out.println("File Not Found");
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package net.davidvoid.thor.lightning.service.security;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.io.*;
import java.util.Date;
import java.util.Map;
import net.davidvoid.thor.lightning.entity.Entity;
import net.davidvoid.thor.lightning.entity.User;
import net.davidvoid.thor.lightning.exception.AuthenticationException;
import net.davidvoid.thor.lightning.util.MapLiteral;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
@Component
public class JwtAuthenticationService {
static Log logger = LogFactory.getLog(JwtAuthenticationService.class);
static long EXPIRATION_TIME = 30L * 24L * 60L * 60L * 1000L;
String secretKey = null;
public JwtAuthenticationService() {
ClassLoader loader = this.getClass().getClassLoader();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(loader.getResourceAsStream("config/key.hmac")))) {
secretKey = reader.readLine();
} catch (IOException e) {
logger.fatal("unable to read HMAC key");
}
}
public Authentication authenticate(String jwtToken) {
try {
Jws<Claims> claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwtToken);
String username = claims.getBody().getSubject();
if (username == null) throw new AuthenticationException("no subject field present");
Date issuedDate = claims.getBody().getIssuedAt();
if (issuedDate == claims) throw new AuthenticationException("no issued at field present");
Date current = new Date();
long offset = current.getTime() - issuedDate.getTime();
if (offset < 0 || offset > EXPIRATION_TIME) throw new AuthenticationException("token expired");
Object uid_obj = claims.getBody().get("uid");
if (uid_obj == null || !Entity.is_valid_id(uid_obj)) throw new AuthenticationException("no uid field present");
return new ThorAuthentication(username, uid_obj);
} catch (JwtException e) {
throw new AuthenticationException("invalid JWT token", e);
}
}
public String getToken(User user) {
Map<String, Object> additional_claims = MapLiteral.map("uid", user.getId());
return Jwts.builder().setClaims(additional_claims).setSubject(user.getName()).setIssuedAt(new Date())
.signWith(SignatureAlgorithm.HS512, secretKey).compact();
}
}
|
package org.sitenv.service.ccda.smartscorecard.controller;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.io.IOUtils;
import org.jsoup.Jsoup;
import org.sitenv.ccdaparsing.model.CCDAXmlSnippet;
import org.sitenv.service.ccda.smartscorecard.model.CCDAScoreCardRubrics;
import org.sitenv.service.ccda.smartscorecard.model.Category;
import org.sitenv.service.ccda.smartscorecard.model.ReferenceError;
import org.sitenv.service.ccda.smartscorecard.model.ReferenceResult;
import org.sitenv.service.ccda.smartscorecard.model.ReferenceTypes.ReferenceInstanceType;
import org.sitenv.service.ccda.smartscorecard.model.ResponseTO;
import org.sitenv.service.ccda.smartscorecard.model.Results;
import org.sitenv.service.ccda.smartscorecard.util.ApplicationConstants;
import org.sitenv.service.ccda.smartscorecard.util.ApplicationUtil;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextRenderer;
import org.xml.sax.SAXException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lowagie.text.DocumentException;
@RestController
public class SaveReportController {
public static final String SAVE_REPORT_CHARSET_NAME = "UTF8";
private static final int CONFORMANCE_ERROR_INDEX = 0;
private static final int CERTIFICATION_FEEDBACK_INDEX = 1;
/**
* Converts received JSON to a ResponseTO POJO (via method signature
* automagically), converts the ResponseTO to a cleaned (parsable) HTML
* report including relevant data, converts the HTML to a PDF report, and,
* finally, streams the data for consumption.
* This is intended to be called from a frontend which has already collected the JSON results.
*
* @param jsonReportData
* JSON which resembles ResponseTO
* @param response
* used to stream the PDF
*/
@RequestMapping(value = "/savescorecardservice", method = RequestMethod.POST)
public void savescorecardservice(@RequestBody ResponseTO jsonReportData,
HttpServletResponse response) {
convertHTMLToPDFAndStreamToOutput(
ensureLogicalParseTreeInHTML(convertReportToHTML(jsonReportData, SaveReportType.MATCH_UI)),
response);
}
/**
* A single service to handle a pure back-end implementation of the
* scorecard which streams back a PDF report.
* This does not require the completed JSON up-front, it creates it from the file sent.
*
* @param ccdaFile
* The C-CDA XML file intended to be scored
*/
@RequestMapping(value = "/savescorecardservicebackend", method = RequestMethod.POST)
public void savescorecardservicebackend(
@RequestParam("ccdaFile") MultipartFile ccdaFile,
HttpServletResponse response) {
handlePureBackendCall(ccdaFile, response, SaveReportType.MATCH_UI);
}
/**
* A single service to handle a pure back-end implementation of the
* scorecard which streams back a PDF report.
* This does not require the completed JSON up-front, it creates it from the file sent.
* This differs from the savescorecardservicebackend in that it has its own specific format of the results
* (dynamic and static table with 'call outs', no filename, more overview type content, etc.)
* and is intended to be used when a Direct Message is received with a C-CDA document.
*
* @param ccdaFile
* The C-CDA XML file intended to be scored
* @param sender
* The email address of the sender to be logged in the report
*/
@RequestMapping(value = "/savescorecardservicebackendsummary", method = RequestMethod.POST)
public void savescorecardservicebackendsummary(
@RequestParam("ccdaFile") MultipartFile ccdaFile, @RequestParam("sender") String sender,
HttpServletResponse response) {
if(ApplicationUtil.isEmpty(sender)) {
sender = "Unknown Sender";
}
handlePureBackendCall(ccdaFile, response, SaveReportType.SUMMARY, sender);
}
private static void handlePureBackendCall(MultipartFile ccdaFile, HttpServletResponse response, SaveReportType reportType) {
handlePureBackendCall(ccdaFile, response, reportType, null);
}
private static void handlePureBackendCall(MultipartFile ccdaFile, HttpServletResponse response, SaveReportType reportType,
String sender) {
ResponseTO pojoResponse = callCcdascorecardservice(ccdaFile);
if (pojoResponse == null) {
pojoResponse = new ResponseTO();
pojoResponse.setResults(null);
pojoResponse.setSuccess(false);
pojoResponse
.setErrorMessage(ApplicationConstants.ErrorMessages.NULL_RESULT_ON_SAVESCORECARDSERVICEBACKEND_CALL);
} else {
if (!ApplicationUtil.isEmpty(ccdaFile.getOriginalFilename())
&& ccdaFile.getOriginalFilename().contains(".")) {
pojoResponse.setFilename(ccdaFile.getOriginalFilename());
} else if (!ApplicationUtil.isEmpty(ccdaFile.getName())
&& ccdaFile.getName().contains(".")) {
pojoResponse.setFilename(ccdaFile.getName());
}
if(ApplicationUtil.isEmpty(pojoResponse.getFilename())) {
pojoResponse.setFilename("Unknown");
}
// otherwise it uses the name given by ccdascorecardservice
}
if(reportType == SaveReportType.SUMMARY) {
pojoResponse.setFilename(sender);
}
convertHTMLToPDFAndStreamToOutput(
ensureLogicalParseTreeInHTML(convertReportToHTML(pojoResponse, reportType)),
response);
};
protected static ResponseTO callCcdascorecardservice(MultipartFile ccdaFile) {
ResponseTO pojoResponse = null;
LinkedMultiValueMap<String, Object> requestMap = new LinkedMultiValueMap<>();
FileOutputStream out = null;
File tempFile = null;
try {
final String tempCcdaFileName = "ccdaFile";
tempFile = File.createTempFile(tempCcdaFileName, "xml");
out = new FileOutputStream(tempFile);
IOUtils.copy(ccdaFile.getInputStream(), out);
requestMap.add(tempCcdaFileName, new FileSystemResource(tempFile));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(
requestMap, headers);
FormHttpMessageConverter formConverter = new FormHttpMessageConverter();
formConverter.setCharset(Charset.forName(SAVE_REPORT_CHARSET_NAME));
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(formConverter);
restTemplate.getMessageConverters().add(
new MappingJackson2HttpMessageConverter());
pojoResponse = restTemplate.postForObject(
ApplicationConstants.CCDASCORECARDSERVICE_URL,
requestEntity, ResponseTO.class);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
if (tempFile != null && tempFile.isFile()) {
tempFile.delete();
}
}
return pojoResponse;
}
/**
* Parses (POJO ResponseTO converted) JSON and builds the results into an
* HTML report
*
* @param report
* the ResponseTO report intended to be converted to HTML
* @return the converted HTML report as a String
*/
protected static String convertReportToHTML(ResponseTO report, SaveReportType reportType) {
StringBuffer sb = new StringBuffer();
appendOpeningHtml(sb);
if (report == null) {
report = new ResponseTO();
report.setResults(null);
report.setSuccess(false);
report.setErrorMessage(ApplicationConstants.ErrorMessages.GENERIC_WITH_CONTACT);
appendErrorMessageFromReport(sb, report,
ApplicationConstants.ErrorMessages.RESULTS_ARE_NULL);
} else {
// report != null
if (report.getResults() != null) {
if (report.isSuccess()) {
Results results = report.getResults();
List<Category> categories = results.getCategoryList();
List<ReferenceResult> referenceResults = report
.getReferenceResults();
appendHeader(sb, report, results, reportType);
appendHorizontalRuleWithBreaks(sb);
if(reportType == SaveReportType.SUMMARY) {
appendPreTopLevelResultsContent(sb);
}
appendTopLevelResults(sb, results, categories,
referenceResults, reportType, report.getCcdaDocumentType());
if(reportType == SaveReportType.MATCH_UI) {
appendHorizontalRuleWithBreaks(sb);
appendHeatmap(sb, results, categories,
referenceResults);
}
sb.append("<br />");
appendHorizontalRuleWithBreaks(sb);
if(reportType == SaveReportType.MATCH_UI) appendDetailedResults(sb, categories, referenceResults);
if(reportType == SaveReportType.SUMMARY) appendPictorialGuide(sb, categories, referenceResults);
}
} else {
// report.getResults() == null
if (!report.isSuccess()) {
appendErrorMessageFromReport(sb, report,
ApplicationConstants.ErrorMessages.IS_SUCCESS_FALSE);
} else {
appendErrorMessageFromReport(sb, report);
}
}
}
appendClosingHtml(sb);
return sb.toString();
}
private static void appendOpeningHtml(StringBuffer sb) {
sb.append("<!DOCTYPE html>");
sb.append("<html>");
sb.append("<head>");
sb.append("<title>SITE C-CDA Scorecard Report</title>");
appendStyleSheet(sb);
sb.append("</head>");
sb.append("<body style='font-family: \"Helvetica Neue\",Helvetica,Arial,sans-serif;'>");
}
private static void appendStyleSheet(StringBuffer sb) {
sb.append("<style>")
.append(System.lineSeparator())
.append(".site-header {")
.append(" background: url(\"https://sitenv.org/assets/images/site/bg-header-1920x170.png\")")
.append(" repeat-x center top #1fdbfe;")
.append("}")
.append(System.lineSeparator())
.append(".site-logo {")
.append(" text-decoration: none;")
.append("}")
.append(System.lineSeparator())
.append("table {")
.append(" font-family: arial, sans-serif;")
.append(" border-collapse: separate;")
.append(" width: 100%;")
.append("}")
.append(System.lineSeparator())
.append("td, th {")
.append(" border: 1px solid #dddddd;")
.append(" text-align: left;")
.append(" padding: 8px;")
.append("}")
.append(System.lineSeparator())
.append("#dynamicTable {")
.append(" border-collapse: collapse;")
.append("}")
.append(System.lineSeparator())
.append("#dynamicTable tr:nth-child(even) {")
.append(" background-color: #dddddd;")
.append("}")
.append(System.lineSeparator())
.append("#staticTable {")
.append(" font-size: 11px;")
.append("}")
.append(System.lineSeparator())
.append(".removeBorder {")
.append(" border: none;")
.append("}")
.append(System.lineSeparator())
.append("#sectionPopOutLink {")
.append(" border-top: 6px double MEDIUMPURPLE;")
.append(" border-bottom: none;")
.append(" border-left: none;")
.append(" border-right: none;")
.append("}")
.append("#gradePopOutLink {")
.append(" border-left: 6px solid MEDIUMSEAGREEN;")
.append(" border-right: none;")
.append(" border-bottom: none;")
.append(" border-top: none; ")
.append("}")
.append("#issuePopOutLink {")
.append(" border-left: 6px double orange;")
.append(" border-right: 6px double orange;")
.append(" border-bottom: none;")
.append(" border-top: none; ")
.append("}")
.append("#errorPopOutLink {")
.append(" border-right: 6px solid red;")
.append(" border-left: none;")
.append(" border-bottom: none;")
.append(" border-top: none; ")
.append("}")
.append("#feedbackPopOutLink {")
.append(" border-top: 6px double DEEPSKYBLUE;")
.append(" border-bottom: none;")
.append(" border-left: none;")
.append(" border-right: none;")
.append("}")
.append(System.lineSeparator())
.append("#sectionPopOut {")
.append(" border: 6px double MEDIUMPURPLE;")
.append(" border-radius: 25px 0px 25px 25px;")
.append("}")
.append("#gradePopOut {")
.append(" border: 6px solid MEDIUMSEAGREEN;")
.append(" border-radius: 25px 25px 25px 25px;")
.append("}")
.append("#issuePopOut {")
.append(" border: 6px double orange;")
.append(" border-radius: 25px 25px 0px 0px;")
.append("}")
.append("#errorPopOut {")
.append(" border: 6px solid red;")
.append(" border-radius: 25px 25px 25px 25px;")
.append("}")
.append("#feedbackPopOut {")
.append(" border: 6px double DEEPSKYBLUE;")
.append(" border-radius: 0px 25px 25px 25px;")
.append("}")
.append(System.lineSeparator())
.append("#sectionHeader {")
.append(" border: 6px double MEDIUMPURPLE;")
.append("}")
.append("#gradeHeader {")
.append(" border: 6px solid MEDIUMSEAGREEN;")
.append("}")
.append("#issueHeader {")
.append(" border: 6px double orange;")
.append("}")
.append("#errorHeader {")
.append(" border: 6px solid red;")
.append("}")
.append("#feedbackHeader {")
.append(" border: 6px double DEEPSKYBLUE;")
.append("}")
.append("</style>");
}
private static void appendHeader(StringBuffer sb, ResponseTO report,
Results results, SaveReportType reportType) {
sb.append("<header id='topOfScorecard'>");
sb.append("<center>");
sb.append("<div class=\"site-header\">")
.append(" <a class=\"site-logo\" href=\"https:
.append(" rel=\"external\" title=\"HealthIT.gov\"> <img alt=\"HealthIT.gov\"")
.append(" src=\"https://sitenv.org/assets/images/site/healthit.gov.logo.png\" width='40%'>")
.append(" </a>")
.append("</div>");
sb.append("<br />");
appendHorizontalRuleWithBreaks(sb);
sb.append("<h1>" + "C-CDA ");
if(reportType == SaveReportType.SUMMARY) {
sb.append("Scorecard For "
+ (report.getCcdaDocumentType() != null ? report
.getCcdaDocumentType() : "document") + "</h1>");
sb.append("<h5>");
sb.append("<span style='float: left'>" + "Submitted By: "
+ (!ApplicationUtil.isEmpty(report.getFilename()) ? report.getFilename() : "Unknown")
+ "</span>");
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
sb.append("<span style='float: right'>" + "Submission Time: " + dateFormat.format(new Date()) + "</span>");
sb.append("</h5>");
sb.append("<div style='clear: both'></div>");
} else {
sb.append(results.getDocType() + " "
+ (report.getCcdaDocumentType() != null ? report .getCcdaDocumentType() : "document")
+ " Scorecard For:" + "</h1>");
sb.append("<h2>" + report.getFilename() + "</h2>");
}
sb.append("</center>");
sb.append("</header>");
}
private static void appendPreTopLevelResultsContent(StringBuffer sb) {
sb.append("<p>")
.append(" The C-CDA Scorecard enables providers, implementers, and health")
.append(" IT professionals with a tool that compares how artifacts (transition")
.append(" of care documents, care plans etc) created by your organization")
.append(" stack up against the HL7 C-CDA implementation guide and HL7 best")
.append(" practices. The C-CDA Scorecard promotes best practices in C-CDA")
.append(" implementation by assessing key aspects of the structured data found")
.append(" in individual documents. The Scorecard tool provides a rough")
.append(" quantitative assessment and highlights areas of improvement which")
.append(" can be made today to move the needle forward in interoperability of")
.append(" C-CDA documents. The ")
.append(" <a href=\"http:
+ "best practices and quantitative scoring criteria"
+ "</a>")
.append(" have been developed by HL7 through the HL7-ONC Cooperative agreement")
.append(" to improve the implementation of health care standards. We hope that")
.append(" providers and health IT developers will use the tool to identify and")
.append(" resolve issues around C-CDA document interoperability in their")
.append(" health IT systems.")
.append("<p>")
.append("<p>")
.append(" The report has two pages. The first page contains the summary")
.append(" of the C-CDA Scorecard results highlighting the overall document")
.append(" grade compared to the industry, a quantitative score out of a maximum")
.append(" of 100, and areas for improvement organized by clinical domains. The")
.append(" second page on the other hand contains a guide to help the providers")
.append(" interpret the scorecard results and take appropriate action.")
.append("</p>");
}
private static void appendTopLevelResults(StringBuffer sb, Results results,
List<Category> categories, List<ReferenceResult> referenceResults, SaveReportType reportType, String ccdaDocumentType) {
boolean isReferenceResultsEmpty = ApplicationUtil.isEmpty(referenceResults);
int conformanceErrorCount = isReferenceResultsEmpty ? 0 : referenceResults.get(CONFORMANCE_ERROR_INDEX).getTotalErrorCount();
int certificationFeedbackCount = isReferenceResultsEmpty ? 0 : referenceResults.get(CERTIFICATION_FEEDBACK_INDEX).getTotalErrorCount();
if(reportType == SaveReportType.SUMMARY) {
//brief summary of overall document results (without scorecard issues count listed)
sb.append("<p>"
+ "Your " + ccdaDocumentType + " document received a grade of <b>" + results.getFinalGrade() + "</b>"
+ " compared to an industry average of " + "<b>" + results.getIndustryAverageGrade() + "</b>" + ". "
+ "The document scored " + "<b>" + results.getFinalNumericalGrade() + "/100" + "</b>"
+ " and is "
+ (conformanceErrorCount > 0 ? "non-compliant" : "compliant")
+ " with the HL7 C-CDA IG"
+ " and is "
+ (certificationFeedbackCount > 0 ? "non-compliant" : "compliant")
+ " with 2015 Edition Certification requirements. "
+ "The detailed results organized by clinical domains are provided in the table below:"
+ "</p>");
//dynamic table
appendDynamicTopLevelResultsTable(sb, results, categories, referenceResults);
} else {
sb.append("<h3>Scorecard Grade: " + results.getFinalGrade() + "</h3>");
sb.append("<ul><li>");
sb.append("<p>Your document scored a " + "<b>"
+ results.getFinalGrade() + "</b>"
+ " compared to an industry average of " + "<b>"
+ results.getIndustryAverageGrade() + "</b>" + ".</p>");
sb.append("</ul></li>");
sb.append("<h3>Scorecard Score: " + results.getFinalNumericalGrade()
+ "</h3>");
sb.append("<ul><li>");
sb.append("<p>Your document scored " + "<b>"
+ +results.getFinalNumericalGrade() + "</b>" + " out of "
+ "<b>" + " 100 " + "</b>" + " total possible points.</p>");
sb.append("</ul></li>");
boolean isSingular = results.getNumberOfIssues() == 1;
appendSummaryRow(sb, results.getNumberOfIssues(), "Scorecard Issues",
null, isSingular ? "Scorecard Issue" : "Scorecard Issues",
isSingular);
sb.append("</ul></li>");
String messageSuffix = null;
if (isReferenceResultsEmpty) {
for (ReferenceInstanceType refType : ReferenceInstanceType.values()) {
if (refType == ReferenceInstanceType.CERTIFICATION_2015) {
messageSuffix = "results";
}
appendSummaryRow(sb, 0, refType.getTypePrettyName(),
messageSuffix, refType.getTypePrettyName(), false, reportType);
sb.append("</ul></li>");
}
} else {
for (ReferenceResult refResult : referenceResults) {
int refErrorCount = refResult.getTotalErrorCount();
isSingular = refErrorCount == 1;
String refTypeName = refResult.getType().getTypePrettyName();
String messageSubject = "";
if (refResult.getType() == ReferenceInstanceType.IG_CONFORMANCE) {
messageSubject = isSingular ? refTypeName.substring(0,
refTypeName.length() - 1) : refTypeName;
} else if (refResult.getType() == ReferenceInstanceType.CERTIFICATION_2015) {
messageSuffix = isSingular ? "result" : "results";
messageSubject = refTypeName;
}
appendSummaryRow(sb, refErrorCount, refTypeName, messageSuffix,
messageSubject, isSingular, reportType);
sb.append("</ul></li>");
}
}
}
}
private static int getFailingSectionSpecificErrorCount(String categoryName,
ReferenceInstanceType refType, List<ReferenceResult> referenceResults) {
if (!ApplicationUtil.isEmpty(referenceResults)) {
if (refType == ReferenceInstanceType.IG_CONFORMANCE) {
List<ReferenceError> igErrors =
referenceResults.get(CONFORMANCE_ERROR_INDEX).getReferenceErrors();
if (!ApplicationUtil.isEmpty(igErrors)) {
return getFailingSectionSpecificErrorCountProcessor(categoryName, igErrors);
}
} else if (refType == ReferenceInstanceType.CERTIFICATION_2015) {
List<ReferenceError> certErrors =
referenceResults.get(CERTIFICATION_FEEDBACK_INDEX).getReferenceErrors();
if (!ApplicationUtil.isEmpty(certErrors)) {
return getFailingSectionSpecificErrorCountProcessor(categoryName, certErrors);
}
}
}
return 0;
}
private static int getFailingSectionSpecificErrorCountProcessor(
String categoryName, List<ReferenceError> errors) {
int count = 0;
for (int i = 0; i < errors.size(); i++) {
String currentSectionInReferenceErrors = errors.get(i).getSectionName();
if (!ApplicationUtil.isEmpty(currentSectionInReferenceErrors)) {
if (currentSectionInReferenceErrors.equalsIgnoreCase(categoryName)) {
count++;
}
}
}
return count;
}
private static void appendDynamicTopLevelResultsTable(StringBuffer sb, Results results,
List<Category> categories, List<ReferenceResult> referenceResults) {
sb.append("<table id='dynamicTable'>")
.append(" <tr>")
.append(" <th>Clinical Domain</th>")
.append(" <th>Scorecard Grade</th>")
.append(" <th>Scorecard Issues</th>")
.append(" <th>Conformance Errors</th>")
.append(" <th>Certification Feedback</th>")
.append(" </tr>");
for(Category category : categories) {
// if(category.getNumberOfIssues() > 0 || referenceResults.get(ReferenceInstanceType.IG/CERT).getTotalErrorCount() > 0) {
if(category.getNumberOfIssues() > 0 || category.isFailingConformance() || category.isCertificationFeedback()) {
sb.append(" <tr>")
.append(" <td>" + (category.getCategoryName() != null ? category.getCategoryName() : "Unknown") + "</td>")
.append(" <td>" + (category.getCategoryGrade() != null ? category.getCategoryGrade() : "N/A") + "</td>")
.append(" <td>" + category.getNumberOfIssues() + "</td>")
.append(" <td>"
+ (!ApplicationUtil.isEmpty(category.getCategoryName())
? getFailingSectionSpecificErrorCount(category.getCategoryName(), ReferenceInstanceType.IG_CONFORMANCE, referenceResults)
: "N/A")
+ "</td>")
.append(" <td>"
+ (!ApplicationUtil.isEmpty(category.getCategoryName())
? getFailingSectionSpecificErrorCount(category.getCategoryName(), ReferenceInstanceType.CERTIFICATION_2015, referenceResults)
: "N/A")
+ "</td>")
.append(" </tr>");
}
}
sb.append("</table>");
}
private static void appendHeatmap(StringBuffer sb, Results results,
List<Category> categories, List<ReferenceResult> referenceResults) {
sb.append("<span id='heatMap'>" + "</span>");
for (Category curCategory : categories) {
sb.append("<h3>"
+ (curCategory.getNumberOfIssues() > 0
? "<a href='#" + curCategory.getCategoryName() + "-category" + "'>" : "")
+ curCategory.getCategoryName()
+ (curCategory.getNumberOfIssues() > 0
? "</a>" : "")
+ "</h3>");
sb.append("<ul>");
if (curCategory.getCategoryGrade() != null) {
sb.append("<li>" + "Section Grade: " + "<b>"
+ curCategory.getCategoryGrade() + "</b>" + "</li>"
+ "<li>" + "Number of Issues: " + "<b>"
+ curCategory.getNumberOfIssues() + "</b>" + "</li>");
} else {
sb.append("<li>"
+ "This category was not scored as it ");
if(curCategory.isNullFlavorNI()) {
sb.append("is an <b>empty section</b>");
}
boolean failingConformance = curCategory.isFailingConformance();
boolean failingCertification = curCategory.isCertificationFeedback();
if(failingConformance || failingCertification) {
if(failingConformance && failingCertification || failingConformance && !failingCertification) {
//we default to IG if true for both since IG is considered a more serious issue (same with the heatmap label, so we match that)
//there could be a duplicate for two reasons, right now, there's always at least one duplicate since we derive ig from cert in the backend
//in the future this might not be the case, but, there could be multiple section fails in the same section, so we have a default for those too
sb.append("contains <a href='#" + ReferenceInstanceType.IG_CONFORMANCE.getTypePrettyName()
+ "-category'" + ">" + "Conformance Errors" + "</a>");
} else if(failingCertification && !failingConformance) {
sb.append("contains <a href='#" + ReferenceInstanceType.CERTIFICATION_2015.getTypePrettyName()
+ "-category'" + ">" + "Certification Feedback" + "</a>");
}
}
sb.append("</li>");
}
sb.append("</ul></li>");
}
}
private static void appendSummaryRow(StringBuffer sb, int result,
String header, String messageSuffix, String messageSubject,
boolean isSingular) {
appendSummaryRow(sb, result, header, messageSuffix, messageSubject, isSingular, null);
}
private static void appendSummaryRow(StringBuffer sb, int result,
String header, String messageSuffix, String messageSubject,
boolean isSingular, SaveReportType reportType) {
if(reportType == null) {
reportType = SaveReportType.MATCH_UI;
}
sb.append("<h3>"
+ header
+ ": "
+ ("Scorecard Issues".equals(header) || result < 1 || reportType == SaveReportType.SUMMARY ? result
: ("<a href=\"#" + header + "-category\">" + result + "</a>"))
+ "</h3>");
sb.append("<ul><li>");
sb.append("<p>There " + (isSingular ? "is" : "are") + " " + "<b>"
+ result + "</b>" + " " + messageSubject
+ (messageSuffix != null ? " " + messageSuffix : "")
+ " in your document.</p>");
}
private static void appendDetailedResults(StringBuffer sb,
List<Category> categories, List<ReferenceResult> referenceResults) {
sb.append("<h2>" + "Detailed Results" + "</h2>");
if (!ApplicationUtil.isEmpty(referenceResults)) {
for (ReferenceResult curRefInstance : referenceResults) {
ReferenceInstanceType refType = curRefInstance.getType();
if (curRefInstance.getTotalErrorCount() > 0) {
String refTypeName = refType.getTypePrettyName();
sb.append("<h3 id=\"" + refTypeName + "-category\">"
+ refTypeName + "</h3>");
sb.append("<ul>"); // START curRefInstance ul
sb.append("<li>"
+ "Number of "
+ (refType == ReferenceInstanceType.CERTIFICATION_2015 ? "Results:"
: "Errors:") + " "
+ curRefInstance.getTotalErrorCount() + "</li>");
sb.append("<ol>"); // START reference errors ol
for (ReferenceError curRefError : curRefInstance
.getReferenceErrors()) {
sb.append("<li>"
+ (refType == ReferenceInstanceType.CERTIFICATION_2015 ? "Feedback:"
: "Error:") + " "
+ curRefError.getDescription() + "</li>");
sb.append("<ul>"); // START ul within the curRefError
if (!ApplicationUtil.isEmpty(curRefError
.getSectionName())) {
sb.append("<li>" + "Related Section: "
+ curRefError.getSectionName() + "</li>");
}
sb.append("<li>"
+ "Document Line Number (approximate): "
+ curRefError.getDocumentLineNumber() + "</li>");
sb.append("<li>"
+ "xPath: "
+ "<xmp style='font-family: Consolas, monaco, monospace;'>"
+ curRefError.getxPath() + "</xmp>" + "</li>");
sb.append("</ul>"); // END ul within the curRefError
}
}
sb.append("</ol>"); // END reference errors ol
sb.append("</ul>"); // END curRefInstance ul
appendBackToTopWithBreaks(sb);
} //END for (ReferenceResult curRefInstance : referenceResults)
}
for (Category curCategory : categories) {
if (curCategory.getNumberOfIssues() > 0) {
sb.append("<h3 id='" + curCategory.getCategoryName() + "-category"
+ "'>" + curCategory.getCategoryName() + "</h3>");
sb.append("<ul>"); // START curCategory ul
sb.append("<li>" + "Section Grade: "
+ curCategory.getCategoryGrade() + "</li>" + "<li>"
+ "Number of Issues: "
+ curCategory.getNumberOfIssues() + "</li>");
sb.append("<ol>"); // START rules ol
for (CCDAScoreCardRubrics curRubric : curCategory
.getCategoryRubrics()) {
if (curRubric.getNumberOfIssues() > 0) {
sb.append("<li>" + "Rule: " + curRubric.getRule()
+ "</li>");
if (curRubric.getDescription() != null) {
sb.append("<ul>" + "<li>" + "Description"
+ "</li>" + "<ul>" + "<li>"
+ curRubric.getDescription() + "</li>"
+ "</ul>" + "</ul>");
sb.append("<br />");
sb.append("<ol>"); // START snippets ol
for (CCDAXmlSnippet curSnippet : curRubric
.getIssuesList()) {
sb.append("<li>"
+ "XML at line number "
+ curSnippet.getLineNumber()
+ "</li>"
+ "<br /><xmp style='font-family: Consolas, monaco, monospace;'>"
+ curSnippet.getXmlString()
+ "</xmp><br /><br />");
}
sb.append("</ol>"); // END snippets ol
}
} else {
// don't display rules without occurrences
sb.append("</ol>");
}
}
sb.append("</ol>"); // END rules ol
sb.append("</ul>"); // END curCategory ul
appendBackToTopWithBreaks(sb);
} //END if (curCategory.getNumberOfIssues() > 0)
} //END for (Category curCategory : categories)
}
private static void appendPictorialGuide(StringBuffer sb,
List<Category> categories, List<ReferenceResult> referenceResults) {
//TODO: ensure this starts on a new page in a more proper manner - the first table is dynamic in size
sb.append("<br />");
// sb.append("<br />");
sb.append("<h2>" + "Guide to Interpret the Scorecard Results Table" + "</h2>");
sb.append("<p>" + "The following sample table identifies how to use the C-CDA Scorecard results "
+ "to improve the C-CDA documents generated by your organization. "
+ "Note: The table below is an example containing fictitious results "
+ "and does not reflect C-CDAs generated by your organization." + "</p>");
//static table
sb.append("<table id='staticTable'>")
.append(" <tr>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td id=\"issuePopOut\" rowspan='2'>")
.append(" A Scorecard Issue identifies data within the document which can be represented in a better way using HL7 best practices for C-CDA. This column should have numbers closer to zero. The Issues are counted for each occurrence of unimplemented best practice (e.g., if a Vital Sign measurement is not using the appropriate UCUM units then each such occurrence would be flagged as an issue). A provider should work with their health IT vendor to better understand the source for why a best practice may not be implemented and then determine if it can be implemented in the future. Note: Scorecard Issues may be zero for a clinical domain, when there is no data for the domain or if there are conformance or certification feedback results.")
.append(" </td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" </tr>")
.append(" <tr>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td id=\"gradePopOut\" colspan='2'>")
.append(" The Scorecard grade is a quantitative assessment of the data quality of the submitted document. Higher grade indicates that HL7 best practices for C-CDA implementation are being followed by the organization and has higher probability of being interoperable with other organizations. The grades are derived from the scores as follows: A+ ( > 94), A-( 90 to 94), B+ (85 to 89), B-(80 to 84), C(70 to 79) and D (< 70).")
.append(" </td>")
.append(" <td id=\"errorPopOut\" colspan='2'>")
.append(" A Conformance Error implies that the document is non-compliant with the HL7 C-CDA IG requirements. This column should have zeros ideally. Providers should work with their health IT vendor to rectify the errors.")
.append(" </td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" </tr>")
.append(" <tr>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td id=\"gradePopOutLink\"></td>")
.append(" <td id=\"issuePopOutLink\"></td>")
.append(" <td id=\"errorPopOutLink\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" </tr> ")
.append(" <tr>")
.append(" <td id=\"sectionPopOut\" rowspan='4'>")
.append(" The Section refers to the part of the document which may need attention depending on the identified results in the related row. Refer to the relevant HL7 C-CDA Implementation Guide to find the related sections your document.")
.append(" </td>")
.append(" <td id=\"sectionPopOutLink\"></td>")
.append(" <th id=\"sectionHeader\">Clinical Domain</th>")
.append(" <th id=\"gradeHeader\">Scorecard Grade</th>")
.append(" <th id=\"issueHeader\">Scorecard Issues</th>")
.append(" <th id=\"errorHeader\">Conformance Errors</th>")
.append(" <th id=\"feedbackHeader\">Certification Feedback</th>")
.append(" <td id=\"feedbackPopOutLink\"></td>")
.append(" <td id=\"feedbackPopOut\" rowspan='4'>")
.append(" A Certification Feedback result is not as severe as a Conformance Error, however it does identify areas where the generated documents are not compliant with the 2015 Edition certification requirements. Most of these errors fall into incorrect use of vocabularies and terminologies. This column should have zeros ideally. Providers should work with their health IT vendor to address the feedback provided to improve interoperable use of structured data between systems.")
.append(" </td>")
.append(" </tr>")
.append(" <tr>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td>Problems</td>")
.append(" <td>A+</td>")
.append(" <td>5</td>")
.append(" <td>0</td>")
.append(" <td>0</td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" </tr>")
.append(" <tr>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td>Lab Results</td>")
.append(" <td>A-</td>")
.append(" <td>4</td>")
.append(" <td>0</td>")
.append(" <td>0</td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" </tr>")
.append(" <tr>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td>Vital Signs</td>")
.append(" <td>A-</td>")
.append(" <td>6</td>")
.append(" <td>0</td>")
.append(" <td>0</td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" </tr> ")
.append(" <tr>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td>Encounters</td>")
.append(" <td>D</td>")
.append(" <td>6</td>")
.append(" <td>0</td>")
.append(" <td>0</td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" </tr>")
.append(" <tr>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td>Medications</td>")
.append(" <td>D</td>")
.append(" <td>N/A</td>")
.append(" <td>0</td>")
.append(" <td>1</td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" </tr>")
.append(" <tr>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td>Allergies</td>")
.append(" <td>D</td>")
.append(" <td>N/A</td>")
.append(" <td>0</td>")
.append(" <td>1</td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" </tr>")
.append(" <tr>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td>Immunizations</td>")
.append(" <td>D</td>")
.append(" <td>N/A</td>")
.append(" <td>0</td>")
.append(" <td>2</td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" </tr> ")
.append("</table>");
}
private static void appendClosingHtml(StringBuffer sb) {
sb.append("</body>");
sb.append("</html>");
}
private static void appendHorizontalRuleWithBreaks(StringBuffer sb) {
sb.append("<br />");
sb.append("<hr />");
sb.append("<br />");
}
private static void appendBackToTopWithBreaks(StringBuffer sb) {
// sb.append("<br />");
sb.append("<a href='#topOfScorecard'>Back to Top</a>");
// sb.append("<br />");
// A PDF conversion bug is not processing this valid HTML so commenting
// out until time to address
// sb.append("<a href='#heatMap'>Back to Section List</a>");
sb.append("<br />");
// sb.append("<br />");
}
private static void appendErrorMessage(StringBuffer sb, String errorMessage) {
sb.append("<h2 style='color:red; background-color: #ffe6e6'>");
sb.append(errorMessage);
sb.append("</h2>");
sb.append("<p>" + ApplicationConstants.ErrorMessages.CONTACT + "</p>");
}
private static void appendGenericErrorMessage(StringBuffer sb) {
sb.append("<p>"
+ ApplicationConstants.ErrorMessages.JSON_TO_JAVA_JACKSON
+ "<br />" + ApplicationConstants.ErrorMessages.CONTACT
+ "</p>");
}
private static void appendErrorMessageFromReport(StringBuffer sb,
ResponseTO report) {
appendErrorMessageFromReport(sb, report, null);
}
private static void appendErrorMessageFromReport(StringBuffer sb,
ResponseTO report, String extraMessage) {
if (report.getErrorMessage() != null
&& !report.getErrorMessage().isEmpty()) {
appendErrorMessage(sb, report.getErrorMessage());
} else {
appendGenericErrorMessage(sb);
}
if (extraMessage != null && !extraMessage.isEmpty()) {
sb.append("<p>" + extraMessage + "</p>");
}
}
protected static String ensureLogicalParseTreeInHTML(String htmlReport) {
org.jsoup.nodes.Document doc = Jsoup.parse(htmlReport);
String cleanHtmlReport = doc.toString();
return cleanHtmlReport;
}
private static void convertHTMLToPDF(String cleanHtmlReport) {
convertHTMLToPDF(cleanHtmlReport, null);
}
private static void convertHTMLToPDF(String cleanHtmlReport, HttpServletResponse response) {
OutputStream out = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document refineddoc = builder.parse(new ByteArrayInputStream(
cleanHtmlReport.getBytes("UTF-8")));
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(refineddoc, null);
renderer.layout();
if(response != null) {
//Stream to Output
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "attachment; filename="
+ "scorecardReport.pdf");
response.setHeader("max-age=3600", "must-revalidate");
response.addCookie(new Cookie("fileDownload=true", "path=/"));
out = response.getOutputStream();
} else {
//Save to local file system
out = new FileOutputStream(new File("testSaveReportImplementation.pdf"));
}
renderer.createPDF(out);
} catch (ParserConfigurationException pcE) {
pcE.printStackTrace();
} catch (SAXException saxE) {
saxE.printStackTrace();
} catch (DocumentException docE) {
docE.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
ApplicationUtil.debugLog("cleanHtmlReport", cleanHtmlReport);
}
}
protected static void convertHTMLToPDFAndStreamToOutput(
String cleanHtmlReport, HttpServletResponse response) {
convertHTMLToPDF(cleanHtmlReport, response);
}
private static void convertHTMLToPDFAndSaveToLocalFileSystem(String cleanHtmlReport) {
convertHTMLToPDF(cleanHtmlReport);
}
/**
* Converts JSON to ResponseTO Java Object using The Jackson API
*
* @param jsonReportData
* JSON which resembles ResponseTO
* @return converted ResponseTO POJO
*/
protected static ResponseTO convertJsonToPojo(String jsonReportData) {
ObjectMapper mapper = new ObjectMapper();
ResponseTO pojo = null;
try {
pojo = mapper.readValue(jsonReportData, ResponseTO.class);
} catch (IOException e) {
e.printStackTrace();
}
return pojo;
}
private enum SaveReportType {
MATCH_UI, SUMMARY;
}
private static void buildReportUsingJSONFromLocalFile(String filenameWithoutExtension,
SaveReportType reportType) throws URISyntaxException {
URI jsonFileURI = new File(
"src/main/webapp/resources/"
+ filenameWithoutExtension + ".json").toURI();
System.out.println("jsonFileURI");
System.out.println(jsonFileURI);
String jsonReportData = convertFileToString(jsonFileURI);
System.out.println("jsonReportData");
System.out.println(jsonReportData);
ResponseTO pojoResponse = convertJsonToPojo(jsonReportData);
System.out.println("response");
System.out.println(pojoResponse.getCcdaDocumentType());
convertHTMLToPDFAndSaveToLocalFileSystem(
ensureLogicalParseTreeInHTML(convertReportToHTML(pojoResponse, reportType)));
}
private static String convertFileToString(URI fileURI) {
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(fileURI.getPath()));
String sCurrentLine = "";
while ((sCurrentLine = br.readLine()) != null) {
sb.append(sCurrentLine);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public static void main(String[] args) {
String[] filenames = {"highScoringSample", "lowScoringSample", "sampleWithErrors"};
final int HIGH_SCORING_SAMPLE = 0, LOW_SCORING_SAMPLE = 1, SAMPLE_WITH_ERRORS = 2;
try {
buildReportUsingJSONFromLocalFile(filenames[SAMPLE_WITH_ERRORS], SaveReportType.SUMMARY);
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
|
package xyz.brassgoggledcoders.boilerplate.lib.common.registries;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.item.Item;
import net.minecraftforge.fml.common.registry.GameRegistry;
import xyz.brassgoggledcoders.boilerplate.lib.BoilerplateLib;
import xyz.brassgoggledcoders.boilerplate.lib.common.blocks.BaseBlock;
import xyz.brassgoggledcoders.boilerplate.lib.common.blocks.BaseTEBlock;
import xyz.brassgoggledcoders.boilerplate.lib.common.blocks.IHasItemBlock;
import xyz.brassgoggledcoders.boilerplate.lib.common.blocks.IHasTileEntity;
import java.util.HashMap;
import java.util.Map;
public class BlockRegistry extends BaseRegistry<Block>
{
private static BlockRegistry instance;
public static BlockRegistry getInstance()
{
if(instance == null)
{
instance = new BlockRegistry();
}
return instance;
}
@Override
public void initiateEntries()
{
for(Map.Entry<String, Block> entry : entries.entrySet())
{
if(entry.getValue() instanceof IHasItemBlock)
{
GameRegistry.registerBlock(entry.getValue(), ((IHasItemBlock)entry.getValue()).getItemBlockClass(),
entry.getKey());
} else
{
GameRegistry.registerBlock(entry.getValue(), entry.getKey());
}
if(entry.getValue() instanceof IHasTileEntity)
{
GameRegistry.registerTileEntity(((IHasTileEntity) entry.getValue()).getTileEntityClass(), entry.getKey());
}
}
}
public static void registerAndCreateBasicBlock(Material mat, String name)
{
Block block = new BaseBlock(mat);
getInstance().entries.put(name, block);
}
public static void registerBlock(Block block)
{
String name = block.getUnlocalizedName();
if(name.startsWith("block."))
{
name = name.substring(6);
}
registerBlock(block, name);
}
public static void registerBlock(Block block, String name)
{
getInstance().entries.put(name, block);
}
public static Block getBlock(String name)
{
return getInstance().entries.get(name);
}
}
|
package org.usfirst.frc.team3070.robot;
import com.ctre.CANTalon;
import org.usfirst.frc.team3070.robot.Pronstants;
import edu.wpi.first.wpilibj.AnalogGyro;
public class Drive {
static CANTalon talFR, talFL, talBR, talBL;
static AnalogGyro gyro;
public Drive()
{
//defines the talon variables
talFR = new CANTalon(Pronstants.TALON_FRONT_RIGHT_PORT);
talFL = new CANTalon(Pronstants.TALON_FRONT_lEFT_PORT);
talBR = new CANTalon(Pronstants.TALON_BACK_RIGHT_PORT);
talBL = new CANTalon(Pronstants.TALON_BACK_LEFT_PORT);
//sets a voltage ramp rate on the talons
talFR.setVoltageRampRate(Pronstants.RAMP_RATE);
talFL.setVoltageRampRate(Pronstants.RAMP_RATE);
talBR.setVoltageRampRate(Pronstants.RAMP_RATE);
talBL.setVoltageRampRate(Pronstants.RAMP_RATE);
//sets a current limit on the talons
talFR.setCurrentLimit(Pronstants.DRIVE_CURRENT_LIMIT);
talFL.setCurrentLimit(Pronstants.DRIVE_CURRENT_LIMIT);
talBR.setCurrentLimit(Pronstants.DRIVE_CURRENT_LIMIT);
talBL.setCurrentLimit(Pronstants.DRIVE_CURRENT_LIMIT);
//sets feedback device to encoders
talFR.setFeedbackDevice(CANTalon.FeedbackDevice.QuadEncoder);
talFL.setFeedbackDevice(CANTalon.FeedbackDevice.QuadEncoder);
}
public void joystickDrive(double joyR, double joyL) {
//makes the joystick control the talons
//defines the variables for the speed of left and right sides of the robot
double speedR, speedL;
//checks if the right joystick is in the deadzone
if (Math.abs(joyR) > Pronstants.DEAD_ZONE) {
//If it isn't, set the speed of the right side to the joystick value
speedR = joyR;
}
else {
//If the joystick is in the deadzone, set the speed of the right side to 0
speedR = 0;
}
//checks if the left joystick is in the deadzone
if (Math.abs(joyL) > Pronstants.DEAD_ZONE) {
//If it isn't, set the speed of the right side to the joystick value
speedL = joyL;
}
else {
//If the joystick is in the deadzone, set the speed of the right side to 0
speedL = 0;
}
//drives the robot forward at the speeds set earlier for left and right
drive(speedR, speedL);
}
public void drive(double right, double left)
{
//drives the robot based on two different input values for left and right
talFR.set(-right);
talBR.set(-right);
talFL.set(left);
talBL.set(left);
}
public double[] getDistanceTraveled()
{
//gets the distance traveled from the encoders
//creates a string with 2 doubles
double ar[] = new double[2];
//creates a double for each encoder value
ar[0] = talFR.getEncPosition() / Pronstants.TICK_COEFFICIENT;
ar[1] = talFL.getEncPosition() / Pronstants.TICK_COEFFICIENT;
//returns the encoder values
return ar;
}
public void resetDistanceTraveled() {
//resets the encoder values to 0
talFR.setEncPosition(0);
talFL.setEncPosition(0);
}
public void turnRight(double angle, double speed) {
//turns the robot right until it aligns with an angle on the gyro
//resets the gyro
gyro.reset();
//checks if the gyro is aligned with the desired angle
if (gyro.getAngle() < angle) { //consider implementing some compensation for the robot taking a bit to stop
//If it isn't, turn right
drive(-speed, speed);
}
//If it is, stop turning
drive(0,0);
}
public void turnLeft(double angle, double speed) {
//turns the robot right until it aligns with an angle on the gyro
//resets the gyro
gyro.reset();
//checks if the gyro is aligned with the desired angle
if (Math.abs(gyro.getAngle()) < angle) { //consider implementing some compensation for the robot taking a bit to stop
//If it isn't, turn left
drive(speed, -speed);
}
//If it is, stop turning
drive(0,0);
}
}
|
package org.formular.operation;
import java.util.LinkedList;
import java.util.List;
import org.formular.core.IOperation;
import org.formular.core.Input;
import org.formular.description.DescriptionElement;
public abstract class BinaryOperation extends AOperation<Float> {
private static final long serialVersionUID = 1L;
public IOperation<Float> right;
public IOperation<Float> left;
public void right(IOperation<Float> operation2) {
right = operation2;
}
public void left(IOperation<Float> operation1) {
left = operation1;
}
public IOperation<Float> right(Float i, Class<? extends ParameterOperation> class1) {
ParameterOperation newInstance = ParameterOperation.createParameter(i, class1);
this.right(newInstance);
return newInstance;
}
public IOperation<Float> left(Float i, Class<? extends ParameterOperation> class1) {
ParameterOperation newInstance = ParameterOperation.createParameter(i, class1);
this.left(newInstance);
return newInstance;
}
@Override
public List <DescriptionElement> inputDescriptions() {
List<DescriptionElement> ret = new LinkedList<DescriptionElement>();
for (Input input: inputs()) {
ret.add(input.getDesciption());
}
return ret;
}
@Override
public List<Input> inputs() {
List<Input> inputs = new LinkedList<Input>();
if(right != null)
inputs.addAll(right.inputs());
if(left != null)
inputs.addAll(left.inputs());
return inputs;
}
public void autoNameInputs() {
int i = 1;
for (Input input : this.inputs()) {
input.setName("input " + i);
i++;
}
};
@Override
public void addOperand(IOperation<?> operation) {
IOperation<Float> iOperation = ((IOperation<Float>) operation);
if (left == null) {
left = iOperation;
operation.setParent(this);
return;
}
if(right == null) {
right = iOperation;
operation.setParent(this);
return;
}
}
}
|
package com.sonymobile.tools.gerrit.gerritevents.dto.events;
import com.sonymobile.tools.gerrit.gerritevents.GerritJsonEventFactory;
import com.sonymobile.tools.gerrit.gerritevents.dto.GerritEvent;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import static org.junit.Assert.assertEquals;
public class EventCreatedOnTest {
/**
* Given an event in JSON format
* When it is converted to an Event Object
* Then the eventCreatedOn attribute can be parsed as a Date.
* @throws IOException if we cannot load json from file.
*/
@Test
public void fromJsonShouldProvideValidDateFromEventCreatedOn() throws IOException {
InputStream stream = getClass().getResourceAsStream("DeserializeEventCreatedOnTest.json");
String json = IOUtils.toString(stream);
JSONObject jsonObject = JSONObject.fromObject(json);
GerritEvent evt = GerritJsonEventFactory.getEvent(jsonObject);
GerritTriggeredEvent gEvt = (GerritTriggeredEvent)evt;
Date dt = gEvt.getEventCreatedOn();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(df.format(dt));
String expectDateString = "2014-12-09 14:02:52";
assertEquals(expectDateString, df.format(dt));
}
}
|
package gcm.gui;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.sbml.libsbml.Compartment;
import com.mxgraph.model.mxCell;
import gcm.gui.schematic.BioGraph;
import gcm.parser.GCMFile;
import gcm.util.GlobalConstants;
/**
* Contains all of the methods relevant to a grid
* This is an explict, formal grid which is principally used for tracking diffusible species
* and the locations of compartments/components/cells in a formal population
*
* @author jason (sarbruis@gmail.com)
*
*/
public class Grid {
//CLASS VARIABLES
//the actual grid -- a 2d arraylist of gridnodes
private ArrayList<ArrayList<GridNode>> grid;
//map of gridnodes and their corresponding rectangles
private HashMap<Rectangle, GridNode> rectToNodeMap;
//components on the grid
private HashMap<String, Properties> components;
//map of row, col grid locations to the component at that location
private HashMap<Point, Map.Entry<String, Properties>> locToComponentMap;
//map of compartment ID strings to the corresponding grid node
private HashMap<String, GridNode> componentIDToNodeMap;
private int numRows, numCols;
private int verticalOffset;
private double padding; //padding for the grid rectangles
private double gridWidth;
private double gridHeight;
private double gridGeomHeight; //to retain geometric shape for each grid rectangle
private double gridGeomWidth; //to retain geometric shape for each grid rectangle
private double componentGeomWidth;
private double componentGeomHeight;
private double zoomAmount;
private boolean enabled;
private boolean mouseClicked;
private boolean mouseReleased; //used for rubberband release
private Point scrollOffset; //for drawing when scrolled
private Rectangle rubberbandBounds;
private Rectangle gridBounds;
private Point mouseClickLocation;
private Point mouseLocation;
private BioGraph graph;
//CLASS METHODS
//PUBLIC
//GRID CREATION METHODS
/**
* default constructor
*/
public Grid() {
enabled = false;
mouseReleased = false;
verticalOffset = 0;
numRows = 0;
numCols = 0;
padding = 30;
zoomAmount = 1;
gridWidth = GlobalConstants.DEFAULT_COMPONENT_WIDTH + padding;
gridHeight = GlobalConstants.DEFAULT_COMPONENT_HEIGHT + padding;
gridGeomWidth = GlobalConstants.DEFAULT_COMPONENT_WIDTH + padding;
gridGeomHeight = GlobalConstants.DEFAULT_COMPONENT_HEIGHT + padding;
componentGeomWidth = GlobalConstants.DEFAULT_COMPONENT_WIDTH;
componentGeomHeight = GlobalConstants.DEFAULT_COMPONENT_HEIGHT;
scrollOffset = new Point(0, 0);
gridBounds = new Rectangle();
rubberbandBounds = new Rectangle();
mouseClickLocation = new Point();
mouseLocation = new Point();
grid = new ArrayList<ArrayList<GridNode>>();
rectToNodeMap = new HashMap<Rectangle, GridNode>();
locToComponentMap = new HashMap<Point, Map.Entry<String, Properties>>();
componentIDToNodeMap = new HashMap<String, GridNode>();
graph = null;
}
/**
* creates a 2d arraylist of GridNodes of rows x cols
* usually called from GridPanel
*
* @param rows number of rows in the grid
* @param cols number of columns in the grid
* @param components the components that are located on the grid
*/
public void createGrid(int rows, int cols, GCMFile gcm, String compGCM) {
//if the grid size is 0 by 0, don't make it
if (rows == 0 && cols == 0) {
enabled = false; //should be false already, but whatever
return;
}
enabled = true;
numRows = rows;
numCols = cols;
gcm.setIsWithinCompartment(true);
gcm.setEnclosingCompartment("gridLevel");
gcm.getSBMLDocument().getModel().getCompartment(0).setId("gridLevel");
for(int row = 0; row < numRows; ++row) {
grid.add(new ArrayList<GridNode>(numCols));
for(int col = 0; col < numCols; ++col) {
grid.get(row).add(new GridNode());
grid.get(row).get(col).setRow(row);
grid.get(row).get(col).setCol(col);
//null signifies that the components are already in the GCM
if (compGCM != null)
addComponentToGCM(row, col, compGCM, gcm);
}
}
this.components = gcm.getComponents();
updateGridRectangles();
updateRectToNodeMap();
updateLocToComponentMap();
updateComponentIDToNodeMap();
putComponentsOntoGrid();
}
//GRID DRAWING
public void drawGrid(Graphics g, BioGraph graph) {
Graphics2D g2 = (Graphics2D) g;
this.graph = graph;
boolean selectionOff = false;
//if the user has completed dragging the rubberband
if (rubberbandBounds != null && rubberbandBounds.height > 5
&& rubberbandBounds.width > 5 && mouseReleased == true) {
selectGridLocationsWithRubberband(g);
}
//if the user's mouse is within the grid bounds
else {
if (gridBounds.contains(mouseLocation)) {
//draw a hover-rectangle over the grid location
hoverGridLocation(g);
}
if (gridBounds.contains(mouseClickLocation)) {
//if the user has clicked, select/de-select that location
if (mouseClicked) selectGridLocation(g);
}
//if the user clicks out of bounds
//de-select all grid locations
else {
if (mouseClicked) selectionOff = true;
}
}
//draw the selection boxes for selected nodes
for (int row = 0; row < numRows; ++row) {
for (int col = 0; col < numCols; ++col) {
GridNode node = grid.get(row).get(col);
Rectangle rect = node.getZoomedRectangle();
if (selectionOff) node.setSelected(false);
if (node.isSelected())
drawGridSelectionBox(g, rect);
// //some debug stuff to draw onto the grid
// g2.drawString(Boolean.toString(node.isSelected()), rect.x, rect.y);
// if (node.component == null) {
// g2.drawString("null", rect.x+40, rect.y);
// else g2.drawString(node.getComponent().getKey(), rect.x+40, rect.y);
}
}
}
/**
* this draws a box around the grid location when the user hovers over it
* with the mouse or clicks it, which is used for grid location selection
*
* @param g Graphics object from the Schematic JPanel
* @param row the row of the selected location
* @param col the column of the selected location
*/
public void drawGridSelectionBox(Graphics g, Rectangle rect) {
g.setColor(new Color(0, 0, 255, 30));
//don't change the original rectangle; make a copy
Rectangle localRect = new Rectangle(rect);
localRect.x -= scrollOffset.x - 1;
localRect.y -= scrollOffset.y;
g.fillRect(localRect.x, localRect.y, localRect.width, localRect.height);
g.setColor(Color.black);
}
/**
* this draws a box around the grid location when the user hovers over it
* with the mouse or clicks it, which is used for grid location selection
*
* @param g Graphics object from the Schematic JPanel
* @param row the row of the selected location
* @param col the column of the selected location
*/
public void drawGridHoverBox(Graphics g, Rectangle rect) {
g.setColor(new Color(0, 0, 255, 150));
//don't change the original rectangle; make a copy
Rectangle localRect = new Rectangle(rect);
localRect.x -= scrollOffset.x - 1;
localRect.y -= scrollOffset.y;
//have to loop to get a thickness > 1
for (int i = 0; i < 3; ++i) {
localRect.x += 1; localRect.y += 1; localRect.width -= 2; localRect.height -= 2;
g.drawRect(localRect.x, localRect.y, localRect.width, localRect.height);
}
g.setColor(Color.black);
}
//NODE METHODS
/**
* clears a node and then removes it from the gcm
*
* @param compID component ID (uniquely identifies the node)
* @param gcm gcm file
*/
public void eraseNode(String compID, GCMFile gcm) {
//clear the grid node data (the actual node stays, though)
clearNode(compID);
//remove the component from the gcm
gcm.getComponents().remove(compID);
//keep the components list updated
components = gcm.getComponents();
}
/**
* empties a node on the grid based on a component ID
*
* @param compID
*/
public void clearNode(String compID) {
GridNode node = getNodeFromCompID(compID);
if (node != null && node.getComponent() != null) {
node.clear();
}
}
/**
* allocates a new node and sets the grid location
* also adds the node to the gcm
*
* @param row
* @param col
* @param compGCM
* @param gcm
*/
public void addNode(int row, int col, String compGCM, GCMFile gcm) {
grid.get(row).add(new GridNode());
grid.get(row).get(col).setRow(row);
grid.get(row).get(col).setCol(col);
if (!compGCM.equals("none")) {
grid.get(row).get(col).setOccupied(true);
addComponentToGCM(row, col, compGCM, gcm);
components = gcm.getComponents();
}
}
/**
* tries to move a node given the component ID and the center x,y coords
* of where the user is trying to move the component
*
* @param compID id of the component
* @param centerX center x coord of where the component is trying to be moved to
* @param centerY center y coord of where the component is trying to be moved to
*/
public boolean moveNode(String compID, double centerX, double centerY, GCMFile gcm) {
//adjust the point for zoom
Point moveToPoint = new Point((int)((double)centerX*zoomAmount), (int)((double)centerY*zoomAmount + verticalOffset));
//if the user is trying to move the component to a place within the grid
//then pay attention
if (gridBounds.contains(moveToPoint)) {
GridNode node = getNodeFromPoint(moveToPoint);
//this shouldn't be null because we're on the grid, but just in case . . .
if (node != null) {
//make sure there isn't a component in the location
if (node.isOccupied() == false) {
//this is a horrible hack to get a Map.Entry<String, Property>
//i didn't realize it was an interface and not instantiable
HashMap<String, Properties> tempMap = new HashMap<String, Properties>();
tempMap.put(compID, components.get(compID));
Map.Entry<String, Properties> compo = tempMap.entrySet().iterator().next();
//clear the old component's spot
clearNode(compID);
//put the component in its new home
node.setComponent(compo);
node.setOccupied(true);
Properties props = compo.getValue();
props.setProperty("row", Integer.toString(node.getRow()));
props.setProperty("col", Integer.toString(node.getCol()));
//update the location to component hash map
//as the component and their locations have changed
updateLocToComponentMap();
return true;
}
else return false;
}
else return false;
}
else return false;
}
/**
* clears all nodes that are selected
*/
public void eraseSelectedNodes(GCMFile gcm) {
//loop through all nodes
//if it's selected, clear it
for (int row = 0; row < numRows; ++row) {
for (int col = 0; col < numCols; ++col) {
if (grid.get(row).get(col).isSelected() && grid.get(row).get(col).isOccupied())
eraseNode(grid.get(row).get(col).getComponent().getKey(), gcm);
}
}
}
/**
* sets every node to selected
*/
public void selectAllNodes() {
//loop through each grid node to see if one is selected
for (int row = 0; row < numRows; ++row) {
for (int col = 0; col < numCols; ++col) {
grid.get(row).get(col).setSelected(true);
}
}
mouseClicked = false;
}
/**
* sets every node to deselected
*/
public void deselectAllNodes() {
//loop through each grid node to see if one is selected
for (int row = 0; row < numRows; ++row) {
for (int col = 0; col < numCols; ++col) {
grid.get(row).get(col).setSelected(false);
}
}
}
/**
* returns the row/col of each selected node in an arraylist
* @return the row/col of each selected node
*/
public ArrayList<Point> getSelectedUnoccupiedNodes() {
ArrayList<Point> selectedNodes = new ArrayList<Point>();
//loop through each grid node to see if one is selected
for (int row = 0; row < numRows; ++row) {
for (int col = 0; col < numCols; ++col) {
if (grid.get(row).get(col).isSelected() && !grid.get(row).get(col).isOccupied())
selectedNodes.add(new Point(grid.get(row).get(col).getRow(), grid.get(row).get(col).getCol()));
}
}
return selectedNodes;
}
//INFORMATION RETRIEVAL METHODS
/**
* finds and returns the snap rectangle from the component id passed in
* @param compID component id
* @return the snap rectangle
*/
public Rectangle getSnapRectangleFromCompID(String compID) {
return getNodeFromCompID(compID).getSnapRectangle();
}
/**
* returns where or not the user clicked on an occupied grid location
* @param mouseX where the user clicked
* @param mouseY where the user clicked
* @return true if the grid location is occupied, false if not
*/
public boolean getOccupancyFromPoint(Point point) {
point.y += verticalOffset;
GridNode node = getNodeFromPoint(point);
if (node != null)
return node.isOccupied();
//return true because it's easier to consider outside the grid as occupied
//so nothing can ever get placed there
else return true;
}
/**
* returns the grid row corresponding to a point
*
* @param point
* @return the grid row corresponding to the point
*/
public int getRowFromPoint(Point point) {
point.y += verticalOffset;
return getNodeFromPoint(point).getRow();
}
/**
* returns the grid column corresponding to a point
*
* @param point
* @return the grid column corresponding to the point
*/
public int getColFromPoint(Point point) {
point.y += verticalOffset;
return getNodeFromPoint(point).getCol();
}
/**
* returns whether or not the user clicked within a grid but outside of the component
* (ie, in the grid's padding area)
*
* @param clickPoint where the user clicked
* @return whether or not the user clicked within a grid but outside of the component
*/
public boolean clickedOnGridPadding(Point clickPoint) {
clickPoint.y += verticalOffset;
//if the user clicked on the grid somewhere
if (gridBounds.contains(clickPoint)) {
//get the grid node corresponding to the click point
GridNode node = getNodeFromPoint(clickPoint);
if (node == null) return true;
//set the snap rectangles operate on mxGraph coordinates
//so we need to erase the vertical offset
clickPoint.y -= verticalOffset;
//if the user didn't click within the component
if (!node.getZoomedSnapRectangle().contains(clickPoint) || node.isOccupied() == false)
return true;
else
return false;
}
//allows de-selection of all on clicking out-of-bounds
else return true;
}
/**
* returns whether or not there's something selected
* this is used for changing the right-click context menu
*
* @return whether or not there's something selected
*/
public boolean isALocationSelected() {
//loop through each grid node
//if one is selected, return true
for (int row = 0; row < numRows; ++row) {
for (int col = 0; col < numCols; ++col) {
if (grid.get(row).get(col).isSelected())
return true;
}
}
return false;
}
//GRID UPDATING METHODS
/**
* updates the local graph pointer and updates the grid's rectangles and maps
* according to the new graph passed in
*
* this is used when the grid sizes/positions change, like with scrolling or zooming
*
* @param graph
*/
public void syncGridGraph(BioGraph graph) {
this.graph = graph;
updateGridRectangles();
updateLocToComponentMap();
updateRectToNodeMap();
}
/**
* takes the gcm's components and resets the grid with those components
* this happens after adding or deleting a node or nodes (like in resizing)
*/
public void refreshComponents(HashMap<String, Properties> gcmComponents) {
components = gcmComponents;
//update the graph
if (graph != null)
graph.buildGraph();
putComponentsOntoGrid();
updateGridRectangles();
//update the location to component hash map
//and the rectangle to node map
//as the components and their locations have changed
updateLocToComponentMap();
updateRectToNodeMap();
}
/**
* changes the grid size
* also updates the GCM components
*
* @param rows number of rows in the new grid size
* @param cols number of cols in the new grid size
* @param compGCM the name of the gcm of the new components
* @param gcm the gcm file that's being altered
*/
public void changeGridSize(int rows, int cols, String compGCM, GCMFile gcm) {
int currentNumRows = this.numRows;
int currentNumCols = this.numCols;
int newNumRows = rows;
int newNumCols = cols;
int numRowsToAdd = newNumRows - currentNumRows;
int numColsToAdd = newNumCols - currentNumCols;
//growing the grid rows
if (numRowsToAdd > 0) {
//add new rows up to the new number of columns
for (int row = currentNumRows; row < newNumRows; ++row) {
//allocate grid nodes for the new rows
//note: this could be small than the old size
//but that doesn't matter
grid.add(new ArrayList<GridNode>(newNumCols));
for(int col = 0; col < newNumCols; ++col) {
addNode(row, col, compGCM, gcm);
}
}
}
//shrinking the grid rows
else if (numRowsToAdd < 0) {
//go from the new last row to the prior last row
//erase all of the nodes (which clears them and erases the components from the gcm)
for (int row = newNumRows; row < currentNumRows; ++row) {
for (int col = 0; col < currentNumCols; ++col) {
Map.Entry<String, Properties> component = locToComponentMap.get(new Point(row, col));
//if it's null, there's nothing to erase
if (component != null) {
String compID = component.getKey();
//if it's null, there's nothing to erase
if (compID != null) eraseNode(compID, gcm);
}
}
}
//change this so that the columns aren't added with length past the proper number of rows
currentNumRows = newNumRows;
}
//growing the grid cols
if (numColsToAdd > 0) {
//add new columns up to the current number of rows
for (int row = 0; row < currentNumRows; ++row) {
//allocate grid nodes for the new columns
grid.add(new ArrayList<GridNode>(numColsToAdd));
for(int col = currentNumCols; col < newNumCols; ++col) {
addNode(row, col, compGCM, gcm);
}
}
}
//shrinking the grid cols
else if (numColsToAdd < 0) {
//go from the new last col to the prior last col
//erase all of the nodes (which clears them and erases the components from the gcm)
for (int row = 0; row < currentNumRows; ++row) {
for (int col = newNumCols; col < currentNumCols; ++col) {
Map.Entry<String, Properties> component = locToComponentMap.get(new Point(row, col));
//if it's null, there's nothing to erase
if (component != null) {
String compID = component.getKey();
//if it's null, there's nothing to erase
if (compID != null) eraseNode(compID, gcm);
}
}
}
}
this.numRows = newNumRows;
this.numCols = newNumCols;
//put the components onto the grid and update hash maps and update the graph
refreshComponents(gcm.getComponents());
}
//PRIVATE
//HASH MAP UPDATING METHODS
/**
* creates a hash map of corresponding rectangles and nodes
* this allows easy access of nodes from rectangle coordinates
*/
private void updateRectToNodeMap() {
rectToNodeMap.clear();
//loop through the rows and columns
//find the grid node and rectangle then make it a map entry
for (int row = 0; row < numRows; ++row) {
for (int col = 0; col < numCols; ++col) {
rectToNodeMap.put(grid.get(row).get(col).getZoomedRectangle(), grid.get(row).get(col));
}
}
}
/**
* creates a hash map for easy access of the component at a specified grid location
* with the component you can get its name and properties
* used for diffusion reaction printing in printDiffusion
* uses 1-indexed row/col numbers!!!
*/
private void updateLocToComponentMap() {
locToComponentMap.clear();
if (components == null) return;
//iterate through the components to get the number of rows and cols
for (Map.Entry<String, Properties> compo : components.entrySet()) {
//find the row and col from the component's properties
Properties props = compo.getValue();
int row = Integer.parseInt(props.getProperty("row"));
int col = Integer.parseInt(props.getProperty("col"));
locToComponentMap.put(new Point(row, col), compo);
}
}
/**
* creates a hashmap for easy access to node information from a component ID
*/
private void updateComponentIDToNodeMap() {
for (int row = 0; row < numRows; ++row) {
for (int col = 0; col < numCols; ++col) {
GridNode node = grid.get(row).get(col);
if (node != null && node.getComponent() != null)
componentIDToNodeMap.put(node.getComponent().getKey(), node);
}
}
}
//INFORMATION RETRIEVAL METHODS
/**
* returns the corresponding grid node for the given point
*
* @param point
* @return the corresponding grid node
*/
private GridNode getNodeFromPoint(Point point) {
//loop through every row and column
//check this location's rectangle against the x,y point
//if it contains it, return that node
for (int row = 0; row < numRows; ++row) {
for (int col = 0; col < numCols; ++col) {
Rectangle rect = grid.get(row).get(col).getZoomedRectangle();
if (rect.contains(point))
return rectToNodeMap.get(rect);
}
}
return null;
}
/**
* finds and returns the grid node with the component id passed in
* @param compID
* @return the grid node with the component id
*/
private GridNode getNodeFromCompID(String compID) {
updateComponentIDToNodeMap();
return componentIDToNodeMap.get(compID);
}
//GRID UPDATING METHODS
/**
* sets the rectangles/bounds for each node
* also sets the bounds for the entire grid
*/
private void updateGridRectangles() {
//create/set rectangles for each location in grid
for (int row = 0; row < numRows; ++row) {
for (int col = 0; col < numCols; ++col) {
//find the bounds from the cell at this row/col
//use that rectangle as the node's rectangle
String cellID = "ROW" + row + "_COL" + col;
if (graph != null && graph.getGridRectangleCellFromID(cellID) != null) {
//set the component sizes (which may have changed due to zooming)
Map.Entry<String, Properties> comp = grid.get(row).get(col).getComponent();
if (comp != null) {
mxCell compCell = graph.getComponentCell(comp.getKey());
if (compCell != null) {
Rectangle compCellRect = graph.getCellGeometry(compCell).getRectangle();
componentGeomHeight = compCellRect.getHeight();
componentGeomWidth = compCellRect.getWidth();
}
}
//set the zoom scale
zoomAmount = graph.getView().getScale();
//get the bounds information from the graph and set the grid
//rectangle's data to fit with the graph's data
mxCell cell = graph.getGridRectangleCellFromID(cellID);
Rectangle cellGeom = graph.getCellGeometry(cell).getRectangle();
gridGeomHeight = cellGeom.getHeight();
gridGeomWidth = cellGeom.getWidth();
gridHeight = gridGeomHeight * zoomAmount;
gridWidth = gridGeomWidth * zoomAmount;
//set the current padding value (which may have changed due to zooming)
//this is usually going to be 30
padding = gridGeomWidth - componentGeomWidth;
grid.get(row).get(col).setRectangle(cellGeom);
}
}
}
//set the total grid bounds
int outerX = (int)gridWidth * numCols;
int outerY = (int)gridHeight * numRows + (int)verticalOffset;
gridBounds.setBounds(15, 15, outerX, outerY);
}
/**
* takes the component list and uses their row/col properties to
* place them onto the grid
*
* i think this should only be run once on grid creation
*/
private void putComponentsOntoGrid() {
//iterate through the components to get the x/y coords of its top left vertex
//using these coords, map it to the grid
for (Map.Entry<String, Properties> compo : components.entrySet()) {
//find the row and col from the component's properties
//use these to put the component into the correct grid location
Properties props = compo.getValue();
String gcm = props.getProperty("gcm");
int row = Integer.valueOf(props.getProperty("row"));
int col = Integer.valueOf(props.getProperty("col"));
//if adding blank components, don't set the component
if (gcm.equals("none"))
grid.get(row).get(col).setOccupied(false);
else {
grid.get(row).get(col).setComponent(compo);
grid.get(row).get(col).setOccupied(true);
}
}
}
/**
* adds a component to the GCM passed in
*
* @param row
* @param col
* @param compGCM the name of the component's gcm file
* @param gcm the gcm to put the component in
*/
private void addComponentToGCM(int row, int col, String compGCM, GCMFile gcm) {
double padding = 30;
double width = componentGeomWidth;
double height = componentGeomHeight;
//don't put blank components onto the grid or gcm
if (!compGCM.equals("none")) {
//make a new properties field with all of the new component's properties
Properties properties = new Properties();
properties.put("gcm", compGCM); //comp is the name of the gcm that the component contains
properties.setProperty("graphwidth", String.valueOf(GlobalConstants.DEFAULT_COMPONENT_WIDTH));
properties.setProperty("graphheight", String.valueOf(GlobalConstants.DEFAULT_COMPONENT_HEIGHT));
properties.setProperty("graphx", String.valueOf(col * (width + padding) + padding));
properties.setProperty("graphy", String.valueOf(row * (height + padding) + padding));
properties.setProperty("row", String.valueOf(row));
properties.setProperty("col", String.valueOf(col));
GCMFile compGCMFile = new GCMFile(gcm.getPath());
compGCMFile.load(gcm.getPath() + File.separator + compGCM);
//set the correct compartment status
if (compGCMFile.getIsWithinCompartment())
properties.setProperty("compartment","true");
else properties.setProperty("compartment","false");
gcm.addComponent(null, properties);
}
}
//HOVER AND SELECTION METHODS
/**
* based on the mouse location, draws a box around the grid location
* that the user is hovering over
*
* @param location the mouse location x,y coordinates
*/
private void hoverGridLocation(Graphics g) {
GridNode hoveredNode = getNodeFromPoint(mouseLocation);
if (hoveredNode != null) {
hoveredNode.setHover(true);
drawGridHoverBox(g, hoveredNode.getZoomedRectangle());
}
}
/**
* based on the mouse-click location, selects the grid location
* also draws a selection box
*
* @param location the mouse-click x,y coordinates
*/
private void selectGridLocation(Graphics g) {
GridNode hoveredNode = getNodeFromPoint(mouseClickLocation);
//select or de-select the grid location
if (hoveredNode != null)
hoveredNode.setSelected(hoveredNode.isSelected() == true ? false : true);
//this click's action has been performed, so set it to false until
//the user clicks again
mouseClicked = false;
}
/**
* selects grid locations using the bounds of the graph's rubberband
*
* @param g
*/
private void selectGridLocationsWithRubberband(Graphics g) {
rubberbandBounds.y += verticalOffset;
//loop through all of the grid locations
//if its rectangle is contained within the rubberband, select it
for (int row = 0; row < numRows; ++row) {
for (int col = 0; col < numCols; ++col) {
if (rubberbandBounds.contains(grid.get(row).get(col).getZoomedRectangle()))
grid.get(row).get(col).setSelected(true);
}
}
mouseReleased = false;
rubberbandBounds = null;
mouseClicked = false;
}
//BORING GET/SET METHODS
/**
* @param enabled whether or not the grid is enabled
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
/**
* @return whether or not the grid is enabled
*/
public boolean isEnabled() {
return enabled;
}
/**
*
* @return the components on the grid
*/
public HashMap<String, Properties> getComponents() {
return components;
}
/**
* @param components the components on the grid
*/
public void setComponents(HashMap<String, Properties> components) {
this.components = components;
}
/**
* used for when there's a toolbar
* @return the number of pixels from the top of the jpanel
*/
public int getVerticalOffset() {
return verticalOffset;
}
/**
* used for when there's a toolbar
* @param verticalOffset pixels from the top of the jpanel
*/
public void setVerticalOffset(int verticalOffset) {
this.verticalOffset = verticalOffset;
//change the grid's rectangle locations based on this offset
updateGridRectangles();
updateRectToNodeMap();
}
/**
* @return the numRows
*/
public int getNumRows() {
return numRows;
}
/**
* @return the numCols
*/
public int getNumCols() {
return numCols;
}
/**
* @param mouseClickLocation the mouseClickLocation to set
*/
public void setMouseClickLocation(Point mouseClickLocation) {
this.mouseClickLocation = new Point(mouseClickLocation.x, mouseClickLocation.y + verticalOffset);
mouseClicked = true;
}
/**
* @return the mouseClickLocation
*/
public Point getMouseClickLocation() {
return mouseClickLocation;
}
/**
* @param mouseLocation the mouseLocation to set
*/
public void setMouseLocation(Point mouseLocation) {
//the mouse location is changed because of the vertical offset
this.mouseLocation = new Point(mouseLocation.x, mouseLocation.y + verticalOffset);
}
/**
* @return the mouseLocation
*/
public Point getMouseLocation() {
return mouseLocation;
}
/**
* @return padding pixels between grid components
*/
public double getPadding() {
return padding;
}
/**
* @param scrollOffset the scrollOffset to set
*/
public void setScrollOffset(Point scrollOffset) {
this.scrollOffset = scrollOffset;
}
/**
* @return the scrollOffset
*/
public Point getScrollOffset() {
return scrollOffset;
}
/**
* @return the gridWidth
*/
public double getGridWidth() {
return gridWidth;
}
/**
* @param gridWidth the gridWidth to set
*/
public void setGridWidth(double gridWidth) {
this.gridWidth = gridWidth;
}
/**
* @param componentWidth the componentWidth to set
*/
public void setComponentGeomWidth(double componentGeomWidth) {
this.componentGeomWidth = componentGeomWidth;
}
/**
* @return the componentGeomWidth
*/
public double getComponentGeomWidth() {
return componentGeomWidth;
}
/**
* @return the ComponentGeomHeight
*/
public double getComponentGeomHeight() {
return componentGeomHeight;
}
/**
* @param ComponentGeomHeight the ComponentGeomHeight to set
*/
public void setComponentGeomHeight(double componentGeomHeight) {
this.componentGeomHeight = componentGeomHeight;
}
/**
* @return the gridGeomHeight
*/
public double getGridGeomHeight() {
return gridGeomHeight;
}
/**
* @param gridGeomHeight the gridGeomHeight to set
*/
public void setGridGeomHeight(double gridGeomHeight) {
this.gridGeomHeight = gridGeomHeight;
}
/**
* @return the gridGeomWidth
*/
public double getGridGeomWidth() {
return gridGeomWidth;
}
/**
* @param gridGeomWidth the gridGeomWidth to set
*/
public void setGridGeomWidth(double gridGeomWidth) {
this.gridGeomWidth = gridGeomWidth;
}
/**
* @return the gridHeight
*/
public double getGridHeight() {
return gridHeight;
}
/**
* @param gridHeight the gridHeight to set
*/
public void setGridHeight(double gridHeight) {
this.gridHeight = gridHeight;
}
/**
* @param rubberbandBounds the bounds of the graph's rubberband
*/
public void setRubberbandBounds(Rectangle rubberbandBounds) {
this.rubberbandBounds = rubberbandBounds;
}
/**
* @return the bounds of the graph's rubberband
*/
public Rectangle getRubberbandBounds() {
return rubberbandBounds;
}
/**
* @param mouseReleased the mouseReleased state of the schematic
*/
public void setMouseReleased(boolean mouseReleased) {
this.mouseReleased = mouseReleased;
}
/**
* @return the mouseReleased state of the schematic
*/
public boolean isMouseReleased() {
return mouseReleased;
}
/**
* @return the location-to-component map
*/
public Map.Entry<String, Properties> getComponentFromLocation(Point location) {
updateLocToComponentMap();
return locToComponentMap.get(location);
}
/**
* returns the row and column of a component based on a given ID
*
* @param compID the component ID
* @return the row and column of that component
*/
public Point getLocationFromComponentID(String compID) {
return new Point(getNodeFromCompID(compID).getRow(), getNodeFromCompID(compID).getCol());
}
public void setGraph(BioGraph graph) {
this.graph = graph;
}
//GRIDNODE CLASS
/**
* contains all of the information for a grid node
* each location on the grid is a grid node
*/
private class GridNode {
//CLASS VARIABLES
private boolean occupied; //has a component or not
private Map.Entry<String, Properties> component; //component in node
private int row, col; //location on the grid (not x,y coords)
private Rectangle snapRectangle; //x,y coordinate of the top-left of the component (not grid) rectangle
private boolean isCompartment; //component is a compartment or not
private boolean selected; //is the grid location selected or not
private boolean hover; //is the grid location being hovered over or not
private Rectangle gridRectangle; //contains the grid coordinates and size
//CLASS METHODS
/**
* default constructor that initializes variables
*/
public GridNode() {
occupied = false;
isCompartment = false;
component = null;
selected = false;
hover = false;
snapRectangle = new Rectangle(0, 0, 0, 0);
gridRectangle = new Rectangle(0, 0, 0, 0);
}
//PUBLIC
/**
* deletes the node's component, freeing it to be re-set to another
*/
public void clear() {
occupied = false;
component = null;
isCompartment = false;
}
//BORING GET/SET METHODS
/**
*
* @return the occupancy status
*/
public boolean isOccupied() {
return occupied;
}
/**
*
* @param occupancy whether gridNode is occupied or not
*/
public void setOccupied(boolean occupancy) {
occupied = occupancy;
}
/**
* @param col the col to set
*/
public void setCol(int col) {
this.col = col;
}
/**
* @return the col
*/
public int getCol() {
return col;
}
/**
* @param row the row to set
*/
public void setRow(int row) {
this.row = row;
}
/**
* @return the row
*/
public int getRow() {
return row;
}
/**
* also sets boolean about whether the component is a compartment
* @param component the component to set
*/
public void setComponent(Map.Entry<String, Properties> component) {
this.component = null;
this.component = component;
isCompartment = Boolean.getBoolean(component.getValue().getProperty("compartment"));
}
/**
* @return the component
*/
public Map.Entry<String, Properties> getComponent() {
return component;
}
/**
* sets the geometric rectangle of the location
* @param rectangle the rectangle for the node
*/
public void setRectangle(Rectangle rectangle) {
this.gridRectangle = rectangle;
int xCoord = (int)(col * gridGeomWidth + padding/2);
int yCoord = (int)(row * gridGeomHeight + padding/2);
snapRectangle = new Rectangle(
(int)(xCoord + padding/2),
(int)(yCoord + padding/2),
(int)componentGeomWidth,
(int)componentGeomHeight);
}
/**
* returns the geometric rectangle of the location
* to get the actual coordinates, you need the zoomed version
*
* @return the grid rectangle for the node
*/
public Rectangle getRectangle() {
return new Rectangle(gridRectangle.x, gridRectangle.y + verticalOffset,
gridRectangle.width, gridRectangle.height);
}
/**
* returns rectangle after applying zoom scaling
*
* @return zoomed rectangle
*/
public Rectangle getZoomedRectangle() {
return new Rectangle(
(int)((double)gridRectangle.x * zoomAmount + 0.5),
(int)((double)gridRectangle.y * zoomAmount + verticalOffset + 0.5),
(int)((double)gridRectangle.width * zoomAmount + 0.5),
(int)((double)gridRectangle.height * zoomAmount + 0.5));
}
/**
* pair of points specifying which location the component should "snap" to
* ie, a component is only allowed to have its top-left point at this snap point
*
* used by the schematic to move cells around the graph
*
* this is a geometric rectangle; to get actual coordinates, you need the zoomed rectangle
*
* @param x
* @param y
*/
public void setSnapRectangle(Rectangle r) {
snapRectangle = r;
}
/**
* used by the schematic to move cells around the graph
*
* @return the snap rectangle
*/
public Rectangle getSnapRectangle() {
return snapRectangle;
}
/**
* returns the snap rectangle after applying a zoom scaling
* @return the zoomed snap rectangle
*/
public Rectangle getZoomedSnapRectangle() {
return new Rectangle(
(int)(snapRectangle.x * zoomAmount),
(int)(snapRectangle.y * zoomAmount),
(int)(snapRectangle.width * zoomAmount),
(int)(snapRectangle.height * zoomAmount));
}
/**
* @return the isCompartment
*/
public boolean isCompartment() {
return isCompartment;
}
/**
* @param isCompartment the isCompartment to set
*/
public void setCompartment(boolean isCompartment) {
this.isCompartment = isCompartment;
}
/**
* @param selected the selected status
*/
public void setSelected(boolean selected) {
this.selected = selected;
}
/**
* @return the selected status
*/
public boolean isSelected() {
return selected;
}
/**
* @param selected the hover status
*/
public void setHover(boolean hover) {
this.hover = hover;
}
/**
* @return the hover status
*/
public boolean isHover() {
return hover;
}
}
}
|
public class Vehicle {
private String regNbr;
private String model;
private String type;
private String licenseReq;
private int price;
private String info;
private boolean hasHook;
private String expiryDate;
public String getRegNbr() {
return regNbr;
}
public void setRegNbr(String regNbr) {
this.regNbr = regNbr;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getLicenseReq() {
return licenseReq;
}
public void setLicenseReq(String licenseReq) {
this.licenseReq = licenseReq;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public boolean isHasHook() {
return hasHook;
}
public void setHasHook(boolean hasHook) {
this.hasHook = hasHook;
}
public String getExpiryDate(){
return expiryDate;
}
public void setExpiryDate(String expiryDate){
this.expiryDate = expiryDate;
}
}
|
package org.scenarioo.pizza.selenium;
import org.scenarioo.pizza.scenarioo.ScenariooEventListener;
import org.scenarioo.pizza.scenarioo.UseCaseContext;
import org.scenarioo.pizza.scenarioo.UseCaseContextHolder;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;
/**
* This singleton creates and holds the reference to the WebDriver which controls the browser.
* This makes it possible to access the WebDriver from all the page objects and wherever else
* needed without passing any references.
* <p>
* Currently this holder only supports one concurrent WebDriver. If you want to run your tests in parallel
* you should extend the holder to hold an instance of a WebDriver for each thread.
*/
public enum WebDriverHolder {
INSTANCE;
private EventFiringWebDriver webDriver;
/**
* Only call this after a use case context has been created for the current use case.
*/
public void openBrowserAndRegisterEventListener() {
webDriver = new EventFiringWebDriver(new FirefoxDriver());
UseCaseContext useCaseContext = UseCaseContextHolder.INSTANCE.getUseCaseContext();
ScenariooEventListener scenariooEventListener = new ScenariooEventListener(useCaseContext);
webDriver.register(scenariooEventListener);
}
public WebDriver getWebDriver() {
return webDriver;
}
public void closeBrowser() {
webDriver.close();
}
}
|
package org.cornutum.tcases.openapi.test;
import com.fasterxml.jackson.databind.JsonNode;
import org.junit.Test;
import static org.cornutum.hamcrest.Composites.*;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.Optional;
/**
* Runs {@link SimpleDecoder} tests.
*/
public class SimpleDecoderTest
{
@Test
public void whenNotExplodedObject()
{
// Given...
boolean explode = false;
SimpleDecoder decoder = new SimpleDecoder( explode);
String content;
// When...
content = "A,1,B,-2.0,C,3";
// Then...
assertJsonNodes(
"Decoded",
decoder.decodeObject( content),
"{\"A\":1,\"B\":-2.0,\"C\":3}",
"{\"A\":1,\"B\":-2.0,\"C\":\"3\"}",
"{\"A\":1,\"B\":\"-2.0\",\"C\":3}",
"{\"A\":1,\"B\":\"-2.0\",\"C\":\"3\"}",
"{\"A\":\"1\",\"B\":-2.0,\"C\":3}",
"{\"A\":\"1\",\"B\":-2.0,\"C\":\"3\"}",
"{\"A\":\"1\",\"B\":\"-2.0\",\"C\":3}",
"{\"A\":\"1\",\"B\":\"-2.0\",\"C\":\"3\"}");
// When...
content = "1,A,-2.0,,3,";
// Then...
assertJsonNodes(
"Decoded",
objectNodes( decoder.decodeObject( content)),
"{\"1\":\"A\",\"-2.0\":\"\",\"3\":\"\"}",
"{\"1\":\"A\",\"-2.0\":\"\",\"3\":null}",
"{\"1\":\"A\",\"-2.0\":null,\"3\":\"\"}",
"{\"1\":\"A\",\"-2.0\":null,\"3\":null}");
// When...
content = "";
// Then...
assertJsonNodes(
"Decoded",
objectNodes( decoder.decodeObject( content)),
"{}");
// When...
content = "A";
// Then...
assertJsonNodes( "Decoded", objectNodes( decoder.decodeObject( content)));
// When...
content = "A,,B";
// Then...
assertJsonNodes( "Decoded", objectNodes( decoder.decodeObject( content)));
}
@Test
public void whenExplodedObject()
{
// Given...
boolean explode = true;
SimpleDecoder decoder = new SimpleDecoder( explode);
String content;
// When...
content = "A=1,B=-2.0,C=3";
// Then...
assertJsonNodes(
"Decoded",
decoder.decodeObject( content),
"{\"A\":1,\"B\":-2.0,\"C\":3}",
"{\"A\":1,\"B\":-2.0,\"C\":\"3\"}",
"{\"A\":1,\"B\":\"-2.0\",\"C\":3}",
"{\"A\":1,\"B\":\"-2.0\",\"C\":\"3\"}",
"{\"A\":\"1\",\"B\":-2.0,\"C\":3}",
"{\"A\":\"1\",\"B\":-2.0,\"C\":\"3\"}",
"{\"A\":\"1\",\"B\":\"-2.0\",\"C\":3}",
"{\"A\":\"1\",\"B\":\"-2.0\",\"C\":\"3\"}");
// When...
content = "1=A,-2.0=,3=";
// Then...
assertJsonNodes(
"Decoded",
objectNodes( decoder.decodeObject( content)),
"{\"1\":\"A\",\"-2.0\":\"\",\"3\":\"\"}",
"{\"1\":\"A\",\"-2.0\":\"\",\"3\":null}",
"{\"1\":\"A\",\"-2.0\":null,\"3\":\"\"}",
"{\"1\":\"A\",\"-2.0\":null,\"3\":null}");
// When...
content = "";
// Then...
assertJsonNodes(
"Decoded",
objectNodes( decoder.decodeObject( content)),
"{}");
// When...
content = "-1.23";
// Then...
assertJsonNodes( "Decoded", objectNodes( decoder.decodeObject( content)));
// When...
content = "A,1,B,-2.0,C,3";
// Then...
assertJsonNodes( "Decoded", objectNodes( decoder.decodeObject( content)));
// When...
content = "A=1,B=-2.0,C==3";
// Then...
assertJsonNodes( "Decoded", objectNodes( decoder.decodeObject( content)));
// When...
content = "A=1,B,C=3";
// Then...
assertJsonNodes( "Decoded", objectNodes( decoder.decodeObject( content)));
// When...
content = "A=1,";
// Then...
assertJsonNodes( "Decoded", objectNodes( decoder.decodeObject( content)));
}
@Test
public void whenArray()
{
// Given...
boolean explode = false;
SimpleDecoder decoder = new SimpleDecoder( explode);
String content;
// When...
content = "A,B,C";
// Then...
assertJsonNodes(
"Decoded",
decoder.decodeArray( content),
"[\"A\",\"B\",\"C\"]");
// When...
content = "1,,-2.34,";
// Then...
assertJsonNodes(
"Decoded",
arrayNodes( decoder.decodeArray( content)),
"[1,\"\",-2.34,\"\"]",
"[1,\"\",-2.34,null]",
"[1,\"\",\"-2.34\",\"\"]",
"[1,\"\",\"-2.34\",null]",
"[1,null,-2.34,\"\"]",
"[1,null,-2.34,null]",
"[1,null,\"-2.34\",\"\"]",
"[1,null,\"-2.34\",null]",
"[\"1\",\"\",-2.34,\"\"]",
"[\"1\",\"\",-2.34,null]",
"[\"1\",\"\",\"-2.34\",\"\"]",
"[\"1\",\"\",\"-2.34\",null]",
"[\"1\",null,-2.34,\"\"]",
"[\"1\",null,-2.34,null]",
"[\"1\",null,\"-2.34\",\"\"]",
"[\"1\",null,\"-2.34\",null]");
// When...
content = "";
// Then...
assertJsonNodes(
"Decoded",
arrayNodes( decoder.decodeArray( content)),
"[]");
// When...
content = "-2.34";
// Then...
assertJsonNodes(
"Decoded",
arrayNodes( decoder.decodeArray( content)),
"[-2.34]",
"[\"-2.34\"]");
}
@Test
public void whenValue()
{
// Given...
boolean explode = false;
SimpleDecoder decoder = new SimpleDecoder( explode);
String content;
// When...
content = "1.234";
// Then...
assertJsonNodes(
"Decoded",
decoder.decodeValue( content),
"1.234",
"\"1.234\"");
// When...
content = "true";
// Then...
assertJsonNodes(
"Decoded",
valueNodes( decoder.decodeValue( content)),
"true",
"\"true\"");
// When...
content = "";
// Then...
assertJsonNodes(
"Decoded",
valueNodes( decoder.decodeValue( content)),
"\"\"",
"null");
// When...
content = "Murgatroid";
// Then...
assertJsonNodes(
"Decoded",
valueNodes( decoder.decodeValue( content)),
"\"Murgatroid\"");
}
@Test
public void whenAny()
{
// Given...
boolean explode = false;
SimpleDecoder decoder = new SimpleDecoder( explode);
String content;
// When...
content = "A,2";
// Then...
assertJsonNodes(
"Decoded",
decoder.decode( content),
"{\"A\":2}",
"{\"A\":\"2\"}",
"[\"A\",2]",
"[\"A\",\"2\"]",
"\"A,2\"");
// When...
content = "true";
// Then...
assertJsonNodes(
"Decoded",
decoder.decode( content),
"[true]",
"[\"true\"]",
"true",
"\"true\"");
// When...
content = "";
// Then...
assertJsonNodes(
"Decoded",
decoder.decode( content),
"{}",
"[]",
"\"\"",
"null");
// When...
content = "Murgatroid";
// Then...
assertJsonNodes(
"Decoded",
decoder.decode( content),
"[\"Murgatroid\"]",
"\"Murgatroid\"");
}
@Test
public void whenBoolean()
{
// Given...
boolean explode = false;
SimpleDecoder decoder = new SimpleDecoder( explode);
String content;
Optional<JsonNode> jsonNode;
// When...
content = "true";
// Then...
jsonNode = decoder.decodeBoolean( content);
assertThat( "Boolean content", jsonNode.isPresent(), is( true));
assertThat( "BooleanNode", jsonNode.get().isBoolean(), is( true));
assertThat( "Value", jsonNode.get().asBoolean(), is( true));
// When...
content = "false";
// Then...
jsonNode = decoder.decodeBoolean( content);
assertThat( "Boolean content", jsonNode.isPresent(), is( true));
assertThat( "BooleanNode", jsonNode.get().isBoolean(), is( true));
assertThat( "Value", jsonNode.get().asBoolean(), is( false));
// When...
content = "?";
// Then...
jsonNode = decoder.decodeBoolean( content);
assertThat( "Boolean content", jsonNode.isPresent(), is( false));
// When...
content = "FALSE";
// Then...
jsonNode = decoder.decodeBoolean( content);
assertThat( "Boolean content", jsonNode.isPresent(), is( false));
// When...
content = null;
// Then...
jsonNode = decoder.decodeBoolean( content);
assertThat( "Boolean content", jsonNode.isPresent(), is( false));
// When...
content = "-1.23";
// Then...
jsonNode = decoder.decodeBoolean( content);
assertThat( "Boolean content", jsonNode.isPresent(), is( false));
}
@Test
public void whenNumber()
{
// Given...
boolean explode = false;
SimpleDecoder decoder = new SimpleDecoder( explode);
String content;
Optional<JsonNode> jsonNode;
// When...
content = "-1.234";
// Then...
jsonNode = decoder.decodeNumber( content);
assertThat( "Number content", jsonNode.isPresent(), is( true));
assertThat( "DecimalNode", jsonNode.get().isBigDecimal(), is( true));
assertThat( "Value", jsonNode.get().decimalValue(), is( new BigDecimal( content)));
// When...
content = "0.0";
// Then...
jsonNode = decoder.decodeNumber( content);
assertThat( "Number content", jsonNode.isPresent(), is( true));
assertThat( "DecimalNode", jsonNode.get().isBigDecimal(), is( true));
assertThat( "Value", jsonNode.get().decimalValue(), is( new BigDecimal( content)));
// When...
content = "1234";
// Then...
jsonNode = decoder.decodeNumber( content);
assertThat( "Number content", jsonNode.isPresent(), is( true));
assertThat( "BigIntegerNode", jsonNode.get().isBigInteger(), is( true));
assertThat( "Value", jsonNode.get().bigIntegerValue(), is( new BigInteger( content)));
// When...
content = "?";
// Then...
jsonNode = decoder.decodeNumber( content);
assertThat( "Number content", jsonNode.isPresent(), is( false));
// When...
content = "false";
// Then...
jsonNode = decoder.decodeNumber( content);
assertThat( "Number content", jsonNode.isPresent(), is( false));
// When...
content = null;
// Then...
jsonNode = decoder.decodeNumber( content);
assertThat( "Number content", jsonNode.isPresent(), is( false));
// When...
content = "0XA";
// Then...
jsonNode = decoder.decodeNumber( content);
assertThat( "Number content", jsonNode.isPresent(), is( false));
}
private void assertJsonNodes( String label, List<JsonNode> actual, String... expected)
{
assertThat(
label,
actual.stream().map( String::valueOf).toArray( String[]::new),
listsElements( expected));
}
private List<JsonNode> objectNodes( List<JsonNode> jsonNodes)
{
jsonNodes.stream()
.forEach( node -> {
assertThat( String.format( "'%s' is an object", node), node.isObject(), is( true));
});
return jsonNodes;
}
private List<JsonNode> arrayNodes( List<JsonNode> jsonNodes)
{
jsonNodes.stream()
.forEach( node -> {
assertThat( String.format( "'%s' is an array", node), node.isArray(), is( true));
});
return jsonNodes;
}
private List<JsonNode> valueNodes( List<JsonNode> jsonNodes)
{
jsonNodes.stream()
.forEach( node -> {
assertThat( String.format( "'%s' is a value", node), node.isValueNode(), is( true));
});
return jsonNodes;
}
}
|
package org.collectionspace.chain.storage;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.collectionspace.chain.controller.ChainServlet;
import org.collectionspace.chain.util.json.JSONUtils;
import org.collectionspace.bconfigutils.bootstrap.BootstrapConfigController;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import org.mortbay.jetty.testing.HttpTester;
import org.mortbay.jetty.testing.ServletTester;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestServiceThroughWebapp {
private String cookie;
private static final Logger log=LoggerFactory.getLogger(TestServiceThroughWebapp.class);
// XXX refactor
private InputStream getResource(String name) {
String path=getClass().getPackage().getName().replaceAll("\\.","/")+"/"+name;
return Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
}
// XXX refactor
private String getResourceString(String name) throws IOException {
InputStream in=getResource(name);
return IOUtils.toString(in,"UTF-8");
}
// XXX refactor
private UTF8SafeHttpTester jettyDo(ServletTester tester,String method,String path,String data_str) throws IOException, Exception {
UTF8SafeHttpTester out=new UTF8SafeHttpTester();
out.request(tester,method,path,data_str,cookie);
return out;
}
private void login(ServletTester tester) throws IOException, Exception {
UTF8SafeHttpTester out=jettyDo(tester,"GET","/chain/login?userid=test@collectionspace.org&password=testtest",null);
assertEquals(303,out.getStatus());
cookie=out.getHeader("Set-Cookie");
log.info("Got cookie "+cookie);
}
// XXX refactor into other copy of this method
private ServletTester setupJetty() throws Exception {
BootstrapConfigController config_controller=new BootstrapConfigController(null);
config_controller.addSearchSuffix("test-config-loader2.xml");
config_controller.go();
String base=config_controller.getOption("services-url");
ServletTester tester=new ServletTester();
tester.setContextPath("/chain");
/* clean up */
/* clean up */
|
package io.spine.tools.gradle.compiler.protoc;
import com.google.protobuf.Message;
/**
* Selects messages by a pattern.
*/
public interface FilePattern<T extends Message> extends Selector<T> {
/**
* Returns current file pattern.
*/
String getPattern();
}
|
package info.hossainkhan.dailynewsheadlines.browser;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v17.leanback.app.BackgroundManager;
import android.support.v17.leanback.app.BrowseFragment;
import android.support.v17.leanback.widget.ArrayObjectAdapter;
import android.support.v17.leanback.widget.DividerRow;
import android.support.v17.leanback.widget.HeaderItem;
import android.support.v17.leanback.widget.PresenterSelector;
import android.support.v17.leanback.widget.Row;
import android.support.v17.leanback.widget.SectionRow;
import android.support.v7.preference.PreferenceManager;
import android.util.DisplayMetrics;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import info.hossainkhan.android.core.headlines.HeadlinesContract;
import info.hossainkhan.android.core.headlines.HeadlinesPresenter;
import info.hossainkhan.android.core.model.CardItem;
import info.hossainkhan.android.core.model.CategoryNameResolver;
import info.hossainkhan.android.core.model.NavigationRow;
import info.hossainkhan.android.core.util.UiUtils;
import info.hossainkhan.dailynewsheadlines.R;
import info.hossainkhan.dailynewsheadlines.browser.listeners.CardItemViewInteractionListener;
import info.hossainkhan.dailynewsheadlines.browser.listeners.PicassoImageTarget;
import info.hossainkhan.dailynewsheadlines.cards.CardListRow;
import info.hossainkhan.dailynewsheadlines.cards.presenters.CardPresenterSelector;
import info.hossainkhan.dailynewsheadlines.cards.presenters.selectors.ShadowRowPresenterSelector;
import info.hossainkhan.dailynewsheadlines.settings.SettingsActivity;
import io.swagger.client.model.ArticleCategory;
import timber.log.Timber;
import static info.hossainkhan.dailynewsheadlines.utils.LeanbackHelper.buildNavigationDivider;
import static info.hossainkhan.dailynewsheadlines.utils.LeanbackHelper.buildNavigationHeader;
/**
* Leanback browser fragment that is responsible for showing all the headlines.
*/
public class HeadlinesBrowseFragment extends BrowseFragment implements HeadlinesContract.View {
private static final int BACKGROUND_UPDATE_DELAY = 300;
private final Handler mHandler = new Handler();
private ArrayObjectAdapter mRowsAdapter;
private Drawable mDefaultBackground;
private DisplayMetrics mMetrics;
private Timer mBackgroundTimer;
private URI mBackgroundURI;
private BackgroundManager mBackgroundManager;
private Target mBackgroundDrawableTarget;
private HeadlinesPresenter mHeadlinesPresenter;
private Resources mResources;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
Timber.i("onCreate");
super.onActivityCreated(savedInstanceState);
if(savedInstanceState == null) {
prepareEntranceTransition();
}
mResources = getResources();
prepareBackgroundManager();
setupUIElements();
mHeadlinesPresenter = new HeadlinesPresenter(this, getPreferredCategories());
}
private List<ArticleCategory> getPreferredCategories() {
ArrayList<ArticleCategory> supportedCategories = CategoryNameResolver.getSupportedCategories();
Timber.d("getPreferredCategories() - Supported Total: %s, %s", supportedCategories.size(),
supportedCategories);
Context context = getActivity().getApplicationContext();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
// FIXME - remove repeatative code.
if (!sharedPreferences.getBoolean(getString(R.string.prefs_key_content_category_sports), true)) {
supportedCategories.remove(ArticleCategory.sports);
}
if (!sharedPreferences.getBoolean(getString(R.string.prefs_key_content_category_technology), true)) {
supportedCategories.remove(ArticleCategory.technology);
}
if (!sharedPreferences.getBoolean(getString(R.string.prefs_key_content_category_business), true)) {
supportedCategories.remove(ArticleCategory.business);
}
if (!sharedPreferences.getBoolean(getString(R.string.prefs_key_content_category_top_headlines), true)) {
supportedCategories.remove(ArticleCategory.home);
}
Timber.d("getPreferredCategories() - Total: %s, %s", supportedCategories.size(), supportedCategories);
return supportedCategories;
}
@Override
public void onDestroy() {
super.onDestroy();
if (null != mBackgroundTimer) {
Timber.d("onDestroy: " + mBackgroundTimer.toString());
mBackgroundTimer.cancel();
}
}
private void loadRows(final List<NavigationRow> list) {
applyStaticNavigationItems(list);
mRowsAdapter = new ArrayObjectAdapter(new ShadowRowPresenterSelector());
int totalNavigationItems = list.size();
int i;
for (i = 0; i < totalNavigationItems; i++) {
NavigationRow navigationRow = list.get(i);
mRowsAdapter.add(createCardRow(navigationRow));
}
setAdapter(mRowsAdapter);
}
/**
* Adds static navigation items like Menu and settings to existing list of navigation.
* @param list
*/
private void applyStaticNavigationItems(final List<NavigationRow> list) {
// Prepare/inject additional items for the navigation
// TODO: This news source heading item should be dynamic once multiple news source is allowed
list.add(0, buildNavigationHeader(mResources, R.string.navigation_header_item_news_source_nytimes_title));
// Begin settings section
list.add(buildNavigationDivider());
list.add(buildNavigationHeader(mResources, R.string.navigation_header_item_settings_title));
// Build settings items
List<CardItem> settingsItems = new ArrayList<>();
CardItem item = new CardItem(CardItem.Type.ICON);
item.setId(R.string.settings_card_item_news_source_title);
item.setTitle(getString(R.string.settings_card_item_news_source_title));
item.setLocalImageResourceId(R.drawable.ic_settings_settings);
settingsItems.add(item);
list.add(new NavigationRow.Builder()
.setTitle(getString(R.string.settings_navigation_row_news_source_title))
.setType(NavigationRow.TYPE_DEFAULT)
.setCards(settingsItems)
.useShadow(false)
.build());
}
/**
* Creates appropriate {@link Row} item based on {@link NavigationRow} type.
*
* @param navigationRow Navigation row
* @return {@link Row}
*/
private Row createCardRow(final NavigationRow navigationRow) {
int navigationRowType = navigationRow.getType();
Timber.d("createCardRow() - Row type: %d", navigationRowType);
switch (navigationRowType) {
case NavigationRow.TYPE_SECTION_HEADER:
return new SectionRow(new HeaderItem(navigationRow.getTitle()));
case NavigationRow.TYPE_DIVIDER:
return new DividerRow();
case NavigationRow.TYPE_DEFAULT:
default:
// Build main row using the ImageCardViewPresenter.
PresenterSelector presenterSelector = new CardPresenterSelector(getActivity());
ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(presenterSelector);
for (CardItem card : navigationRow.getCards()) {
listRowAdapter.add(card);
}
HeaderItem header;
if(navigationRow.getCategory() != null) {
header = new HeaderItem(getString(CategoryNameResolver.resolveCategoryResId(navigationRow.getCategory())));
} else {
header = new HeaderItem(navigationRow.getTitle());
}
return new CardListRow(header, listRowAdapter, navigationRow);
}
}
private void prepareBackgroundManager() {
mBackgroundManager = BackgroundManager.getInstance(getActivity());
mBackgroundManager.attach(getActivity().getWindow());
mBackgroundDrawableTarget = new PicassoImageTarget(mBackgroundManager);
mDefaultBackground = mResources.getDrawable(R.drawable.default_background);
mMetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(mMetrics);
}
private void setupUIElements() {
// setBadgeDrawable(getActivity().getResources().getDrawable(
// R.drawable.videos_by_google_banner));
setTitle(getString(R.string.browse_title)); // Badge, when set, takes precedent
// over title
setHeadersState(HEADERS_ENABLED);
setHeadersTransitionOnBackEnabled(true);
// set fastLane (or headers) background color
setBrandColor(getResources().getColor(R.color.fastlane_background));
}
private void setupEventListeners() {
CardItemViewInteractionListener listener = new CardItemViewInteractionListener(mHeadlinesPresenter);
setOnItemViewClickedListener(listener);
setOnItemViewSelectedListener(listener);
}
protected void updateBackground(String uri) {
Timber.d("Updating background: %s", uri);
int width = mMetrics.widthPixels;
int height = mMetrics.heightPixels;
Picasso.with(getActivity())
.load(uri)
.resize(width, height)
.centerCrop()
.error(mDefaultBackground)
.into(mBackgroundDrawableTarget);
mBackgroundTimer.cancel();
}
private void startBackgroundTimer() {
if (null != mBackgroundTimer) {
mBackgroundTimer.cancel();
}
mBackgroundTimer = new Timer();
mBackgroundTimer.schedule(new HeadlinesBrowseFragment.UpdateBackgroundTask(), BACKGROUND_UPDATE_DELAY);
}
@Override
public void setLoadingIndicator(final boolean active) {
Timber.d("setLoadingIndicator() called with: active = [" + active + "]");
if (!active) {
startEntranceTransition();
}
}
@Override
public void showHeadlines(final List<NavigationRow> headlines) {
loadRows(headlines);
setupEventListeners();
}
@Override
public void showHeadlineDetailsUi(final CardItem cardItem) {
Timber.d("Load details view for item: %s", cardItem);
}
@Override
public void showLoadingHeadlinesError() {
UiUtils.showToast(getActivity(), "Unable to load headlines");
}
@Override
public void showNoHeadlines() {
Timber.d("showNoHeadlines() called");
}
@Override
public void showAppSettingsScreen() {
Intent intent = null;
intent = new Intent(getActivity().getBaseContext(), SettingsActivity.class);
startActivity(intent);
}
@Override
public void showHeadlineBackdropBackground(final URI imageURI) {
mBackgroundURI = imageURI;
Timber.d("Loading HD background URL: %s", mBackgroundURI);
startBackgroundTimer();
}
private class UpdateBackgroundTask extends TimerTask {
@Override
public void run() {
mHandler.post(() -> {
if (mBackgroundURI != null) {
updateBackground(mBackgroundURI.toString());
}
});
}
}
}
|
package edu.cornell.mannlib.vitro.webapp.controller.grefine;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties;
import edu.cornell.mannlib.vitro.webapp.controller.VitroHttpServlet;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyStatementDao;
import com.hp.hpl.jena.rdf.model.Literal;
/**
* This servlet is for servicing Google Refine's
* "Add columns from VIVO"'s search for individual properties.
* e.g. search for Joe Smith's email in VIVO and download to Google Refine under a new email column.
*
* @author Eliza Chan (elc2013@med.cornell.edu)
*
*/
public class GrefineMqlreadServlet extends VitroHttpServlet {
private static final long serialVersionUID = 1L;
private static final Log log = LogFactory.getLog(GrefineMqlreadServlet.class.getName());
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//resp.setContentType("application/json");
super.doPost(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
super.doGet(req, resp);
resp.setContentType("application/json");
VitroRequest vreq = new VitroRequest(req);
try {
if (vreq.getParameter("query") != null) {
JSONObject qJson = getResult(vreq, req, resp);
log.debug("result: " + qJson.toString());
String responseStr = (vreq.getParameter("callback") == null) ? qJson
.toString() : vreq.getParameter("callback") + "("
+ qJson.toString() + ")";
// System.out.println(responseStr);
ServletOutputStream out = resp.getOutputStream();
out.print(responseStr);
}
} catch (Exception ex) {
log.warn(ex, ex);
}
}
private JSONObject getResult(VitroRequest vreq, HttpServletRequest req,
HttpServletResponse resp) throws ServletException {
JSONObject resultAllJson = new JSONObject();
try {
// parse query
ArrayList<String> subjectUriList = new ArrayList<String>();
Map<String, JSONArray> propertyUriMap = new HashMap<String, JSONArray>();
String query = vreq.getParameter("query");
parseQuery(query, subjectUriList, propertyUriMap);
// run SPARQL query to get the results
JSONArray resultAllJsonArr = new JSONArray();
DataPropertyStatementDao dpsDao = vreq.getUnfilteredWebappDaoFactory().getDataPropertyStatementDao();
for (String subjectUri: subjectUriList) {
JSONObject subjectPropertyResultJson = new JSONObject();
subjectPropertyResultJson.put("id", subjectUri);
for (Map.Entry<String, JSONArray> entry : propertyUriMap.entrySet()) {
int limit = 200; // default
String propertyUri = entry.getKey();
JSONArray propertyUriOptions = entry.getValue();
for (int i=0; i<propertyUriOptions.length(); i++) {
JSONObject propertyUriOption = (JSONObject)propertyUriOptions.get(i);
limit = ((Integer)propertyUriOption.get("limit")).intValue();
}
List<Literal> literals = dpsDao.getDataPropertyValuesForIndividualByProperty(subjectUri, propertyUri);
// Make sure the subject has a value for this property
if (literals.size() > 0) {
int counter = 0;
JSONArray valueJsonArr = new JSONArray();
for (Literal literal: literals) {
if (counter <= limit) {
String value = literal.getLexicalForm();
valueJsonArr.put(value);
}
counter++;
}
subjectPropertyResultJson.put(propertyUri, valueJsonArr);
}
}
resultAllJsonArr.put(subjectPropertyResultJson);
}
resultAllJson.put("result", resultAllJsonArr);
} catch (JSONException e) {
log.error("GrefineMqlreadServlet getResult JSONException: " + e);
}
// System.out.println(resultAllJson);
return resultAllJson;
}
/**
* Construct json from query String
* @param query
* @param subjectUriList
* @param propertyUriMap
*/
private void parseQuery(String query, ArrayList<String> subjectUriList, Map<String, JSONArray> propertyUriMap) {
try {
JSONObject rawJson = new JSONObject(query);
JSONArray qJsonArr = rawJson.getJSONArray("query");
for (int i=0; i<qJsonArr.length(); i++) {
Object obj = qJsonArr.get(i);
if (obj instanceof JSONObject) {
JSONObject jsonObj = (JSONObject)obj;
JSONArray jsonObjNames = jsonObj.names();
for (int j=0; j<jsonObjNames.length(); j++) {
String objName = (String)jsonObjNames.get(j);
if (objName.contains("http://")) { // most likely this is a propertyUri
// e.g. http://weill.cornell.edu/vivo/ontology/wcmc#cwid
Object propertyUriObj = jsonObj.get(objName);
if (propertyUriObj instanceof JSONArray) {
propertyUriMap.put(objName, (JSONArray)propertyUriObj);
}
} else if ("id".equals(objName)) {
Object idObj = jsonObj.get(objName); // TODO: This is a String object but not sure what it is for
} else if ("id|=".equals(objName)) { // list of subject uri
Object subjectUriObj = jsonObj.get(objName);
if (subjectUriObj instanceof JSONArray) {
JSONArray subjectUriUriArr = (JSONArray)subjectUriObj;
for (int k=0; k<subjectUriUriArr.length(); k++) {
Object subjectUriUriObj = subjectUriUriArr.get(k);
if (subjectUriUriObj instanceof String) {
subjectUriList.add((String)subjectUriUriObj);
}
}
}
}
}
}
}
} catch (JSONException e) {
log.error("GrefineMqlreadServlet parseQuery JSONException: " + e);
}
}
}
|
package com.exedio.cope.lib;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import junit.framework.TestCase;
public class LibTest extends TestCase
{
final Type[] types = new Type[]
{
ItemWithSingleUnique.TYPE,
ItemWithSingleUniqueReadOnly.TYPE,
ItemWithSingleUniqueNotNull.TYPE,
ItemWithoutAttributes.TYPE,
ItemWithoutAttributes2.TYPE,
ItemWithManyAttributes.TYPE,
};
public LibTest()
{}
public void setUp()
{
Database.theInstance.createTables();
}
public void tearDown()
{
Database.theInstance.dropTables();
}
public void testLib()
{
// BEWARE:
// if something does not compile,
// it may be an error in the
// instrumentor as well.
dotestItemMethods();
dotestItemWithSingleUnique();
dotestItemWithSingleUniqueReadOnly();
dotestItemWithSingleNotNull();
dotestItemWithManyAttributes();
dotestContinuousPrimaryKeyGeneration();
}
/**
* type, ID, equals, hashCode
*/
private void dotestItemMethods()
{
assertEquals(ItemWithoutAttributes.TYPE, Type.getType(ItemWithoutAttributes.class.getName()));
assertEquals(ItemWithoutAttributes2.TYPE, Type.getType(ItemWithoutAttributes2.class.getName()));
assertEquals(toSet(Arrays.asList(types)), toSet(Type.getTypes()));
final ItemWithoutAttributes item1 = new ItemWithoutAttributes();
final ItemWithoutAttributes item2 = new ItemWithoutAttributes();
final ItemWithoutAttributes2 item3 = new ItemWithoutAttributes2();
assertEquals(ItemWithoutAttributes.TYPE, item1.getType());
assertEquals(ItemWithoutAttributes.TYPE, item2.getType());
assertEquals(ItemWithoutAttributes2.TYPE, item3.getType());
assertEquals(item1, Search.findByID(item1.getID()));
assertEquals(item2, Search.findByID(item2.getID()));
assertEquals(item3, Search.findByID(item3.getID()));
assertEquals(item1, item1);
assertEquals(item2, item2);
assertEquals(item3, item3);
assertFalse(item1.equals(null));
assertFalse(item2.equals(null));
assertFalse(item3.equals(null));
assertNotEquals(item1, item2);
assertNotEquals(item1, item3);
assertNotEquals(item2, item3);
assertFalse(item1.equals("hello"));
assertFalse(item1.equals(new Integer(1)));
assertFalse(item1.equals(Boolean.TRUE));
}
private void dotestItemWithSingleUnique()
{
assertEquals(null, ItemWithSingleUnique.findByUniqueString("uniqueString"));
final ItemWithSingleUnique item = new ItemWithSingleUnique();
assertEquals(null, item.getUniqueString());
assertEquals(null, item.findByUniqueString("uniqueString"));
try
{
item.setUniqueString("uniqueString");
}
catch(UniqueViolationException e)
{
throw new SystemException(e);
}
assertEquals("uniqueString", item.getUniqueString());
assertEquals(item, ItemWithSingleUnique.findByUniqueString("uniqueString"));
// test unique violation
{
final ItemWithSingleUnique item2 = new ItemWithSingleUnique();
try
{
item2.setUniqueString("uniqueString2");
}
catch(UniqueViolationException e)
{
throw new SystemException(e);
}
try
{
item2.setUniqueString("uniqueString");
fail("should have thrown UniqueViolationException");
}
catch(UniqueViolationException e)
{
assertEquals(list(item2.uniqueString), e.getConstraint().getUniqueAttributes());
}
assertEquals("uniqueString2", item2.getUniqueString());
assertEquals(item2, ItemWithSingleUnique.findByUniqueString("uniqueString2"));
}
item.passivate();
assertTrue(!item.isActive());
assertEquals("uniqueString", item.getUniqueString());
assertTrue(item.isActive());
final ItemWithSingleUnique firstFoundItem;
{
item.passivate();
assertTrue(!item.isActive());
final ItemWithSingleUnique foundItem = ItemWithSingleUnique.findByUniqueString("uniqueString");
assertEquals(item, foundItem);
assertEquals(item.getID(), foundItem.getID());
assertEquals(item.hashCode(), foundItem.hashCode());
assertNotSame(item, foundItem);
assertTrue(!item.isActive());
assertTrue(!foundItem.isActive());
assertSame(item, item.activeItem());
assertTrue(item.isActive());
assertTrue(!foundItem.isActive());
assertSame(item, foundItem.activeItem());
assertTrue(item.isActive());
assertTrue(!foundItem.isActive());
firstFoundItem = foundItem;
}
{
item.passivate();
assertTrue(!item.isActive());
final ItemWithSingleUnique foundItem = ItemWithSingleUnique.findByUniqueString("uniqueString");
assertEquals("uniqueString", foundItem.getUniqueString());
assertEquals("uniqueString", item.getUniqueString());
assertEquals(item, foundItem);
assertEquals(item.getID(), foundItem.getID());
assertEquals(item.hashCode(), foundItem.hashCode());
assertNotSame(item, foundItem);
assertNotSame(item, firstFoundItem);
assertNotSame(foundItem, firstFoundItem);
assertTrue(!item.isActive());
assertTrue(foundItem.isActive());
assertSame(foundItem, item.activeItem());
assertSame(foundItem, foundItem.activeItem());
}
}
private void dotestItemWithSingleUniqueReadOnly()
{
assertEquals(null, ItemWithSingleUniqueReadOnly.findByUniqueReadOnlyString("uniqueString"));
final ItemWithSingleUniqueReadOnly item;
try
{
item = new ItemWithSingleUniqueReadOnly("uniqueString");
}
catch(UniqueViolationException e)
{
throw new SystemException(e);
}
assertEquals("uniqueString", item.getUniqueReadOnlyString());
assertEquals(item, ItemWithSingleUniqueReadOnly.findByUniqueReadOnlyString("uniqueString"));
try
{
item.setAttribute(item.uniqueReadOnlyString, "zapp");
fail("should have thrown ReadOnlyViolationException");
}
catch(ReadOnlyViolationException e)
{
assertEquals(item.uniqueReadOnlyString, e.getReadOnlyAttribute());
assertEquals(item, e.getItem());
}
catch(ConstraintViolationException e)
{
throw new SystemException(e);
}
assertEquals("uniqueString", item.getUniqueReadOnlyString());
assertEquals(item, ItemWithSingleUniqueReadOnly.findByUniqueReadOnlyString("uniqueString"));
}
private void dotestItemWithSingleNotNull()
{
assertEquals(null, ItemWithSingleUniqueNotNull.findByUniqueNotNullString("uniqueString"));
assertEquals(null, ItemWithSingleUniqueNotNull.findByUniqueNotNullString("uniqueString2"));
final ItemWithSingleUniqueNotNull item;
try
{
item = new ItemWithSingleUniqueNotNull("uniqueString");
}
catch(UniqueViolationException e)
{
throw new SystemException(e);
}
catch(NotNullViolationException e)
{
throw new SystemException(e);
}
assertEquals("uniqueString", item.getUniqueNotNullString());
assertEquals(item, ItemWithSingleUniqueNotNull.findByUniqueNotNullString("uniqueString"));
assertEquals(null, ItemWithSingleUniqueNotNull.findByUniqueNotNullString("uniqueString2"));
try
{
item.setUniqueNotNullString("uniqueString2");
}
catch(UniqueViolationException e)
{
throw new SystemException(e);
}
catch(NotNullViolationException e)
{
throw new SystemException(e);
}
assertEquals("uniqueString2", item.getUniqueNotNullString());
assertEquals(null, ItemWithSingleUniqueNotNull.findByUniqueNotNullString("uniqueString"));
assertEquals(item, ItemWithSingleUniqueNotNull.findByUniqueNotNullString("uniqueString2"));
try
{
item.setUniqueNotNullString(null);
fail("should have thrown NotNullViolationException");
}
catch(UniqueViolationException e)
{
throw new SystemException(e);
}
catch(NotNullViolationException e)
{
assertEquals(item.uniqueNotNullString, e.getNotNullAttribute());
assertEquals(item, e.getItem());
}
assertEquals("uniqueString2", item.getUniqueNotNullString());
assertEquals(null, ItemWithSingleUniqueNotNull.findByUniqueNotNullString("uniqueString"));
assertEquals(item, ItemWithSingleUniqueNotNull.findByUniqueNotNullString("uniqueString2"));
}
private void dotestItemWithManyAttributes()
{
final ItemWithoutAttributes someItem = new ItemWithoutAttributes();
final ItemWithoutAttributes someItem2 = new ItemWithoutAttributes();
final ItemWithManyAttributes item;
try
{
item = new ItemWithManyAttributes("someString", 5, true, someItem);
}
catch(NotNullViolationException e)
{
throw new SystemException(e);
}
dotestItemWithManyAttributesSomeString(item);
dotestItemWithManyAttributesSomeNotNullString(item);
dotestItemWithManyAttributesSomeInteger(item);
dotestItemWithManyAttributesSomeNotNullInteger(item);
dotestUnmodifiableSearchResult(item);
dotestItemWithManyAttributesSomeBoolean(item);
dotestItemWithManyAttributesSomeNotNullBoolean(item);
dotestItemWithManyAttributesSomeItem(item, someItem);
dotestItemWithManyAttributesSomeNotNullItem(item, someItem, someItem2);
dotestItemWithManyAttributesSomeEnumeration(item);
// TODO: dotestItemWithManyAttributesSomeNotNullEnumeration(item);
dotestItemWithManyAttributesSomeMedia(item);
// TODO: dotestItemWithManyAttributesSomeNotNullMedia(item);
dotestItemWithManyAttributesSomeQualifiedAttribute(item, someItem);
}
private void dotestItemWithManyAttributesSomeString(final ItemWithManyAttributes item)
{
assertEquals(item.TYPE, item.someString.getType());
assertEquals(item.TYPE, item.someStringUpperCase.getType());
assertEquals(null, item.getSomeString());
assertEquals(null, item.getSomeStringUpperCase());
item.setSomeString("someString");
assertEquals("someString", item.getSomeString());
assertEquals("SOMESTRING", item.getSomeStringUpperCase());
assertEquals(set(item), toSet(Search.search(item.TYPE, Search.equal(item.someString, "someString"))));
assertEquals(set(), toSet(Search.search(item.TYPE, Search.equal(item.someString, "SOMESTRING"))));
assertEquals(set(item), toSet(Search.search(item.TYPE, Search.equal(item.someStringUpperCase, "SOMESTRING"))));
assertEquals(set(), toSet(Search.search(item.TYPE, Search.equal(item.someStringUpperCase, "someString"))));
item.passivate();
assertEquals("someString", item.getSomeString());
assertEquals("SOMESTRING", item.getSomeStringUpperCase());
item.setSomeString(null);
assertEquals(null, item.getSomeString());
assertEquals(null, item.getSomeStringUpperCase());
}
private void dotestItemWithManyAttributesSomeNotNullString(final ItemWithManyAttributes item)
{
assertEquals(item.TYPE, item.someNotNullString.getType());
assertEquals("someString", item.getSomeNotNullString());
try
{
item.setSomeNotNullString("someOtherString");
}
catch(NotNullViolationException e)
{
throw new SystemException(e);
}
assertEquals("someOtherString", item.getSomeNotNullString());
try
{
item.setSomeNotNullString(null);
}
catch(NotNullViolationException e)
{
assertEquals(item.someNotNullString, e.getNotNullAttribute());
assertEquals(item, e.getItem());
}
}
private void dotestItemWithManyAttributesSomeInteger(final ItemWithManyAttributes item)
{
assertEquals(item.TYPE, item.someInteger.getType());
assertEquals(null, item.getSomeInteger());
// TODO: assertEquals(list(item), Search.search(item.TYPE, Search.equal(item.someInteger, null)));
item.setSomeInteger(new Integer(10));
assertEquals(new Integer(10), item.getSomeInteger());
assertEquals(list(item), Search.search(item.TYPE, Search.equal(item.someInteger, 10)));
item.setSomeInteger(null);
assertEquals(null, item.getSomeInteger());
}
private void dotestItemWithManyAttributesSomeNotNullInteger(final ItemWithManyAttributes item)
{
assertEquals(item.TYPE, item.someNotNullInteger.getType());
assertEquals(5, item.getSomeNotNullInteger());
item.setSomeNotNullInteger(20);
assertEquals(20, item.getSomeNotNullInteger());
item.setSomeNotNullInteger(0);
assertEquals(0, item.getSomeNotNullInteger());
assertEquals(set(item), toSet(Search.search(item.TYPE, Search.equal(item.someNotNullInteger, 0))));
item.setSomeNotNullInteger(Integer.MIN_VALUE);
assertEquals(Integer.MIN_VALUE, item.getSomeNotNullInteger());
assertEquals(set(item), toSet(Search.search(item.TYPE, Search.equal(item.someNotNullInteger, Integer.MIN_VALUE))));
item.setSomeNotNullInteger(Integer.MAX_VALUE);
assertEquals(Integer.MAX_VALUE, item.getSomeNotNullInteger());
assertEquals(set(item), toSet(Search.search(item.TYPE, Search.equal(item.someNotNullInteger, Integer.MAX_VALUE))));
}
private void dotestUnmodifiableSearchResult(final ItemWithManyAttributes item)
{
item.setSomeNotNullInteger(0);
assertUnmodifiable(Search.search(item.TYPE, Search.equal(item.someNotNullInteger, 0)));
}
private void assertUnmodifiable(final Collection c)
{
try
{
c.add(new Object());
fail("should have thrown UnsupportedOperationException");
}
catch(UnsupportedOperationException e) {}
try
{
c.addAll(Collections.EMPTY_LIST);
fail("should have thrown UnsupportedOperationException");
}
catch(UnsupportedOperationException e) {}
try
{
c.clear();
fail("should have thrown UnsupportedOperationException");
}
catch(UnsupportedOperationException e) {}
try
{
c.remove(new Object());
fail("should have thrown UnsupportedOperationException");
}
catch(UnsupportedOperationException e) {}
try
{
c.removeAll(Collections.EMPTY_LIST);
fail("should have thrown UnsupportedOperationException");
}
catch(UnsupportedOperationException e) {}
try
{
c.retainAll(Collections.EMPTY_LIST);
fail("should have thrown UnsupportedOperationException");
}
catch(UnsupportedOperationException e) {}
final Iterator iterator = c.iterator();
try
{
iterator.remove();
fail("should have thrown UnsupportedOperationException");
}
catch(UnsupportedOperationException e) {}
}
private void dotestItemWithManyAttributesSomeBoolean(final ItemWithManyAttributes item)
{
assertEquals(item.TYPE, item.someBoolean.getType());
assertEquals(null, item.getSomeBoolean());
item.setSomeBoolean(Boolean.TRUE);
assertEquals(Boolean.TRUE, item.getSomeBoolean());
item.setSomeBoolean(Boolean.FALSE);
assertEquals(Boolean.FALSE, item.getSomeBoolean());
item.setSomeBoolean(null);
assertEquals(null, item.getSomeBoolean());
}
private void dotestItemWithManyAttributesSomeNotNullBoolean(final ItemWithManyAttributes item)
{
assertEquals(item.TYPE, item.someNotNullBoolean.getType());
assertEquals(true, item.getSomeNotNullBoolean());
item.setSomeNotNullBoolean(false);
assertEquals(false, item.getSomeNotNullBoolean());
}
private void dotestItemWithManyAttributesSomeItem(final ItemWithManyAttributes item, final ItemWithoutAttributes someItem)
{
assertEquals(item.TYPE, item.someItem.getType());
assertEquals(ItemWithoutAttributes.TYPE, item.someItem.getTargetType());
assertEquals(null, item.getSomeItem());
item.setSomeItem(someItem);
assertEquals(someItem, item.getSomeItem());
item.passivate();
assertEquals(someItem, item.getSomeItem());
item.setSomeItem(null);
assertEquals(null, item.getSomeItem());
}
private void dotestItemWithManyAttributesSomeNotNullItem(final ItemWithManyAttributes item, final ItemWithoutAttributes someItem, final ItemWithoutAttributes someItem2)
{
assertEquals(item.TYPE, item.someNotNullItem.getType());
assertEquals(ItemWithoutAttributes.TYPE, item.someNotNullItem.getTargetType());
assertEquals(someItem, item.getSomeNotNullItem());
try
{
item.setSomeNotNullItem(someItem2);
}
catch(NotNullViolationException e)
{
throw new SystemException(e);
}
assertEquals(someItem2, item.getSomeNotNullItem());
item.passivate();
assertEquals(someItem2, item.getSomeNotNullItem());
try
{
item.setSomeNotNullItem(null);
fail("should have thrown NotNullViolationException");
}
catch(NotNullViolationException e)
{
assertEquals(item, e.getItem());
assertEquals(item.someNotNullItem, e.getNotNullAttribute());
}
assertEquals(someItem2, item.getSomeNotNullItem());
}
private void dotestItemWithManyAttributesSomeEnumeration(final ItemWithManyAttributes item)
{
assertEquals(item.TYPE, item.someEnumeration.getType());
assertEquals(list(ItemWithManyAttributes.SomeEnumeration.enumValue1), item.someEnumeration.getValues());
assertEquals(ItemWithManyAttributes.SomeEnumeration.enumValue1, item.someEnumeration.getValue(ItemWithManyAttributes.SomeEnumeration.enumValue1NUM));
ItemWithManyAttributes.SomeEnumeration someEnumeration = item.getSomeEnumeration();
assertEquals(null, someEnumeration);
if(someEnumeration!=ItemWithManyAttributes.SomeEnumeration.enumValue1)
someEnumeration = ItemWithManyAttributes.SomeEnumeration.enumValue1;
switch(someEnumeration.number)
{
case ItemWithManyAttributes.SomeEnumeration.enumValue1NUM:
someEnumeration = ItemWithManyAttributes.SomeEnumeration.enumValue1;
break;
default:
throw new RuntimeException("Ooooops");
}
item.setSomeEnumeration(someEnumeration);
assertEquals(ItemWithManyAttributes.SomeEnumeration.enumValue1, item.getSomeEnumeration());
item.setSomeEnumeration(ItemWithManyAttributes.SomeEnumeration.enumValue1);
assertEquals(ItemWithManyAttributes.SomeEnumeration.enumValue1, item.getSomeEnumeration());
item.passivate();
assertEquals(ItemWithManyAttributes.SomeEnumeration.enumValue1, item.getSomeEnumeration());
item.setSomeEnumeration(null);
assertEquals(null, item.getSomeEnumeration());
}
private void dotestItemWithManyAttributesSomeMedia(final ItemWithManyAttributes item)
{
assertEquals(item.TYPE, item.someMedia.getType());
assertEquals(null, item.getSomeMediaURL());
assertEquals(null, item.getSomeMediaURLSomeVariant());
assertEquals(null, item.getSomeMediaData());
assertEquals(null, item.getSomeMediaMimeMajor());
assertEquals(null, item.getSomeMediaMimeMinor());
try
{
item.setSomeMediaData(null/*some data*/, "someMimeMajor", "someMimeMinor");
}
catch(IOException e)
{
throw new SystemException(e);
}
final String prefix = "/medias/com.exedio.cope.lib.ItemWithManyAttributes/someMedia/";
final String expectedURL = prefix+item.pk+".someMimeMajor.someMimeMinor";
final String expectedURLSomeVariant = prefix+"SomeVariant/"+item.pk+".someMimeMajor.someMimeMinor";
//System.out.println(expectedURL);
//System.out.println(item.getSomeMediaURL());
assertEquals(expectedURL, item.getSomeMediaURL());
assertEquals(expectedURLSomeVariant, item.getSomeMediaURLSomeVariant());
assertEquals(null/*somehow gets the data*/, item.getSomeMediaData());
assertEquals("someMimeMajor", item.getSomeMediaMimeMajor());
assertEquals("someMimeMinor", item.getSomeMediaMimeMinor());
item.passivate();
assertEquals(expectedURL, item.getSomeMediaURL());
assertEquals(expectedURLSomeVariant, item.getSomeMediaURLSomeVariant());
assertEquals(null/*somehow gets the data*/, item.getSomeMediaData());
assertEquals("someMimeMajor", item.getSomeMediaMimeMajor());
assertEquals("someMimeMinor", item.getSomeMediaMimeMinor());
assertMediaMime(item, "image", "jpeg", "jpg");
assertMediaMime(item, "image", "pjpeg", "jpg");
assertMediaMime(item, "image", "gif", "gif");
assertMediaMime(item, "image", "png", "png");
assertMediaMime(item, "image", "someMinor", "image.someMinor");
try
{
item.setSomeMediaData(null, null, null);
}
catch(IOException e)
{
throw new SystemException(e);
}
assertEquals(null, item.getSomeMediaURL());
assertEquals(null, item.getSomeMediaURLSomeVariant());
assertEquals(null, item.getSomeMediaData());
assertEquals(null, item.getSomeMediaMimeMajor());
assertEquals(null, item.getSomeMediaMimeMinor());
}
private void dotestItemWithManyAttributesSomeQualifiedAttribute(final ItemWithManyAttributes item, final ItemWithoutAttributes someItem)
{
assertEquals(item.TYPE, item.someQualifiedString.getType());
final ItemWithoutAttributes someItem2 = new ItemWithoutAttributes();
assertEquals(null, item.getSomeQualifiedString(someItem));
assertEquals(null, item.getSomeQualifiedString(someItem2));
item.setSomeQualifiedString(someItem, "someQualifiedValue");
assertEquals("someQualifiedValue", item.getSomeQualifiedString(someItem));
assertEquals("someQualifiedValue"/*null TODO*/, item.getSomeQualifiedString(someItem2));
item.passivate();
assertEquals("someQualifiedValue", item.getSomeQualifiedString(someItem));
assertEquals("someQualifiedValue"/*null TODO*/, item.getSomeQualifiedString(someItem2));
item.setSomeQualifiedString(someItem, null);
assertEquals(null, item.getSomeQualifiedString(someItem));
assertEquals(null, item.getSomeQualifiedString(someItem2));
}
private void dotestContinuousPrimaryKeyGeneration()
{
final ItemWithoutAttributes item1 = new ItemWithoutAttributes();
item1.TYPE.flushPK();
final ItemWithoutAttributes item2 = new ItemWithoutAttributes();
assertNotEquals(item1, item2);
}
private void assertMediaMime(final ItemWithManyAttributes item,
final String mimeMajor,
final String mimeMinor,
final String url)
{
try
{
item.setSomeMediaData(null/*some data*/, mimeMajor, mimeMinor);
}
catch(IOException e)
{
throw new SystemException(e);
}
final String prefix = "/medias/com.exedio.cope.lib.ItemWithManyAttributes/someMedia/";
final String expectedURL = prefix+item.pk+'.'+url;
final String expectedURLSomeVariant = prefix+"SomeVariant/"+item.pk+'.'+url;
//System.out.println(expectedURL);
//System.out.println(item.getSomeMediaURL());
assertEquals(expectedURL, item.getSomeMediaURL());
assertEquals(expectedURLSomeVariant, item.getSomeMediaURLSomeVariant());
//System.out.println(expectedURLSomeVariant);
//System.out.println(item.getSomeMediaURL());
assertEquals(null/*somehow gets the data*/, item.getSomeMediaData());
assertEquals(mimeMajor, item.getSomeMediaMimeMajor());
assertEquals(mimeMinor, item.getSomeMediaMimeMinor());
}
protected void assertNotEquals(final Item item1, final Item item2)
{
assertFalse(item1.equals(item2));
assertFalse(item2.equals(item1));
assertFalse(item1.getID().equals(item2.getID()));
assertFalse(item1.hashCode()==item2.hashCode());
}
protected Set toSet(final Collection collection)
{
return new HashSet(collection);
}
protected Set set()
{
return Collections.EMPTY_SET;
}
protected Set set(final Object o)
{
return Collections.singleton(o);
}
protected List list(final Object o)
{
return Collections.singletonList(o);
}
protected Object waitForKey(final Object o)
{
try
{
System.in.read();
}
catch(IOException e)
{
throw new SystemException(e);
}
return o;
}
}
|
package com.exedio.cope.lib;
public class SumTest extends DatabaseLibTest
{
SumItem item;
SumItem item2;
final static Integer i1 = new Integer(1);
final static Integer i2 = new Integer(2);
final static Integer i3 = new Integer(3);
final static Integer i4 = new Integer(4);
final static Integer i5 = new Integer(5);
final static Integer i6 = new Integer(6);
final static Integer i7 = new Integer(7);
final static Integer i8 = new Integer(8);
public void setUp() throws Exception
{
super.setUp();
item = new SumItem(1, 2, 3);
item2 = new SumItem(3, 4, 5);
}
public void tearDown() throws Exception
{
item2.delete();
item.delete();
super.tearDown();
}
public void testSum()
{
// test model
assertEquals(item.TYPE, item.sum12.getType());
assertEquals("sum12", item.sum12.getName());
// test normal operation
assertEquals(i1, item.getNum1());
assertEquals(i2, item.getNum2());
assertEquals(i3, item.getNum3());
assertEquals(set(item), toSet(Search.search(item.TYPE, Search.equal(item.num1, 1))));
assertEquals(set(item), toSet(Search.search(item.TYPE, Search.equal(item.num2, 2))));
assertEquals(set(item), toSet(Search.search(item.TYPE, Search.equal(item.num3, 3))));
assertEquals(i3, item.getSum12());
assertEquals(i4, item.getSum13());
assertEquals(i5, item.getSum23());
assertEquals(i6, item.getSum123());
assertEquals(set(item), toSet(Search.search(item.TYPE, Search.equal(item.sum12, 3))));
assertEquals(set(item), toSet(Search.search(item.TYPE, Search.equal(item.sum13, 4))));
assertEquals(set(item), toSet(Search.search(item.TYPE, Search.equal(item.sum23, 5))));
assertEquals(set(item), toSet(Search.search(item.TYPE, Search.equal(item.sum123, 6))));
assertEquals(set(item), toSet(Search.search(item.TYPE, Search.equal(item.sum12a3, 6))));
// test null propagation
item.setNum1(null);
assertEquals(null, item.getNum1());
assertEquals(i2, item.getNum2());
assertEquals(i3, item.getNum3());
assertEquals(set(item), toSet(Search.search(item.TYPE, Search.equal(item.num1, null))));
assertEquals(set(item), toSet(Search.search(item.TYPE, Search.equal(item.num2, 2))));
assertEquals(set(item), toSet(Search.search(item.TYPE, Search.equal(item.num3, 3))));
assertEquals(null, item.getSum12());
assertEquals(null, item.getSum13());
assertEquals(i5, item.getSum23());
assertEquals(null, item.getSum123());
assertEquals(set(item), toSet(Search.search(item.TYPE, Search.equal(item.sum12, null))));
assertEquals(set(item), toSet(Search.search(item.TYPE, Search.equal(item.sum13, null))));
assertEquals(set(item), toSet(Search.search(item.TYPE, Search.equal(item.sum23, 5))));
assertEquals(set(item), toSet(Search.search(item.TYPE, Search.equal(item.sum123, null))));
assertEquals(set(item), toSet(Search.search(item.TYPE, Search.equal(item.sum12a3, null))));
}
}
|
package imj2.tools;
import static java.awt.Color.RED;
import static java.awt.Color.YELLOW;
import static java.lang.Math.abs;
import static java.lang.Math.max;
import static net.sourceforge.aprog.swing.SwingTools.show;
import static net.sourceforge.aprog.tools.Tools.debugPrint;
import static net.sourceforge.aprog.tools.Tools.instances;
import static net.sourceforge.aprog.tools.Tools.unchecked;
import imj2.tools.Image2DComponent.Painter;
import imj2.tools.RegionShrinkingTest.AutoMouseAdapter;
import imj2.tools.RegionShrinkingTest.SimpleImageView;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseWheelEvent;
import java.awt.image.BufferedImage;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.aprog.tools.Factory.DefaultFactory;
import org.junit.Test;
/**
* @author codistmonk (creation 2014-02-07)
*/
public final class MultiresolutionSegmentationTest {
@Test
public final void test() {
final SimpleImageView imageView = new SimpleImageView();
new AutoMouseAdapter(imageView.getImageHolder()) {
private BufferedImage[] pyramid;
private int cellSize = 8;
private final Painter<SimpleImageView> painter = new Painter<SimpleImageView>() {
private Point[] particles;
{
imageView.getPainters().add(this);
}
@Override
public final void paint(final Graphics2D g, final SimpleImageView component,
final int width, final int height) {
refreshLODs();
final BufferedImage[] pyramid = getPyramid();
final int lodCount = pyramid.length;
final int s0 = getCellSize();
final int widthLOD0 = pyramid[0].getWidth();
final int heightLOD0 = pyramid[0].getHeight();
final boolean debugGradient = false;
if (debugGradient && s0 < lodCount) {
final int lod = s0;
debugPrint(lod);
final int dimensionMask = (-1) << lod;
final int w = widthLOD0 & dimensionMask;
final int h = heightLOD0 & dimensionMask;
final BufferedImage image = pyramid[lod];
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
try {
component.getBuffer().setRGB(x, y, gray888(getColorGradient(image, x >> lod, y >> lod)));
} catch (final Exception exception) {
debugPrint(x, y, x >> lod, y >> lod, image.getWidth(), image.getHeight());
throw unchecked(exception);
}
}
}
}
if (0 < s0) {
int startingLOD = -1;
for (int lod = lodCount - 1; 0 <= lod; --lod) {
final BufferedImage image = pyramid[lod];
final int w = image.getWidth();
final int h = image.getHeight();
final int diameter = 1 + 2 * lod;
for (int particleY = s0; particleY < h; particleY += s0) {
for (int particleX = s0; particleX < w; particleX += s0) {
if (startingLOD < 0) {
startingLOD = lod;
}
g.setColor(RED);
g.drawOval((particleX << lod) - lod, (particleY << lod) - lod, diameter, diameter);
}
}
}
{
debugPrint(startingLOD);
Grid grid = null;
for (int lod = startingLOD; 0 <= lod; --lod) {
grid = grid == null ? new Grid(pyramid[lod], s0) : grid.refine(pyramid[lod]);
}
if (grid != null) {
for (final Point vertex : grid.getVertices()) {
g.setColor(YELLOW);
g.drawOval(vertex.x - 1, vertex.y - 1, 3, 3);
}
}
}
}
}
/**
* {@value}.
*/
private static final long serialVersionUID = -8692596860025480748L;
};
@Override
public final void mouseWheelMoved(final MouseWheelEvent event) {
if (event.getWheelRotation() < 0 && 0 < this.getCellSize()) {
--this.cellSize;
imageView.refreshBuffer();
}
if (0 < event.getWheelRotation()) {
++this.cellSize;
imageView.refreshBuffer();
}
}
public final boolean refreshLODs() {
if (this.getPyramid() == null || this.getPyramid().length == 0 || this.getPyramid()[0] != imageView.getImage()) {
this.pyramid = makePyramid(imageView.getImage());
return true;
}
return false;
}
public final BufferedImage[] getPyramid() {
return this.pyramid;
}
public final int getCellSize() {
return this.cellSize;
}
@Override
protected final void cleanup() {
imageView.getPainters().remove(this.painter);
}
/**
* {@value}.
*/
private static final long serialVersionUID = 3954986726959359787L;
};
show(imageView, "Simple Image View", true);
}
/**
* @author codistmonk (creation 2014-02-21)
*/
public static final class Grid implements Serializable {
private final int cellSize;
private final int horizontalVertexCount;
private final int verticalVertexCount;
private final Point[] vertices;
public Grid(final BufferedImage image, final int cellSize) {
this(cellSize, 2 + (image.getWidth() - 1) / cellSize, 2 + (image.getHeight() - 1) / cellSize);
final int width = image.getWidth();
final int height = image.getHeight();
for (int i = 0, vertexIndex = 0; i < this.verticalVertexCount; ++i) {
for (int j = 0; j < this.horizontalVertexCount; ++j, ++vertexIndex) {
this.vertices[vertexIndex].setLocation(
j + 1 == this.horizontalVertexCount ? width - 1 : cellSize * j,
i + 1 == this.verticalVertexCount ? height - 1 : cellSize * i);
}
}
}
private Grid(final int cellSize, final int horizontalVertexCount, final int verticalVertexCount) {
this.cellSize = cellSize;
this.horizontalVertexCount = horizontalVertexCount;
this.verticalVertexCount = verticalVertexCount;
this.vertices = instances(this.horizontalVertexCount * this.verticalVertexCount,
DefaultFactory.forClass(Point.class));
}
public final int getHorizontalVertexCount() {
return this.horizontalVertexCount;
}
public final int getVerticalVertexCount() {
return this.verticalVertexCount;
}
public final Point[] getVertices() {
return this.vertices;
}
public final Point getVertex(final int verticalIndex, final int horizontalIndex) {
return this.getVertices()[verticalIndex * this.getHorizontalVertexCount() + horizontalIndex];
}
public final Grid refine(final BufferedImage image) {
final Grid result = new Grid(this.cellSize,
this.getHorizontalVertexCount() * 2 - 1, this.getVerticalVertexCount() * 2 - 1);
final int width = image.getWidth();
final int height = image.getHeight();
for (int i = 0; i < this.getVerticalVertexCount(); ++i) {
final int ii = i * 2;
for (int j = 0; j < this.getHorizontalVertexCount(); ++j) {
final int jj = j * 2;
final Point thisVertex = this.getVertex(i, j);
final Point thatVertex = result.getVertex(ii, jj);
thatVertex.setLocation(
j + 1 == this.getHorizontalVertexCount() ? width - 1 : thisVertex.x * 2,
i + 1 == this.getVerticalVertexCount() ? height - 1 : thisVertex.y * 2);
final Point westVertex = 0 < j ? result.getVertex(ii, jj - 2) : null;
final Point northVertex = 0 < i ? result.getVertex(ii - 2, jj) : null;
final Point northWestVertex = northVertex != null && westVertex != null ? result.getVertex(ii - 2, jj - 2) : null;
if (westVertex != null) {
result.getVertex(ii, jj - 1).setLocation(
(thatVertex.x + westVertex.x) / 2, (thatVertex.y + westVertex.y) / 2);
}
if (northVertex != null) {
result.getVertex(ii - 1, jj).setLocation(
(thatVertex.x + northVertex.x) / 2, (thatVertex.y + northVertex.y) / 2);
}
if (northWestVertex != null) {
result.getVertex(ii - 1, jj - 1).setLocation(
(thatVertex.x + westVertex.x + northVertex.x + northWestVertex.x) / 4,
(thatVertex.y + westVertex.y + northVertex.y + northWestVertex.y) / 4);
}
}
}
if (true) {
return result;
}
for (int i = 0, vertexIndex = 0; i < result.getVerticalVertexCount(); ++i) {
for (int j = 0; j < result.getHorizontalVertexCount(); ++j, ++vertexIndex) {
// if (i == 0) {
// result.getVertices()[vertexIndex].setLocation(j + 1 == result.getHorizontalVertexCount() ? width - 1 : this.cellSize * j, 0);
// } else if (j == 0) {
// result.getVertices()[vertexIndex].setLocation(0, i + 1 == result.getVerticalVertexCount() ? height - 1 : this.cellSize * i);
// } else if (j + 1 == result.getHorizontalVertexCount() - 1) {
// result.getVertices()[vertexIndex].setLocation(width - 1, i + 1 == result.getVerticalVertexCount() ? height - 1 : this.cellSize * i);
// } else if (i + 1 == result.getVerticalVertexCount() - 1) {
// result.getVertices()[vertexIndex].setLocation(j + 1 == result.getHorizontalVertexCount() ? width - 1 : this.cellSize * j, height - 1);
final int x;
final int y;
if (i == 0) {
y = 0;
if (j == 0) {
x = 0;
} else if (j + 1 == result.getVerticalVertexCount()) {
x = width - 1;
} else if (isEven(j)) {
x = this.getVertices()[0 * this.getHorizontalVertexCount() + j / 2].x * 2;
} else {
x = this.getVertices()[0 * this.getHorizontalVertexCount() + (j - 1) / 2].x +
this.getVertices()[0 * this.getHorizontalVertexCount() + (j + 1) / 2].x;
}
} else if (i + 1 == result.getVerticalVertexCount()) {
y = height - 1;
// } else if (isEven(i)) {
// y = this.getVertices()[(i / 2) * this.getHorizontalVertexCount() + j / 2].y * 2;
}
if (i != 0 && i + 1 != result.getVerticalVertexCount() && isEven(i) && j != 0 && j + 1 != result.getHorizontalVertexCount() && isEven(j)) {
final Point thisVertex = this.getVertices()[(i / 2) * this.getHorizontalVertexCount() + j / 2];
result.getVertices()[vertexIndex].setLocation(thisVertex.x * 2, thisVertex.y * 2);
} else {
result.getVertices()[vertexIndex].setLocation(
j + 1 == result.getHorizontalVertexCount() ? width - 1 : this.cellSize * j,
i + 1 == result.getVerticalVertexCount() ? height - 1 : this.cellSize * i);
}
}
}
return result;
}
/**
* {@value}.
*/
private static final long serialVersionUID = -6546839284908468675L;
public static final boolean isEven(final int n) {
return (n & 1) == 0;
}
}
public static final int MAXIMUM_COLOR_DISTANCE = getColorDistance(0x00000000, 0x00FFFFFF);
public static final int gray888(final int value8) {
return value8 | (value8 << 8) | (value8 << 16);
}
public static final int getColorGradient(final BufferedImage image, final int x, final int y) {
final int maxX = image.getWidth() - 1;
final int maxY = image.getHeight() - 1;
final int rgb = image.getRGB(x, y);
int result = 0;
if (0 < x) {
if (0 < y) {
result = max(result, getColorDistance(rgb, image.getRGB(x - 1, y - 1)));
}
if (y < maxY) {
result = max(result, getColorDistance(rgb, image.getRGB(x - 1, y + 1)));
}
}
if (x < maxX) {
if (0 < y) {
result = max(result, getColorDistance(rgb, image.getRGB(x + 1, y - 1)));
}
if (y < maxY) {
result = max(result, getColorDistance(rgb, image.getRGB(x + 1, y + 1)));
}
}
return result * 255 / MAXIMUM_COLOR_DISTANCE;
}
public static final int getColorDistance(final int rgb1, final int rgb2) {
return abs(red8(rgb1) - red8(rgb2)) + abs(green8(rgb1) - green8(rgb2)) + abs(blue8(rgb1) - blue8(rgb2));
}
public static final BufferedImage[] makePyramid(final BufferedImage lod0) {
final List<BufferedImage> lods = new ArrayList<BufferedImage>();
BufferedImage lod = lod0;
int w = lod.getWidth();
int h = lod.getHeight();
do {
lods.add(lod);
final BufferedImage nextLOD = new BufferedImage(w /= 2, h /= 2, lod.getType());
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
final int c00 = lod.getRGB(2 * x + 0, 2 * y + 0);
final int c10 = lod.getRGB(2 * x + 1, 2 * y + 0);
final int c01 = lod.getRGB(2 * x + 0, 2 * y + 1);
final int c11 = lod.getRGB(2 * x + 1, 2 * y + 1);
nextLOD.setRGB(x, y,
mean(red(c00), red(c10), red(c01), red(c11)) |
mean(green(c00), green(c10), green(c01), green(c11)) |
mean(blue(c00), blue(c10), blue(c01), blue(c11)));
}
}
lod = nextLOD;
} while (1 < w && 1 < h);
return lods.toArray(new BufferedImage[0]);
}
public static final int red8(final int rgb) {
return red(rgb) >> 16;
}
public static final int green8(final int rgb) {
return green(rgb) >> 8;
}
public static final int blue8(final int rgb) {
return blue(rgb);
}
public static final int red(final int rgb) {
return rgb & 0x00FF0000;
}
public static final int green(final int rgb) {
return rgb & 0x0000FF00;
}
public static final int blue(final int rgb) {
return rgb & 0x000000FF;
}
public static final int mean(final int... values) {
int sum = 0;
for (final int value : values) {
sum += value;
}
return 0 < values.length ? sum / values.length : 0;
}
}
|
import static org.junit.Assert.assertEquals;
import org.junit.BeforeClass;
import org.junit.Test;
import coeur.*;
import java.util.concurrent.*;
import javax.swing.SwingUtilities;
import javafx.embed.swing.JFXPanel;
public class TestEtats
{
private static Controleur controleur = Controleur.getInstance();
private static GraphiqueACoeurImpl instance = GraphiqueACoeurImpl.getInstance();
@Test
public void testEtatMenu()
{
instance.choixDemarrerSimul();
assertEquals(controleur.getEtatActuel(), EtatMenu.getInstance());
}
@Test
public void testChoixBillet()
{
controleur.modifEtat(EtatMenu.getInstance());
instance.choixBillet();
assertEquals(controleur.getEtatActuel(), EtatChoixBillet.getInstance());
}
@Test
public void testChoixValider()
{
controleur.modifEtat(EtatDemandeRecu.getInstance());
instance.choixOui();
assertEquals(controleur.getEtatActuel(), EtatImpressionRecu.getInstance());
}
}
|
package org.doube.util;
import ij.IJ;
import ij.ImagePlus;
import ij.ImageStack;
import ij.measure.Calibration;
import ij.plugin.ClassChecker;
import ij.process.ImageStatistics;
/**
* Check if an image conforms to the type defined by each method.
*
* @author Michael Doube
*
*/
public class ImageCheck {
/**
* Minimal ImageJ version required by BoneJ
*/
public static final String requiredIJVersion = "1.49u";
/**
* ImageJ releases known to produce errors or bugs with BoneJ. Daily builds
* are not included.
*/
public static final String[] blacklistedIJVersions = {
// introduced bug where ROIs added to the ROI Manager
// lost their z-position information
"1.48a" };
/**
* Check if image is binary
*
* @param imp
* @return true if image is binary
*/
public static boolean isBinary(final ImagePlus imp) {
if (imp == null) {
IJ.error("Image is null");
return false;
}
if (imp.getType() != ImagePlus.GRAY8) {
return false;
}
final ImageStatistics stats = imp.getStatistics();
return stats.histogram[0] + stats.histogram[255] == stats.pixelCount;
}
/**
* Check if an image is a multi-slice image stack
*
* @param imp
* @return true if the image has >= 2 slices
*/
public static boolean isMultiSlice(final ImagePlus imp) {
if (imp == null) {
IJ.noImage();
return false;
}
if (imp.getStackSize() < 2)
return false;
return true;
}
/**
* Check if the image's voxels are isotropic in all 3 dimensions (i.e. are
* placed on a cubic grid)
*
* @param imp
* image to test
* @param tolerance
* tolerated fractional deviation from equal length
* @return true if voxel width == height == depth
*/
public static boolean isVoxelIsotropic(final ImagePlus imp, final double tolerance) {
if (imp == null) {
IJ.error("No image", "Image is null");
return false;
}
final Calibration cal = imp.getCalibration();
final double vW = cal.pixelWidth;
final double vH = cal.pixelHeight;
final double tLow = 1 - tolerance;
final double tHigh = 1 + tolerance;
final double widthHeightRatio = vW > vH ? vW / vH : vH / vW;
final boolean isStack = (imp.getStackSize() > 1);
if (widthHeightRatio < tLow || widthHeightRatio > tHigh) {
return false;
}
if (!isStack) {
return true;
}
final double vD = cal.pixelDepth;
final double widthDepthRatio = vW > vD ? vW / vD : vD / vW;
return (widthDepthRatio >= tLow && widthDepthRatio <= tHigh);
}
/**
* Run isVoxelIsotropic() with a default tolerance of 0%
*
* @param imp
* input image
* @return false if voxel dimensions are not equal
*/
public static boolean isVoxelIsotropic(final ImagePlus imp) {
return isVoxelIsotropic(imp, 0.0);
}
/**
* Check that the voxel thickness is correct
*
* @param imp
* @return voxel thickness based on DICOM header information. Returns -1 if
* there is no DICOM slice position information.
*/
public static double dicomVoxelDepth(final ImagePlus imp) {
if (imp == null) {
IJ.error("Cannot check DICOM header of a null image");
return -1;
}
final Calibration cal = imp.getCalibration();
final double vD = cal.pixelDepth;
final int stackSize = imp.getStackSize();
String position = getDicomAttribute(imp, 1, "0020,0032");
if (position == null) {
IJ.log("No DICOM slice position data");
return -1;
}
String[] xyz = position.split("\\\\");
double first = 0;
if (xyz.length == 3) // we have 3 values
first = Double.parseDouble(xyz[2]);
else
return -1;
position = getDicomAttribute(imp, stackSize, "0020,0032");
xyz = position.split("\\\\");
double last = 0;
if (xyz.length == 3) // we have 3 values
last = Double.parseDouble(xyz[2]);
else
return -1;
final double sliceSpacing = (Math.abs(last - first) + 1) / stackSize;
final String units = cal.getUnits();
final double error = Math.abs((sliceSpacing - vD) / sliceSpacing) * 100.0;
if (Double.compare(vD, sliceSpacing) != 0) {
IJ.log(imp.getTitle() + ":\n" + "Current voxel depth disagrees by " + error
+ "% with DICOM header slice spacing.\n" + "Current voxel depth: " + IJ.d2s(vD, 6) + " " + units
+ "\n" + "DICOM slice spacing: " + IJ.d2s(sliceSpacing, 6) + " " + units + "\n"
+ "Updating image properties...");
cal.pixelDepth = sliceSpacing;
imp.setCalibration(cal);
} else
IJ.log(imp.getTitle() + ": Voxel depth agrees with DICOM header.\n");
return sliceSpacing;
}
/**
* Get the value associated with a DICOM tag from an ImagePlus header
*
* @param imp
* @param slice
* @param tag
* , in 0000,0000 format.
* @return the value associated with the tag
*/
private static String getDicomAttribute(final ImagePlus imp, final int slice, final String tag) {
final ImageStack stack = imp.getImageStack();
final String header = stack.getSliceLabel(slice);
// tag must be in format 0000,0000
if (slice < 1 || slice > stack.getSize()) {
return null;
}
if (header == null) {
return null;
}
String attribute = " ";
String value = " ";
final int idx1 = header.indexOf(tag);
final int idx2 = header.indexOf(":", idx1);
final int idx3 = header.indexOf("\n", idx2);
if (idx1 >= 0 && idx2 >= 0 && idx3 >= 0) {
try {
attribute = header.substring(idx1 + 9, idx2);
attribute = attribute.trim();
value = header.substring(idx2 + 1, idx3);
value = value.trim();
// IJ.log("tag = " + tag + ", attribute = " + attribute
// + ", value = " + value);
} catch (final Throwable e) {
return " ";
}
}
return value;
}
/**
* Checks if the version of ImageJ is compatible with BoneJ
*
* @return false if the IJ version is too old or blacklisted
*/
public static boolean checkIJVersion() {
if (isIJVersionBlacklisted()) {
IJ.error("Bad ImageJ version",
"The version of ImageJ you are using (v" + IJ.getVersion()
+ ") is known to run BoneJ incorrectly.\n"
+ "Please up- or downgrade your ImageJ using Help-Update ImageJ.");
return false;
}
if (requiredIJVersion.compareTo(IJ.getVersion()) > 0) {
IJ.error("Update ImageJ", "You are using an old version of ImageJ, v" + IJ.getVersion() + ".\n"
+ "Please update to at least ImageJ v" + requiredIJVersion + " using Help-Update ImageJ.");
return false;
}
return true;
}
/** Returns true if the environment has everything BoneJ needs ot run */
public static boolean checkEnvironment() {
try {
Class.forName("ij3d.ImageJ3DViewer");
} catch (final ClassNotFoundException e) {
IJ.showMessage("ImageJ 3D Viewer is not installed.\n" + "Please install and run the ImageJ 3D Viewer.");
return false;
}
return checkIJVersion();
}
/**
* Check that IJ has enough memory to do the job
*
* @param memoryRequirement
* Estimated required memory
* @return True if there is enough memory or if the user wants to continue.
* False if the user wants to continue despite a risk of
* insufficient memory
*/
public static boolean checkMemory(final long memoryRequirement) {
if (memoryRequirement > IJ.maxMemory()) {
final String message = "You might not have enough memory to run this job.\n" + "Do you want to continue?";
if (IJ.showMessageWithCancel("Memory Warning", message))
return true;
return false;
}
return true;
}
public static boolean checkMemory(final ImagePlus imp, final double ratio) {
double size = ((double) imp.getWidth() * imp.getHeight() * imp.getStackSize());
switch (imp.getType()) {
case ImagePlus.GRAY8:
case ImagePlus.COLOR_256:
break;
case ImagePlus.GRAY16:
size *= 2.0;
break;
case ImagePlus.GRAY32:
size *= 4.0;
break;
case ImagePlus.COLOR_RGB:
size *= 4.0;
break;
}
final long memoryRequirement = (long) (size * ratio);
return checkMemory(memoryRequirement);
}
/**
* Guess whether an image is Hounsfield unit calibrated
*
* @param imp
* @return true if the image might be HU calibrated
*/
public static boolean huCalibrated(final ImagePlus imp) {
final Calibration cal = imp.getCalibration();
final double[] coeff = cal.getCoefficients();
if (!cal.calibrated() || cal == null || (cal.getCValue(0) == 0 && coeff[1] == 1)
|| (cal.getCValue(0) == Short.MIN_VALUE && coeff[1] == 1))
return false;
return true;
}
/**
* Check if the version of IJ has been blacklisted as a known broken release
*
* @return true if the IJ version is blacklisted, false otherwise
*/
public static boolean isIJVersionBlacklisted() {
for (final String version : blacklistedIJVersions) {
if (version.equals(IJ.getVersion()))
return true;
}
return false;
}
}
|
/*
Reverses an array of ints.
*/
public class ArrayReverser
{
public static void main(String[] args)
{
java.util.Scanner gets = new java.util.Scanner(System.in);
System.out.println("Enter a set of numbers with each number separated by a space.");
//Get input and split into an array of Strings, splitInput.
String input = gets.nextLine();
String[] splitInput = input.split(" ");
int[] integers = new int[splitInput.length];
//Copy int values of splitInput into integers.
for (int i = 0; i < splitInput.length; i++)
{
try
{
integers[i] = Integer.parseInt(splitInput[i]);
}
catch (java.lang.NumberFormatException e) {
System.out.println("Invalid input. Exiting...");
System.exit(0);
}
}
for (int x : reverseArray(integers))
{
System.out.print(x + " ");
}
System.out.println();
}
static int[] reverseArray(int[] original)
{
int[] reversed = new int[original.length];
for (int i = 0; i < original.length; i++)
{
//(original.length - 1) must be used because arrays are 0-indexed, but <Array>.length is not.
reversed[i] = original[(original.length - 1) - i];
}
return reversed;
}
}
|
package io.spark.ddf;
import com.google.gson.Gson;
import io.ddf.DDF;
import io.ddf.DDFManager;
import io.ddf.exception.DDFException;
import io.spark.ddf.util.SparkUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.spark.SparkContext;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.sql.hive.HiveContext;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//import shark.SharkEnv;
//import shark.api.JavaSharkContext;
/**
* An Apache-Spark-based implementation of DDFManager
*/
public class SparkDDFManager extends DDFManager {
@Override
public String getEngine() {
return "spark";
}
private static final String DEFAULT_SPARK_APPNAME = "DDFClient";
private static final String DEFAULT_SPARK_MASTER = "local[4]";
public SparkDDFManager(SparkContext sparkContext) throws DDFException {
this.initialize(sparkContext, null);
}
/**
* Use system environment variables to configure the SparkContext creation.
*
* @throws DDFException
*/
public SparkDDFManager() throws DDFException {
this.initialize(null, new HashMap<String, String>());
}
public SparkDDFManager(Map<String, String> params) throws DDFException {
this.initialize(null, params);
}
private void initialize(SparkContext sparkContext, Map<String, String> params) throws DDFException {
this.setSparkContext(sparkContext == null ? this.createSparkContext(params) : sparkContext);
this.mHiveContext = new HiveContext(this.mSparkContext);
String compression = System.getProperty("spark.sql.inMemoryColumnarStorage.compressed", "true");
String batchSize = System.getProperty("spark.sql.inMemoryColumnarStorage.batchSize", "1000");
this.mHiveContext.setConf("spark.sql.inMemoryColumnarStorage.compressed", compression);
this.mHiveContext.setConf("spark.sql.inMemoryColumnarStorage.batchSize", batchSize);
}
public String getDDFEngine() {
return "spark";
}
private SparkContext mSparkContext;
private JavaSparkContext mJavaSparkContext;
public SparkContext getSparkContext() {
return mSparkContext;
}
private void setSparkContext(SparkContext sparkContext) {
this.mSparkContext = sparkContext;
}
private HiveContext mHiveContext;
public HiveContext getHiveContext() {
return mHiveContext;
}
// private SparkUtils.createSharkContext mSharkContext;
// public SharkContext getSharkContext() {
// return mSharkContext;
// private JavaSharkContext mJavaSharkContext;
// public JavaSharkContext getJavaSharkContext() {
// return mJavaSharkContext;
// public void setJavaSharkContext(JavaSharkContext javaSharkContext) {
// this.mJavaSharkContext = javaSharkContext;
/**
* Also calls setSparkContext() to the same sharkContext
*
* @param sharkContext
*/
// private void setSharkContext(SharkContext sharkContext) {
// this.mSharkContext = sharkContext;
// this.setSparkContext(sharkContext);
private Map<String, String> mSparkContextParams;
public Map<String, String> getSparkContextParams() {
return mSparkContextParams;
}
private void setSparkContextParams(Map<String, String> mSparkContextParams) {
this.mSparkContextParams = mSparkContextParams;
}
public void shutdown() {
if (this.getSparkContext() != null) {
this.getSparkContext().stop();
}
}
private static final String[][] SPARK_ENV_VARS = new String[][] {
// @formatter:off
{ "SPARK_APPNAME", "spark.appname" },
{ "SPARK_MASTER", "spark.master" },
{ "SPARK_HOME", "spark.home" },
{ "SPARK_SERIALIZER", "spark.kryo.registrator" },
{ "HIVE_HOME", "hive.home" },
{ "HADOOP_HOME", "hadoop.home" },
{ "DDFSPARK_JAR", "ddfspark.jar" }
// @formatter:on
};
/**
* Takes an existing params map, and reads both environment as well as system property settings to merge into it. The
* merge priority is as follows: (1) already set in params, (2) in system properties (e.g., -Dspark.home=xxx), (3) in
* environment variables (e.g., export SPARK_HOME=xxx)
*
* @param params
* @return
*/
private Map<String, String> mergeSparkParamsFromSettings(Map<String, String> params) {
if (params == null) params = new HashMap<String, String>();
Map<String, String> env = System.getenv();
for (String[] varPair : SPARK_ENV_VARS) {
if (params.containsKey(varPair[0])) continue; // already set in params
// Read setting either from System Properties, or environment variable.
// Env variable has lower priority if both are set.
String value = System.getProperty(varPair[1], env.get(varPair[0]));
if (value != null && value.length() > 0) params.put(varPair[0], value);
}
// Some well-known defaults
if (!params.containsKey("SPARK_MASTER")) params.put("SPARK_MASTER", DEFAULT_SPARK_MASTER);
if (!params.containsKey("SPARK_APPNAME")) params.put("SPARK_APPNAME", DEFAULT_SPARK_APPNAME);
params.put("SPARK_SERIALIZER", "io.spark.content.KryoRegistrator");
Gson gson = new Gson();
mLog.info(String.format(">>>>>>> params = %s", gson.toJson(params)));
return params;
}
/**
* Side effect: also sets SharkContext and SparkContextParams in case the client wants to examine or use those.
*
* @param params
* @return
* @throws DDFException
*/
private SparkContext createSparkContext(Map<String, String> params) throws DDFException {
this.setSparkContextParams(this.mergeSparkParamsFromSettings(params));
String ddfSparkJar = params.get("DDFSPARK_JAR");
String[] jobJars = ddfSparkJar != null ? ddfSparkJar.split(",") : new String[] { };
mLog.info(">>>>> ddfSparkJar = " + ddfSparkJar);
for (String key : params.keySet()) {
mLog.info(">>>> key = " + key + ", value = " + params.get(key));
}
SparkContext context = SparkUtils.createSparkContext(params.get("SPARK_MASTER"), params.get("SPARK_APPNAME"),
params.get("SPARK_HOME"), jobJars, params);
this.mSparkContext = context;
this.mJavaSparkContext = new JavaSparkContext(context);
return this.getSparkContext();
}
public DDF loadTable(String fileURL, String fieldSeparator) throws DDFException {
JavaRDD<String> fileRDD = mJavaSparkContext.textFile(fileURL);
String[] metaInfos = getMetaInfo(fileRDD, fieldSeparator);
SecureRandom rand = new SecureRandom();
String tableName = "tbl" + String.valueOf(Math.abs(rand.nextLong()));
String cmd = "CREATE TABLE " + tableName + "(" + StringUtils.join(metaInfos, ", ")
+ ") ROW FORMAT DELIMITED FIELDS TERMINATED BY '" + fieldSeparator + "'";
sql2txt(cmd);
sql2txt("LOAD DATA LOCAL INPATH '" + fileURL + "' " +
"INTO TABLE " + tableName);
return sql2ddf("SELECT * FROM " + tableName);
}
/**
* Given a String[] vector of data values along one column, try to infer what the data type should be.
* <p/>
* TODO: precompile regex
*
* @param vector
* @return string representing name of the type "integer", "double", "character", or "logical" The algorithm will
* first scan the vector to detect whether the vector contains only digits, ',' and '.', <br>
* if true, then it will detect whether the vector contains '.', <br>
* if true then the vector is double else it is integer <br>
* if false, then it will detect whether the vector contains only 'T' and 'F' <br>
* if true then the vector is logical, otherwise it is characters
*/
public static String determineType(String[] vector, Boolean doPreferDouble) {
boolean isNumber = true;
boolean isInteger = true;
boolean isLogical = true;
boolean allNA = true;
for (String s : vector) {
if (s == null || s.startsWith("NA") || s.startsWith("Na") || s.matches("^\\s*$")) {
// Ignore, don't set the type based on this
continue;
}
allNA = false;
if (isNumber) {
// match numbers: 123,456.123 123 123,456 456.123 .123
if (!s.matches("(^|^-)((\\d+(,\\d+)*)|(\\d*))\\.?\\d+$")) {
isNumber = false;
}
// match double
else if (isInteger && s.matches("(^|^-)\\d*\\.{1}\\d+$")) {
isInteger = false;
}
}
// NOTE: cannot use "else" because isNumber changed in the previous
// if block
if (isLogical && !s.toLowerCase().matches("^t|f|true|false$")) {
isLogical = false;
}
}
// String result = "Unknown";
String result = "string";
if (!allNA) {
if (isNumber) {
if (!isInteger || doPreferDouble) {
result = "double";
} else {
result = "int";
}
} else {
if (isLogical) {
result = "boolean";
} else {
result = "string";
}
}
}
return result;
}
/**
* TODO: check more than a few lines in case some lines have NA
*
* @param fileRDD
* @return
*/
public String[] getMetaInfo(JavaRDD<String> fileRDD, String fieldSeparator) {
String[] headers = null;
int sampleSize = 5;
// sanity check
if (sampleSize < 1) {
mLog.info("DATATYPE_SAMPLE_SIZE must be bigger than 1");
return null;
}
List<String> sampleStr = fileRDD.take(sampleSize);
sampleSize = sampleStr.size(); // actual sample size
mLog.info("Sample size: " + sampleSize);
// create sample list for getting data type
String[] firstSplit = sampleStr.get(0).split(fieldSeparator);
// get header
boolean hasHeader = false;
if (hasHeader) {
headers = firstSplit;
} else {
headers = new String[firstSplit.length];
int size = headers.length;
for (int i = 0; i < size; ) {
headers[i] = "V" + (++i);
}
}
String[][] samples = hasHeader ? (new String[firstSplit.length][sampleSize - 1])
: (new String[firstSplit.length][sampleSize]);
String[] metaInfoArray = new String[firstSplit.length];
int start = hasHeader ? 1 : 0;
for (int j = start; j < sampleSize; j++) {
firstSplit = sampleStr.get(j).split(fieldSeparator);
for (int i = 0; i < firstSplit.length; i++) {
samples[i][j - start] = firstSplit[i];
}
}
boolean doPreferDouble = true;
for (int i = 0; i < samples.length; i++) {
String[] vector = samples[i];
metaInfoArray[i] = headers[i] + " " + determineType(vector, doPreferDouble);
}
return metaInfoArray;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.