answer
stringlengths 17
10.2M
|
|---|
package net.viktorc.pp4j.impl;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.Semaphore;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.helpers.NOPLogger;
import net.viktorc.pp4j.api.Command;
import net.viktorc.pp4j.api.ProcessExecutor;
import net.viktorc.pp4j.api.ProcessManager;
import net.viktorc.pp4j.api.ProcessManagerFactory;
import net.viktorc.pp4j.api.ProcessPool;
import net.viktorc.pp4j.api.Submission;
public class StandardProcessPool implements ProcessPool {
/**
* The number of milliseconds after which idle process executor instances and process executor threads are
* evicted from the object pool and the thread pool respectively.
*/
private static final long EVICT_TIME = 60L*1000;
private final ProcessManagerFactory procManagerFactory;
private final int minPoolSize;
private final int maxPoolSize;
private final int reserveSize;
private final boolean verbose;
private final StandardProcessPoolExecutor procExecutorThreadPool;
private final ExecutorService auxThreadPool;
private final StandardProcessExecutorObjectPool procExecutorPool;
private final Queue<StandardProcessExecutor> activeProcExecutors;
private final LinkedBlockingDeque<InternalSubmission> submissionQueue;
private final AtomicInteger numOfActiveSubmissions;
private final CountDownLatch prestartLatch;
private final Object poolLock;
private final Logger logger;
private volatile boolean close;
public StandardProcessPool(ProcessManagerFactory procManagerFactory, int minPoolSize, int maxPoolSize,
int reserveSize, boolean verbose) throws InterruptedException {
if (procManagerFactory == null)
throw new IllegalArgumentException("The process manager factory cannot be null.");
if (minPoolSize < 0)
throw new IllegalArgumentException("The minimum pool size has to be greater than 0.");
if (maxPoolSize < 1 || maxPoolSize < minPoolSize)
throw new IllegalArgumentException("The maximum pool size has to be at least 1 and at least as great " +
"as the minimum pool size.");
if (reserveSize < 0 || reserveSize > maxPoolSize)
throw new IllegalArgumentException("The reserve has to be at least 0 and less than the maximum pool " +
"size.");
this.procManagerFactory = procManagerFactory;
this.minPoolSize = minPoolSize;
this.maxPoolSize = maxPoolSize;
this.reserveSize = reserveSize;
this.verbose = verbose;
procExecutorThreadPool = new StandardProcessPoolExecutor();
int actualMinSize = Math.max(minPoolSize, reserveSize);
/* One process requires minimum 3 auxiliary threads (std_out listener, err_out listener,
* submission handler); 4 if keepAliveTime is positive (one more for timing). */
auxThreadPool = new ThreadPoolExecutor(3*actualMinSize, Integer.MAX_VALUE, EVICT_TIME,
TimeUnit.MILLISECONDS, new SynchronousQueue<>(),
new CustomizedThreadFactory(this + "-auxThreadPool"));
procExecutorPool = new StandardProcessExecutorObjectPool();
submissionQueue = new LinkedBlockingDeque<>();
activeProcExecutors = new LinkedBlockingQueue<>();
numOfActiveSubmissions = new AtomicInteger(0);
prestartLatch = new CountDownLatch(actualMinSize);
poolLock = new Object();
logger = verbose ? LoggerFactory.getLogger(getClass()) : NOPLogger.NOP_LOGGER;
for (int i = 0; i < actualMinSize && !close; i++) {
synchronized (poolLock) {
startNewProcess(null);
}
}
// Wait for the processes in the initial pool to start up.
prestartLatch.await();
logger.info("Pool started up.");
}
/**
* Returns the minimum number of processes to hold in the pool.
*
* @return The minimum size of the process pool.
*/
public int getMinSize() {
return minPoolSize;
}
/**
* Returns the maximum allowed number of processes to hold in the pool.
*
* @return The maximum size of the process pool.
*/
public int getMaxSize() {
return maxPoolSize;
}
/**
* Returns the minimum number of available processes to keep in the pool.
*
* @return The number of available processes to keep in the pool.
*/
public int getReserveSize() {
return reserveSize;
}
/**
* Returns whether events relating to the management of the processes held by the pool are logged to the
* console.
*
* @return Whether the pool is verbose.
*/
public boolean isVerbose() {
return verbose;
}
/**
* Returns the number of running processes currently held in the pool.
*
* @return The number of running processes.
*/
public int getNumOfProcesses() {
return activeProcExecutors.size();
}
/**
* Returns the number of submissions currently being executed in the pool.
*
* @return The number of submissions currently being executed in the pool.
*/
public int getNumOfExecutingSubmissions() {
return numOfActiveSubmissions.get();
}
/**
* Returns the number of submissions queued and waiting for execution.
*
* @return The number of queued submissions.
*/
public int getNumOfQueuedSubmissions() {
return submissionQueue.size();
}
/**
* Returns the number of active, queued, and currently executing processes as string.
*
* @return A string of statistics concerning the size of the process pool.
*/
private String getPoolStats() {
return "Processes: " + activeProcExecutors.size() + "; active submission: " +
numOfActiveSubmissions.get() + "; queued submission: " + submissionQueue.size();
}
/**
* Returns whether a new {@link StandardProcessExecutor} instance should be started.
*
* @return Whether the process pool should be extended.
*/
private boolean doExtendPool() {
return !close && (activeProcExecutors.size() < minPoolSize || (activeProcExecutors.size() <
Math.min(maxPoolSize, numOfActiveSubmissions.get() + submissionQueue.size() + reserveSize)));
}
/**
* Starts a new process by executing the provided {@link StandardProcessExecutor}. If it is null, it borrows
* an instance from the pool.
*
* @param executor An optional {@link StandardProcessExecutor} instance to re-start in case one is available.
* @return Whether the process was successfully started.
*/
private boolean startNewProcess(StandardProcessExecutor executor) {
if (executor == null) {
try {
executor = procExecutorPool.borrowObject();
} catch (Exception e) {
return false;
}
}
procExecutorThreadPool.execute(executor);
activeProcExecutors.add(executor);
logger.debug("Process executor {} started.{}", executor, System.lineSeparator() + getPoolStats());
return true;
}
@Override
public ProcessManagerFactory getProcessManagerFactory() {
return procManagerFactory;
}
@Override
public Future<Long> submit(Submission submission) {
if (close)
throw new IllegalStateException("The pool has already been shut down.");
if (submission == null)
throw new IllegalArgumentException("The submission cannot be null or empty.");
InternalSubmission internalSubmission = new InternalSubmission(submission);
submissionQueue.addLast(internalSubmission);
// If necessary, adjust the pool size given the new submission.
synchronized (poolLock) {
if (doExtendPool())
startNewProcess(null);
}
logger.info("Submission {} received.{}", internalSubmission, System.lineSeparator() +
getPoolStats());
// Return a Future holding the total execution time including the submission delay.
return new InternalSubmissionFuture(internalSubmission);
}
@Override
public synchronized void shutdown() {
synchronized (poolLock) {
if (close)
throw new IllegalStateException("The pool has already been shut down.");
logger.info("Initiating shutdown...");
close = true;
while (prestartLatch.getCount() != 0)
prestartLatch.countDown();
logger.debug("Shutting down process executors...");
for (StandardProcessExecutor executor : activeProcExecutors) {
if (!executor.stop(true)) {
// This should never happen.
logger.error("Process executor {} could not be stopped.", executor);
}
}
logger.debug("Shutting down thread pools...");
auxThreadPool.shutdown();
procExecutorThreadPool.shutdown();
procExecutorPool.close();
}
try {
auxThreadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
procExecutorThreadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
for (InternalSubmission submission : submissionQueue)
submission.setException(new Exception("The process pool has been shut down."));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
logger.info("Process pool shut down.");
}
@Override
public String toString() {
return String.format("stdProcPool@%s", Integer.toHexString(hashCode()));
}
/**
* An implementation of the {@link net.viktorc.pp4j.api.Submission} interface to keep track of the number
* of commands being executed at a time and to establish a mechanism for cancelling submitted commands via the
* {@link java.util.concurrent.Future} returned by the
* {@link net.viktorc.pp4j.impl.StandardProcessPool#submit(Submission)} method.
*
* @author Viktor Csomor
*
*/
private class InternalSubmission implements Submission {
final Submission origSubmission;
final long receivedTime;
final Object lock;
Thread thread;
Exception exception;
volatile long submittedTime;
volatile long processedTime;
volatile boolean processed;
volatile boolean cancelled;
InternalSubmission(Submission originalSubmission) {
if (originalSubmission == null)
throw new IllegalArgumentException("The submission cannot be null.");
this.origSubmission = originalSubmission;
receivedTime = System.nanoTime();
lock = new Object();
}
/**
* Sets the thread that is executing the submission.
*
* @param t The thread that executes the submission.
*/
void setThread(Thread t) {
synchronized (lock) {
thread = t;
}
}
/**
* Sets the exception thrown during the execution of the submission if there was any.
*
* @param e The exception thrown during the execution of the submission.
*/
void setException(Exception e) {
// Notify the InternalSubmissionFuture that an exception was thrown while processing the submission.
synchronized (lock) {
exception = e;
lock.notifyAll();
}
}
/**
* Returns whether the <code>cancelled</code> flag of the submission has been set to true.
*
* @return Whether the submission has been cancelled.
*/
boolean isCancelled() {
synchronized (lock) {
return cancelled;
}
}
/**
* Sets the <code>cancelled</code> flag of the submission to true.
*/
void cancel() {
synchronized (lock) {
cancelled = true;
lock.notifyAll();
}
}
@Override
public List<Command> getCommands() {
return origSubmission.getCommands();
}
@Override
public boolean doTerminateProcessAfterwards() {
return origSubmission.doTerminateProcessAfterwards();
}
@Override
public void onStartedProcessing() {
// If it is the first time the submission is submitted to a process...
if (submittedTime == 0) {
submittedTime = System.nanoTime();
origSubmission.onStartedProcessing();
}
}
@Override
public void onFinishedProcessing() {
origSubmission.onFinishedProcessing();
processedTime = System.nanoTime();
// Notify the InternalSubmissionFuture that the submission has been processed.
synchronized (lock) {
processed = true;
lock.notifyAll();
}
}
@Override
public String toString() {
return String.format("{commands:[%s],terminate:%s}@%s", String.join(",", origSubmission.getCommands()
.stream().map(c -> "\"" + c.getInstruction() + "\"").collect(Collectors.toList())),
Boolean.toString(origSubmission.doTerminateProcessAfterwards()),
Integer.toHexString(hashCode()));
}
}
/**
* An implementation of {@link java.util.concurrent.Future} that returns the time it took to process the
* submission in nanoseconds.
*
* @author Viktor Csomor
*
*/
private class InternalSubmissionFuture implements Future<Long> {
final InternalSubmission submission;
/**
* Constructs a {@link java.util.concurrent.Future} for the specified submission.
*
* @param submission The submission to get a {@link java.util.concurrent.Future} for.
*/
InternalSubmissionFuture(InternalSubmission submission) {
this.submission = submission;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
synchronized (submission.lock) {
/* If the submission has already been cancelled or if it has already been processed, don't do
* anything and return false. */
if (submission.cancelled || submission.processed)
return false;
/* If it is already being processed and mayInterruptIfRunning is true, interrupt the executor
* thread. */
if (submission.thread != null) {
if (mayInterruptIfRunning) {
submission.cancel();
submission.thread.interrupt();
}
// If mayInterruptIfRunning is false, don't let the submission be cancelled.
} else
// If the processing of the submission has not commenced yet, cancel it.
submission.cancel();
return submission.cancelled;
}
}
@Override
public Long get() throws InterruptedException, ExecutionException, CancellationException {
// Wait until the submission is processed, or cancelled, or fails.
synchronized (submission.lock) {
while (!submission.processed && !submission.cancelled && submission.exception == null)
submission.lock.wait();
if (submission.cancelled)
throw new CancellationException(String.format("Submission %s cancelled.", submission));
if (submission.exception != null)
throw new ExecutionException(submission.exception);
return submission.processedTime - submission.receivedTime;
}
}
@Override
public Long get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException, CancellationException {
// Wait until the submission is processed, or cancelled, or fails, or the method times out.
synchronized (submission.lock) {
long timeoutNs = unit.toNanos(timeout);
long start = System.nanoTime();
while (!submission.processed && !submission.cancelled && submission.exception == null &&
timeoutNs > 0) {
submission.lock.wait(timeoutNs/1000000, (int) (timeoutNs%1000000));
timeoutNs -= (System.nanoTime() - start);
}
if (submission.cancelled)
throw new CancellationException(String.format("Submission %s cancelled.", submission));
if (submission.exception != null)
throw new ExecutionException(submission.exception);
if (timeoutNs <= 0)
throw new TimeoutException(String.format("Submission %s timed out.", submission));
return timeoutNs <= 0 ? null : (submission.processedTime - submission.receivedTime);
}
}
@Override
public boolean isCancelled() {
return submission.cancelled;
}
@Override
public boolean isDone() {
return submission.processed;
}
}
/**
* An implementation of the {@link net.viktorc.pp4j.api.ProcessExecutor} interface for starting, managing,
* and interacting with a process. The life cycle of the associated process is the same as that of the
* {@link #run()} method of the instance. The process is not started until this method is called and the
* method does not terminate until the process does.
*
* @author Viktor Csomor
*
*/
private class StandardProcessExecutor implements ProcessExecutor, Runnable {
/**
* If a process cannot be started or an exception occurs which would make it impossible to retrieve the
* actual return code of the process.
*/
public static final int UNEXPECTED_TERMINATION_RESULT_CODE = -1;
final ProcessManager manager;
final Lock submissionLock;
final Lock stopLock;
final Object runLock;
final Object execLock;
final Object processLock;
final Object subHandlerLock;
final Semaphore termSemaphore;
Process process;
KeepAliveTimer timer;
BufferedReader stdOutReader;
BufferedReader stdErrReader;
BufferedWriter stdInWriter;
Thread subThread;
Command command;
long keepAliveTime;
boolean doTime;
boolean onWait;
boolean commandCompleted;
boolean startedUp;
volatile boolean running;
volatile boolean stop;
/**
* Constructs an executor for the specified process using two threads to listen to the out streams of
* the process, one for listening to the submission queue, and one thread for ensuring that the process
* is terminated once it times out if <code>keepAliveTime</code> is greater than 0.
*/
StandardProcessExecutor() {
manager = procManagerFactory.newProcessManager();
submissionLock = new ReentrantLock();
stopLock = new ReentrantLock();
runLock = new Object();
execLock = new Object();
processLock = new Object();
subHandlerLock = new Object();
termSemaphore = new Semaphore(0);
}
/**
* Starts listening to an out stream of the process using the specified reader.
*
* @param reader The buffered reader to use to listen to the steam.
* @param standard Whether it is the standard out or the standard error stream of the process.
*/
void startListeningToProcess(BufferedReader reader, boolean standard) {
try {
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.isEmpty())
continue;
// Make sure that the submission executor thread is waiting.
synchronized (execLock) {
if (startedUp) {
/* Before processing a new line, make sure that the submission executor
* thread is notified that the line signaling the completion of the command
* has been processed. */
while (commandCompleted && onWait)
execLock.wait();
if (command != null) {
// Process the next line.
commandCompleted = command.onNewOutput(line, standard);
if (commandCompleted)
execLock.notifyAll();
}
} else {
startedUp = manager.isStartedUp(line, standard);
if (startedUp)
execLock.notifyAll();
}
}
}
} catch (IOException | InterruptedException e) {
throw new ProcessException(e);
} finally {
termSemaphore.release();
}
}
/**
* Starts waiting on the blocking queue of submissions executing available ones one at a time.
*/
void startHandlingSubmissions() {
synchronized (subHandlerLock) {
subThread = Thread.currentThread();
}
try {
while (running && !stop) {
InternalSubmission submission = null;
boolean submissionRetrieved = false;
try {
/* Wait until the startup phase is over and the mainLock is available to avoid retrieving
* a submission only to find that it cannot be executed and thus has to be put back into
* the queue. */
submissionLock.lock();
submissionLock.unlock();
// Wait for an available submission.
submission = submissionQueue.takeFirst();
/* Increment the counter for active submissions to keep track of the number of busy
* processes. */
numOfActiveSubmissions.incrementAndGet();
submissionRetrieved = true;
submission.setThread(subThread);
if (submission.isCancelled()) {
submission = null;
continue;
}
/* It can happen of course that in the mean time, the mainLock has been stolen (for
* terminating the process) or that the process is already terminated, and thus the
* execute method fails. In this case, the submission is put back into the queue. */
if (execute(submission)) {
logger.info(String.format("Submission %s processed; delay: %.3f; " +
"execution time: %.3f.%n%s", submission, (float) ((double)
(submission.submittedTime - submission.receivedTime)/1000000000),
(float) ((double) (submission.processedTime -
submission.submittedTime)/1000000000), getPoolStats()));
submission = null;
}
} catch (InterruptedException e) {
// Next round (unless the process is stopped).
continue;
} catch (Exception e) {
// Signal the exception to the future and do not put the submission back into the queue.
if (submission != null) {
logger.warn(String.format("Exception while executing submission %s.%n%s",
submission, getPoolStats()), e);
submission.setException(e);
submission = null;
}
} finally {
/* If the execute method failed and there was no exception thrown, put the submission
* back into the queue at the front. */
if (submission != null) {
if (!submission.isCancelled()) {
submission.setThread(null);
submissionQueue.addFirst(submission);
}
}
// Decrement the active submissions counter if it was incremented in this cycle.
if (submissionRetrieved)
numOfActiveSubmissions.decrementAndGet();
}
}
} finally {
synchronized (subHandlerLock) {
subThread = null;
}
termSemaphore.release();
}
}
/**
* It prompts the currently running process, if there is one, to terminate. Once the process has been
* successfully terminated, subsequent calls are ignored and return true unless the process is started
* again.
*
* @param forcibly Whether the process should be killed forcibly or using the
* {@link net.viktorc.pp4j.api.ProcessManager#terminateGracefully(ProcessExecutor)} method of the
* {@link net.viktorc.pp4j.api.ProcessManager} instance assigned to the executor. The latter might be
* ineffective if the process is currently executing a command or has not started up.
* @return Whether the process was successfully terminated.
*/
boolean stop(boolean forcibly) {
stopLock.lock();
try {
if (stop)
return true;
synchronized (execLock) {
boolean success = true;
if (running) {
if (!forcibly)
success = manager.terminateGracefully(this);
else {
synchronized (processLock) {
if (process != null)
process.destroy();
}
}
}
if (success) {
stop = true;
execLock.notifyAll();
}
return success;
}
} finally {
stopLock.unlock();
}
}
@Override
public boolean execute(Submission submission)
throws IOException, InterruptedException, CancellationException {
if (submissionLock.tryLock()) {
// Make sure that the reader thread can only process output lines if this one is ready and waiting.
synchronized (execLock) {
boolean success = false;
try {
/* If the process has terminated or the ProcessExecutor has been stopped while acquiring
* the execLock, return. */
if (!running || stop)
return success;
// Stop the timer as the process is not idle anymore.
if (doTime)
timer.stop();
if (stop)
return success;
submission.onStartedProcessing();
List<Command> commands = submission.getCommands();
List<Command> processedCommands = commands.size() > 1 ?
new ArrayList<>(commands.size() - 1) : null;
for (int i = 0; i < commands.size(); i++) {
command = commands.get(i);
if (i != 0 && !command.doExecute(new ArrayList<>(processedCommands)))
continue;
commandCompleted = !command.generatesOutput();
stdInWriter.write(command.getInstruction());
stdInWriter.newLine();
stdInWriter.flush();
while (running && !stop && !commandCompleted) {
onWait = true;
execLock.wait();
}
// Let the readers know that the command may be considered effectively processed.
onWait = false;
execLock.notifyAll();
/* If the process has terminated or the ProcessExecutor has been stopped, return false
* to signal failure. */
if (!commandCompleted)
return success;
if (i < commands.size() - 1)
processedCommands.add(command);
}
command = null;
if (running && !stop && submission.doTerminateProcessAfterwards() &&
stopLock.tryLock()) {
try {
if (!stop(false))
stop(true);
} finally {
stopLock.unlock();
}
}
success = true;
return success;
} finally {
try {
if (success)
submission.onFinishedProcessing();
} finally {
command = null;
onWait = false;
execLock.notifyAll();
if (running && !stop && doTime)
timer.start();
submissionLock.unlock();
}
}
}
}
return false;
}
@Override
public void run() {
synchronized (runLock) {
termSemaphore.drainPermits();
int rc = UNEXPECTED_TERMINATION_RESULT_CODE;
long lifeTime = 0;
try {
submissionLock.lock();
boolean orderly = false;
try {
// Start the process
synchronized (execLock) {
if (stop)
return;
running = true;
command = null;
keepAliveTime = manager.getKeepAliveTime();
doTime = keepAliveTime > 0;
timer = doTime && timer == null ? new KeepAliveTimer() : timer;
// Start the process.
synchronized (processLock) {
process = manager.start();
}
lifeTime = System.currentTimeMillis();
stdOutReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
stdErrReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
stdInWriter = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
// Handle the startup; check if the process is to be considered immediately started up.
startedUp = manager.startsUpInstantly();
auxThreadPool.submit(() -> startListeningToProcess(stdOutReader, true));
auxThreadPool.submit(() -> startListeningToProcess(stdErrReader, false));
while (!startedUp) {
execLock.wait();
if (stop)
return;
}
manager.onStartup(this);
if (stop)
return;
// Start accepting submissions.
auxThreadPool.submit(this::startHandlingSubmissions);
if (doTime) {
// Start the timer.
auxThreadPool.submit(timer);
timer.start();
}
orderly = true;
prestartLatch.countDown();
}
} finally {
/* If the startup was not orderly, e.g. the process was stopped prematurely or an exception
* was thrown, release as many permits as there are slave threads to ensure that the
* semaphore does not block in the finally clause; also count down on the pre-start latch
* to avoid having the pool wait on the failed startup. */
if (!orderly) {
termSemaphore.release(doTime ? 4 : 3);
prestartLatch.countDown();
}
submissionLock.unlock();
}
/* If the startup failed, the process might not be initialized. Otherwise, wait for the process
* to terminate. */
if (orderly)
rc = process.waitFor();
} catch (Exception e) {
throw new ProcessException(e);
} finally {
// Stop the timer.
if (doTime)
timer.stop();
// Make sure the process itself has terminated.
synchronized (processLock) {
if (process != null) {
if (process.isAlive()) {
process.destroy();
try {
process.waitFor();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
process = null;
}
}
lifeTime = lifeTime == 0 ? 0 : System.currentTimeMillis() - lifeTime;
logger.debug(String.format("Process runtime in executor %s: %.3f", this,
((float) lifeTime)/1000));
// Make sure that there are no submission currently being executed...
submissionLock.lock();
try {
// Set running to false...
synchronized (execLock) {
running = false;
execLock.notifyAll();
}
/* And interrupt the submission handler thread to avoid having it stuck waiting for
* submissions forever in case the queue is empty. */
synchronized (subHandlerLock) {
if (subThread != null)
subThread.interrupt();
}
/* Make sure that the timer sees the new value of running and the timer thread can
* terminate. */
if (doTime)
timer.stop();
} finally {
submissionLock.unlock();
}
// Wait for all the slave threads to finish.
try {
termSemaphore.acquire(doTime ? 4 : 3);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
// Try to close all the streams.
if (stdOutReader != null) {
try {
stdOutReader.close();
} catch (IOException e) {
// Ignore it.
}
}
if (stdErrReader != null) {
try {
stdErrReader.close();
} catch (IOException e) {
// Ignore it.
}
}
if (stdInWriter != null) {
try {
stdInWriter.close();
} catch (IOException e) {
// Ignore it.
}
}
// The process life cycle is over.
try {
manager.onTermination(rc, lifeTime);
} finally {
synchronized (execLock) {
stop = false;
}
}
}
}
}
@Override
public String toString() {
return String.format("%s-stdProcExecutor@%s", StandardProcessPool.this,
Integer.toHexString(hashCode()));
}
/**
* A simple timer that stops the process after <code>keepAliveTime</code> milliseconds unless the process
* is inactive or the timer is cancelled. It also enables the timer to be restarted using the same thread.
*
* @author Viktor Csomor
*
*/
private class KeepAliveTimer implements Runnable {
boolean go;
/**
* Restarts the timer.
*/
synchronized void start() {
go = true;
notifyAll();
}
/**
* Stops the timer.
*/
synchronized void stop() {
go = false;
notifyAll();
}
@Override
public synchronized void run() {
try {
while (running && !stop) {
while (!go) {
wait();
if (!running || stop)
return;
}
long waitTime = keepAliveTime;
while (go && waitTime > 0) {
long start = System.currentTimeMillis();
wait(waitTime);
if (!running || stop)
return;
waitTime -= (System.currentTimeMillis() - start);
}
/* Normally, the timer should not be running while a submission is being processed, i.e.
* if the timer gets to this point with go set to true, submissionLock should be available to
* the timer thread. However, if the execute method acquires the submissionLock right after the
* timer's wait time elapses, it will not be able to disable the timer until it enters
* the wait method in the next cycle and gives up its intrinsic lock. Therefore, the
* first call of the stop method of the StandardProcessExecutor would fail due to the
* lock held by the thread running the execute method, triggering the forcible shutdown
* of the process even though it is not idle. To avoid this behavior, first the submissionLock
* is attempted to be acquired to ensure that the process is indeed idle. */
if (go && submissionLock.tryLock()) {
try {
if (!StandardProcessExecutor.this.stop(false))
StandardProcessExecutor.this.stop(true);
} finally {
submissionLock.unlock();
}
}
}
} catch (InterruptedException e) {
// Just let the thread terminate.
} catch (Exception e) {
throw new ProcessException(e);
} finally {
go = false;
termSemaphore.release();
}
}
}
}
/**
* A sub-class of {@link org.apache.commons.pool2.impl.GenericObjectPool} for the pooling of
* {@link net.viktorc.pp4j.impl.StandardProcessPool.StandardProcessExecutor} instances.
*
* @author Viktor Csomor
*
*/
private class StandardProcessExecutorObjectPool extends GenericObjectPool<StandardProcessExecutor> {
/**
* Constructs an object pool instance to facilitate the reuse of
* {@link net.viktorc.pp4j.impl.StandardProcessPool.StandardProcessExecutor} instances. The pool
* does not block if there are no available objects, it accommodates <code>maxPoolSize</code>
* objects, and if there are more than <code>Math.max(minPoolSize, reserveSize)</code> idle objects
* in the pool, excess idle objects are eligible for eviction after <code>EVICT_TIME</code>
* milliseconds. The eviction thread runs at the above specified intervals and performs at most
* <code>maxPoolSize - Math.max(minPoolSize, reserveSize)</code> evictions per run.
*/
StandardProcessExecutorObjectPool() {
super(new PooledObjectFactory<StandardProcessExecutor>() {
@Override
public PooledObject<StandardProcessExecutor> makeObject() throws Exception {
return new DefaultPooledObject<StandardProcessExecutor>(new StandardProcessExecutor());
}
@Override
public void activateObject(PooledObject<StandardProcessExecutor> p) { /* No-operation. */ }
@Override
public boolean validateObject(PooledObject<StandardProcessExecutor> p) {
return true;
}
@Override
public void passivateObject(PooledObject<StandardProcessExecutor> p) { /* No-operation. */ }
@Override
public void destroyObject(PooledObject<StandardProcessExecutor> p) { /* No-operation. */ }
});
setBlockWhenExhausted(false);
setMaxTotal(maxPoolSize);
setMaxIdle(Math.max(minPoolSize, reserveSize));
long evictTime = EVICT_TIME;
setTimeBetweenEvictionRunsMillis(evictTime);
setSoftMinEvictableIdleTimeMillis(evictTime);
setNumTestsPerEvictionRun(maxPoolSize - Math.max(maxPoolSize, reserveSize));
}
}
/**
* An implementation the {@link java.util.concurrent.ThreadFactory} interface that provides more descriptive
* thread names and extends the {@link java.lang.Thread.UncaughtExceptionHandler} of the created threads by
* logging the uncaught exceptions if the enclosing {@link net.viktorc.pp4j.impl.StandardProcessPool}
* instance is verbose. It also attempts to shut down the enclosing pool if a
* {@link net.viktorc.pp4j.impl.ProcessException} is thrown in one of the threads it created.
*
* @author Viktor Csomor
*
*/
private class CustomizedThreadFactory implements ThreadFactory {
final String poolName;
final ThreadFactory defaultFactory;
/**
* Constructs an instance according to the specified parameters.
*
* @param poolName The name of the thread pool. It will be prepended to the name of the created threads.
*/
CustomizedThreadFactory(String poolName) {
this.poolName = poolName;
defaultFactory = Executors.defaultThreadFactory();
}
@Override
public Thread newThread(Runnable r) {
Thread t = defaultFactory.newThread(r);
t.setName(t.getName().replaceFirst("pool-[0-9]+", poolName));
t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
// Log the exception whether verbose or not.
logger.error(e.getMessage(), e);
StandardProcessPool.this.shutdown();
}
});
return t;
}
}
private class StandardProcessPoolExecutor extends ThreadPoolExecutor {
/**
* Constructs thread pool for the execution of
* {@link net.viktorc.pp4j.impl.StandardProcessPool.StandardProcessExecutor} instances. If there are
* more than <code>Math.max(minPoolSize, reserveSize)</code> idle threads in the pool, excess threads
* are evicted after <code>EVICT_TIME</code> milliseconds.
*/
StandardProcessPoolExecutor() {
super(Math.max(minPoolSize, reserveSize), maxPoolSize, EVICT_TIME, TimeUnit.MILLISECONDS,
new LinkedTransferQueue<Runnable>() {
private static final long serialVersionUID = 1L;
@Override
public boolean offer(Runnable r) {
/* If there is at least one thread waiting on the queue, delegate the task immediately;
* else decline it and force the pool to create a new thread for running the task. */
return tryTransfer(r);
}
}, new CustomizedThreadFactory(StandardProcessPool.this + "-procExecThreadPool"),
new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
/* If there are no threads waiting on the queue (all of them are busy executing)
* and the maximum pool size has been reached, when the queue declines the offer,
* the pool will not create any more threads but call this handler instead. This
* handler 'forces' the declined task on the queue, ensuring that it is not
* rejected. */
executor.getQueue().put(r);
} catch (InterruptedException e) {
// Should not happen.
Thread.currentThread().interrupt();
}
}
});
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
StandardProcessExecutor executor = (StandardProcessExecutor) r;
activeProcExecutors.remove(executor);
logger.debug("Process executor {} stopped.{}", executor, System.lineSeparator() + getPoolStats());
/* A process has terminated. Extend the pool if necessary by directly reusing the ProcessExecutor
* instance. If not, return it to the pool. */
synchronized (poolLock) {
if (doExtendPool())
startNewProcess(executor);
else
procExecutorPool.returnObject(executor);
}
}
}
}
|
package beast.evolution.tree;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.commons.math.MathException;
import beast.core.BEASTInterface;
import beast.core.Description;
import beast.core.Input;
import beast.core.Input.Validate;
import beast.core.StateNode;
import beast.core.StateNodeInitialiser;
import beast.core.util.Log;
import beast.evolution.alignment.Alignment;
import beast.evolution.alignment.TaxonSet;
import beast.evolution.tree.coalescent.PopulationFunction;
import beast.math.distributions.MRCAPrior;
import beast.math.distributions.ParametricDistribution;
import beast.util.HeapSort;
import beast.util.Randomizer;
@Description("This class provides the basic engine for coalescent simulation of a given demographic model over a given time period. ")
public class RandomTree extends Tree implements StateNodeInitialiser {
final public Input<Alignment> taxaInput = new Input<>("taxa", "set of taxa to initialise tree specified by alignment");
final public Input<PopulationFunction> populationFunctionInput = new Input<>("populationModel", "population function for generating coalescent???", Validate.REQUIRED);
final public Input<List<MRCAPrior>> calibrationsInput = new Input<>("constraint", "specifies (monophyletic or height distribution) constraints on internal nodes", new ArrayList<>());
final public Input<Double> rootHeightInput = new Input<>("rootHeight", "If specified the tree will be scaled to match the root height, if constraints allow this");
// total nr of taxa
int nrOfTaxa;
class Bound {
Double upper = Double.POSITIVE_INFINITY;
Double lower = Double.NEGATIVE_INFINITY;
@Override
public String toString() {
return "[" + lower + "," + upper + "]";
}
}
// Location of last monophyletic clade in the lists below, which are grouped together at the start.
// (i.e. the first isMonophyletic of the TaxonSets are monophyletic, while the remainder are not).
int lastMonophyletic;
// taxonSets,distributions, m_bounds and taxonSetIDs are indexed together (four values associated with this clade, a set of taxa.
// taxon sets of clades that has a constraint of calibrations. Monophyletic constraints may be nested, and are sorted by the code to be at a
// higher index, i.e iterating from zero up does post-order (descendants before parent).
List<Set<String>> taxonSets;
// list of parametric distribution constraining the MRCA of taxon sets, null if not present
List<ParametricDistribution> distributions;
// hard bound for the set, if any
List<Bound> m_bounds;
// The prior element involved, if any
List<String> taxonSetIDs;
List<Integer>[] children;
Set<String> taxa;
// number of the next internal node, used when creating new internal nodes
int nextNodeNr;
// used to indicate one of the MRCA constraints could not be met
protected class ConstraintViolatedException extends Exception {
private static final long serialVersionUID = 1L;
}
@Override
public void initAndValidate() {
taxa = new LinkedHashSet<>();
if (taxaInput.get() != null) {
taxa.addAll(taxaInput.get().getTaxaNames());
} else {
taxa.addAll(m_taxonset.get().asStringList());
}
nrOfTaxa = taxa.size();
initStateNodes();
super.initAndValidate();
}
@SuppressWarnings({"rawtypes", "unchecked"})
private void swap(final List list, final int i, final int j) {
final Object tmp = list.get(i);
list.set(i, list.get(j));
list.set(j, tmp);
}
// taxonset intersection test
// private boolean intersects(final BitSet bitSet, final BitSet bitSet2) {
// for (int k = bitSet.nextSetBit(0); k >= 0; k = bitSet.nextSetBit(k + 1)) {
// if (bitSet2.get(k)) {
// return true;
// return false;
// returns true if bitSet is a subset of bitSet2
// private boolean isSubset(final BitSet bitSet, final BitSet bitSet2) {
// boolean isSubset = true;
// for (int k = bitSet.nextSetBit(0); isSubset && k >= 0; k = bitSet.nextSetBit(k + 1)) {
// isSubset = bitSet2.get(k);
// return isSubset;
@SuppressWarnings("unchecked")
@Override
public void initStateNodes() {
// find taxon sets we are dealing with
taxonSets = new ArrayList<>();
m_bounds = new ArrayList<>();
distributions = new ArrayList<>();
taxonSetIDs = new ArrayList<>();
lastMonophyletic = 0;
if (taxaInput.get() != null) {
taxa.addAll(taxaInput.get().getTaxaNames());
} else {
taxa.addAll(m_taxonset.get().asStringList());
}
// pick up constraints from outputs, m_inititial input tree and output tree, if any
List<MRCAPrior> calibrations = new ArrayList<>();
calibrations.addAll(calibrationsInput.get());
// for (BEASTObject beastObject : outputs) {
// // pick up constraints in outputs
// if (beastObject instanceof MRCAPrior && !calibrations.contains(beastObject)) {
// calibrations.add((MRCAPrior) beastObject);
// } else if (beastObject instanceof Tree) {
// // pick up constraints in outputs if output tree
// Tree tree = (Tree) beastObject;
// if (tree.m_initial.get() == this) {
// for (BEASTObject beastObject2 : tree.outputs) {
// if (beastObject2 instanceof MRCAPrior && !calibrations.contains(beastObject2)) {
// calibrations.add((MRCAPrior) beastObject2);
// pick up constraints in m_initial tree
for (final Object beastObject : getOutputs()) {
if (beastObject instanceof MRCAPrior && !calibrations.contains(beastObject) ) {
calibrations.add((MRCAPrior) beastObject);
}
}
if (m_initial.get() != null) {
for (final Object beastObject : m_initial.get().getOutputs()) {
if (beastObject instanceof MRCAPrior && !calibrations.contains(beastObject)) {
calibrations.add((MRCAPrior) beastObject);
}
}
}
for (final MRCAPrior prior : calibrations) {
final TaxonSet taxonSet = prior.taxonsetInput.get();
if (taxonSet != null && !prior.onlyUseTipsInput.get()) {
final Set<String> usedTaxa = new LinkedHashSet<>();
if (taxonSet.asStringList() == null) {
taxonSet.initAndValidate();
}
for (final String taxonID : taxonSet.asStringList()) {
if (!taxa.contains(taxonID)) {
throw new IllegalArgumentException("Taxon <" + taxonID + "> could not be found in list of taxa. Choose one of " + taxa);
}
usedTaxa.add(taxonID);
}
final ParametricDistribution distr = prior.distInput.get();
final Bound bounds = new Bound();
if (distr != null) {
List<BEASTInterface> beastObjects = new ArrayList<>();
distr.getPredecessors(beastObjects);
for (int i = beastObjects.size() - 1; i >= 0 ; i
beastObjects.get(i).initAndValidate();
}
try {
bounds.lower = distr.inverseCumulativeProbability(0.0) + distr.offsetInput.get();
bounds.upper = distr.inverseCumulativeProbability(1.0) + distr.offsetInput.get();
} catch (MathException e) {
Log.warning.println("At RandomTree::initStateNodes, bound on MRCAPrior could not be set " + e.getMessage());
}
}
if (prior.isMonophyleticInput.get()) {
// add any monophyletic constraint
taxonSets.add(lastMonophyletic, usedTaxa);
distributions.add(lastMonophyletic, distr);
m_bounds.add(lastMonophyletic, bounds);
taxonSetIDs.add(prior.getID());
lastMonophyletic++;
} else {
// only calibrations with finite bounds are added
if (!Double.isInfinite(bounds.lower) || !Double.isInfinite(bounds.upper)) {
taxonSets.add(usedTaxa);
distributions.add(distr);
m_bounds.add(bounds);
taxonSetIDs.add(prior.getID());
}
}
}
}
// assume all calibration constraints are MonoPhyletic
// TODO: verify that this is a reasonable assumption
lastMonophyletic = taxonSets.size();
// sort constraints such that if taxon set i is subset of taxon set j, then i < j
for (int i = 0; i < lastMonophyletic; i++) {
for (int j = i + 1; j < lastMonophyletic; j++) {
Set<String> intersection = new LinkedHashSet<>(taxonSets.get(i));
intersection.retainAll(taxonSets.get(j));
if (intersection.size() > 0) {
final boolean isSubset = taxonSets.get(i).containsAll(taxonSets.get(j));
final boolean isSubset2 = taxonSets.get(j).containsAll(taxonSets.get(i));
// sanity check: make sure either
// o taxonset1 is subset of taxonset2 OR
// o taxonset1 is superset of taxonset2 OR
// o taxonset1 does not intersect taxonset2
if (!(isSubset || isSubset2)) {
throw new IllegalArgumentException("333: Don't know how to generate a Random Tree for taxon sets that intersect, " +
"but are not inclusive. Taxonset " + taxonSetIDs.get(i) + " and " + taxonSetIDs.get(j));
}
// swap i & j if b1 subset of b2
if (isSubset) {
swap(taxonSets, i, j);
swap(distributions, i, j);
swap(m_bounds, i, j);
swap(taxonSetIDs, i, j);
}
}
}
}
// build tree of mono constraints such that j is parent of i if i is a subset of j but i+1,i+2,...,j-1 are not.
// The last one, standing for the virtual "root" of all monophyletic clades is not associated with an actual clade
final int[] parent = new int[lastMonophyletic];
children = new List[lastMonophyletic + 1];
for (int i = 0; i < lastMonophyletic + 1; i++) {
children[i] = new ArrayList<>();
}
for (int i = 0; i < lastMonophyletic; i++) {
int j = i + 1;
while (j < lastMonophyletic && !taxonSets.get(j).containsAll(taxonSets.get(i))) {
j++;
}
parent[i] = j;
children[j].add(i);
}
// make sure upper bounds of a child does not exceed the upper bound of its parent
for (int i = lastMonophyletic-1; i >= 0 ;--i) {
if (parent[i] < lastMonophyletic ) {
if (m_bounds.get(i).upper > m_bounds.get(parent[i]).upper) {
m_bounds.get(i).upper = m_bounds.get(parent[i]).upper - 1e-100;
}
}
}
final PopulationFunction popFunction = populationFunctionInput.get();
simulateTree(taxa, popFunction);
if (rootHeightInput.get() != null) {
scaleToFit(rootHeightInput.get() / root.getHeight(), root);
}
nodeCount = 2 * taxa.size() - 1;
internalNodeCount = taxa.size() - 1;
leafNodeCount = taxa.size();
HashMap<String,Integer> taxonToNR = null;
// preserve node numbers where possible
if (m_initial.get() != null) {
if( leafNodeCount == m_initial.get().getLeafNodeCount() ) {
// dont ask me how the initial tree is rubbish (i.e. 0:0.0)
taxonToNR = new HashMap<>();
for (Node n : m_initial.get().getExternalNodes()) {
taxonToNR.put(n.getID(), n.getNr());
}
}
} else {
taxonToNR = new HashMap<>();
String[] taxa = getTaxaNames();
for(int k = 0; k < taxa.length; ++k) {
taxonToNR.put(taxa[k], k);
}
}
// multiple simulation tries may produce an excess of nodes with invalid nr's. reset those.
setNodesNrs(root, 0, new int[1], taxonToNR);
initArrays();
if (m_initial.get() != null) {
m_initial.get().assignFromWithoutID(this);
}
for(int k = 0; k < lastMonophyletic; ++k) {
final MRCAPrior p = calibrations.get(k);
if( p.isMonophyleticInput.get() ) {
final TaxonSet taxonSet = p.taxonsetInput.get();
if (taxonSet == null) {
throw new IllegalArgumentException("Something is wrong with constraint " + p.getID() + " -- a taxonset must be specified if a monophyletic constraint is enforced.");
}
final Set<String> usedTaxa = new LinkedHashSet<>();
usedTaxa.addAll(taxonSet.asStringList());
/* int c = */ traverse(root, usedTaxa, taxonSet.getTaxonCount(), new int[1]);
// boolean b = c == nrOfTaxa + 127;
}
}
}
private int setNodesNrs(final Node node, int internalNodeCount, int[] n, Map<String,Integer> initial) {
if( node.isLeaf() ) {
if( initial != null ) {
node.setNr(initial.get(node.getID()));
} else {
node.setNr(n[0]);
n[0] += 1;
}
} else {
for (final Node child : node.getChildren()) {
internalNodeCount = setNodesNrs(child, internalNodeCount, n, initial);
}
node.setNr(nrOfTaxa + internalNodeCount);
internalNodeCount += 1;
}
return internalNodeCount;
}
private void scaleToFit(double scale, Node node) {
if (!node.isLeaf()) {
double oldHeight = node.getHeight();
node.height *= scale;
final Integer constraint = getDistrConstraint(node);
if (constraint != null) {
if (node.height < m_bounds.get(constraint).lower || node.height > m_bounds.get(constraint).upper) {
//revert scaling
node.height = oldHeight;
return;
}
}
scaleToFit(scale, node.getLeft());
scaleToFit(scale, node.getRight());
if (node.height < Math.max(node.getLeft().getHeight(), node.getRight().getHeight())) {
// this can happen if a child node is constrained and the default tree is higher than desired
node.height = 1.0000001 * Math.max(node.getLeft().getHeight(), node.getRight().getHeight());
}
}
}
//@Override
@Override
public void getInitialisedStateNodes(final List<StateNode> stateNodes) {
stateNodes.add(m_initial.get());
}
/**
* Simulates a coalescent tree, given a taxon list.
*
* @param taxa the set of taxa to simulate a coalescent tree between
* @param demoFunction the demographic function to use
*/
public void simulateTree(final Set<String> taxa, final PopulationFunction demoFunction) {
if (taxa.size() == 0)
return;
String msg = "Failed to generate a random tree (probably a bug).";
for (int attempts = 0; attempts < 1000; ++attempts) {
try {
nextNodeNr = nrOfTaxa;
final Set<Node> candidates = new LinkedHashSet<>();
int i = 0;
for (String taxon : taxa) {
final Node node = newNode();
node.setNr(i);
node.setID(taxon);
node.setHeight(0.0);
candidates.add(node);
i += 1;
}
if (m_initial.get() != null) {
processCandidateTraits(candidates, m_initial.get().m_traitList.get());
} else {
processCandidateTraits(candidates, m_traitList.get());
}
final Map<String,Node> allCandidates = new TreeMap<>();
for (Node node: candidates) {
allCandidates.put(node.getID(),node);
}
root = simulateCoalescent(lastMonophyletic, allCandidates, candidates, demoFunction);
return;
} catch (ConstraintViolatedException e) {
// need to generate another tree
msg = "\nWARNING: Generating a random tree did not succeed. The most common reasons are:\n";
msg += "1. there are conflicting monophyletic constraints, for example if both (A,B) \n"
+ "and (B,C) must be monophyletic no tree will be able to meet these constraints at the same \n"
+ "time. To fix this, carefully check all clade sets, especially the ones that are expected to \n"
+ "be nested clades.\n";
msg += "2. clade heights are constrained by an upper and lower bound, but the population size \n"
+ "is too large, so it is very unlikely a generated treed does not violate these constraints. To \n"
+ "fix this you can try to reduce the population size of the population model.\n";
msg += "Expect BEAST to crash if this is not fixed.\n";
Log.err.println(msg);
}
}
throw new RuntimeException(msg);
}
/**
* Apply traits to a set of nodes.
* @param candidates List of nodes
* @param traitSets List of TraitSets to apply
*/
private void processCandidateTraits(Set<Node> candidates, List<TraitSet> traitSets) {
for (TraitSet traitSet : traitSets) {
for (Node node : candidates) {
node.setMetaData(traitSet.getTraitName(), traitSet.getValue(node.getID()));
}
}
}
private Node simulateCoalescent(final int isMonophyleticNode, final Map<String,Node> allCandidates, final Set<Node> candidates, final PopulationFunction demoFunction)
throws ConstraintViolatedException {
final List<Node> remainingCandidates = new ArrayList<>();
final Set<String> taxaDone = new TreeSet<>();
for (final int monoNode : children[isMonophyleticNode]) {
// create list of leaf nodes for this monophyletic MRCA
final Set<Node> candidates2 = new LinkedHashSet<>();
final Set<String> isTaxonSet = taxonSets.get(monoNode);
for (String taxon : isTaxonSet) {
candidates2.add(allCandidates.get(taxon));
}
final Node MRCA = simulateCoalescent(monoNode, allCandidates, candidates2, demoFunction);
remainingCandidates.add(MRCA);
taxaDone.addAll(isTaxonSet);
}
for (final Node node : candidates) {
if (!taxaDone.contains(node.getID())) {
remainingCandidates.add(node);
}
}
final double upper = isMonophyleticNode < m_bounds.size() ? m_bounds.get(isMonophyleticNode).upper : Double.POSITIVE_INFINITY;
final Node MRCA = simulateCoalescentWithMax(remainingCandidates, demoFunction, upper);
return MRCA;
}
// /**
// * @param id the id to match
// * @param nodes a list of nodes
// * @return the node with the matching id;
// */
// private Node getNodeById(String id, List<Node> nodes) {
// for (Node node : nodes) {
// if (node.getID().equals(id)) return node;
// return null;
/**
* @param nodes
* @param demographic
* @return the root node of the given array of nodes after simulation of the
* coalescent under the given demographic model.
* @throws beast.evolution.tree.RandomTree.ConstraintViolatedException
*/
// public Node simulateCoalescent(final List<Node> nodes, final PopulationFunction demographic) throws ConstraintViolatedException {
// return simulateCoalescentWithMax(nodes, demographic, Double.POSITIVE_INFINITY);
/**
* @param nodes
* @param demographic
* @return the root node of the given array of nodes after simulation of the
* coalescent under the given demographic model.
* @throws beast.evolution.tree.RandomTree.ConstraintViolatedException
*/
public Node simulateCoalescentWithMax(final List<Node> nodes, final PopulationFunction demographic,
final double maxHeight) throws ConstraintViolatedException {
// sanity check - disjoint trees
// if( ! Tree.Utils.allDisjoint(nodes) ) {
// throw new RuntimeException("non disjoint trees");
if (nodes.size() == 0) {
throw new IllegalArgumentException("empty nodes set");
}
for (int attempts = 0; attempts < 1000; ++attempts) {
final List<Node> rootNode = simulateCoalescent(nodes, demographic, 0.0, maxHeight);
if (rootNode.size() == 1) {
return rootNode.get(0);
}
}
if( Double.isFinite(maxHeight) ){
double h = -1;
for( Node n : nodeList ) {
h = Math.max(h, n.getHeight());
}
assert h < maxHeight;
double dt = (maxHeight - h)/ (nodeList.size() + 1);
while (nodeList.size() > 1) {
int k = nodeList.size() - 1;
final Node left = nodeList.remove(k);
final Node right = nodeList.get(k-1);
final Node newNode = newNode();
newNode.setNr(nextNodeNr++); // multiple tries may generate an excess of nodes assert(nextNodeNr <= nrOfTaxa*2-1);
newNode.setHeight(h + dt);
newNode.setLeft(left);
left.setParent(newNode);
newNode.setRight(right);
right.setParent(newNode);
nodeList.set(k-1, newNode);
}
assert (nodeList.size() == 1);
return nodeList.get(0);
}
throw new RuntimeException("failed to merge trees after 1000 tries!");
}
public List<Node> simulateCoalescent(final List<Node> nodes, final PopulationFunction demographic, double currentHeight,
final double maxHeight) throws ConstraintViolatedException {
// If only one node, return it
// continuing results in an infinite loop
if (nodes.size() == 1)
return nodes;
final double[] heights = new double[nodes.size()];
for (int i = 0; i < nodes.size(); i++) {
heights[i] = nodes.get(i).getHeight();
}
final int[] indices = new int[nodes.size()];
HeapSort.sort(heights, indices);
// node list
nodeList.clear();
activeNodeCount = 0;
for (int i = 0; i < nodes.size(); i++) {
nodeList.add(nodes.get(indices[i]));
}
setCurrentHeight(currentHeight);
// get at least two tips
while (getActiveNodeCount() < 2) {
currentHeight = getMinimumInactiveHeight();
setCurrentHeight(currentHeight);
}
// simulate coalescent events
double nextCoalescentHeight = currentHeight
+ PopulationFunction.Utils.getSimulatedInterval(demographic, getActiveNodeCount(), currentHeight);
// while (nextCoalescentHeight < maxHeight && (getNodeCount() > 1)) {
while (nextCoalescentHeight < maxHeight && (nodeList.size() > 1)) {
if (nextCoalescentHeight >= getMinimumInactiveHeight()) {
currentHeight = getMinimumInactiveHeight();
setCurrentHeight(currentHeight);
} else {
currentHeight = coalesceTwoActiveNodes(currentHeight, nextCoalescentHeight);
}
// if (getNodeCount() > 1) {
if (nodeList.size() > 1) {
// get at least two tips
while (getActiveNodeCount() < 2) {
currentHeight = getMinimumInactiveHeight();
setCurrentHeight(currentHeight);
}
// nextCoalescentHeight = currentHeight +
// DemographicFunction.Utils.getMedianInterval(demographic,
// getActiveNodeCount(), currentHeight);
nextCoalescentHeight = currentHeight
+ PopulationFunction.Utils.getSimulatedInterval(demographic, getActiveNodeCount(),
currentHeight);
}
}
return nodeList;
}
/**
* @return the height of youngest inactive node.
*/
private double getMinimumInactiveHeight() {
if (activeNodeCount < nodeList.size()) {
return (nodeList.get(activeNodeCount)).getHeight();
} else
return Double.POSITIVE_INFINITY;
}
/**
* Set the current height.
* @param height
*/
private void setCurrentHeight(final double height) {
while (getMinimumInactiveHeight() <= height) {
activeNodeCount += 1;
}
}
/**
* @return the number of active nodes (equate to lineages)
*/
private int getActiveNodeCount() {
return activeNodeCount;
}
// /**
// * @return the total number of nodes both active and inactive
// */
// private int getNodeCount() {
// return nodeList.size();
/**
* Coalesce two nodes in the active list. This method removes the two
* (randomly selected) active nodes and replaces them with the new node at
* the top of the active list.
* @param minHeight
* @param height
* @return
*/
private double coalesceTwoActiveNodes(final double minHeight, double height) throws ConstraintViolatedException {
final int node1 = Randomizer.nextInt(activeNodeCount);
int node2 = node1;
while (node2 == node1) {
node2 = Randomizer.nextInt(activeNodeCount);
}
final Node left = nodeList.get(node1);
final Node right = nodeList.get(node2);
final Node newNode = newNode();
// System.err.println(2 * m_taxa.get().getNrTaxa() - nodeList.size());
newNode.setNr(nextNodeNr++); // multiple tries may generate an excess of nodes assert(nextNodeNr <= nrOfTaxa*2-1);
newNode.setHeight(height);
newNode.setLeft(left);
left.setParent(newNode);
newNode.setRight(right);
right.setParent(newNode);
nodeList.remove(left);
nodeList.remove(right);
activeNodeCount -= 2;
nodeList.add(activeNodeCount, newNode);
activeNodeCount += 1;
// check if there is a calibration on this node
final Integer constraint = getDistrConstraint(newNode);
if (constraint != null) {
// for (int i = 0; i < 1000; i++) {
// try {
// height = distr.sample(1)[0][0];
// } catch (Exception e) {
// e.printStackTrace();
// if (height > minHeight) {
// break;
final double min = Math.max(m_bounds.get(constraint).lower, minHeight);
final double max = m_bounds.get(constraint).upper;
if (max < min) {
// failed to draw a matching height from the MRCA distribution
// TODO: try to scale rest of tree down
throw new ConstraintViolatedException();
}
if (height < min || height > max) {
if (max == Double.POSITIVE_INFINITY) {
height = min + 0.1;
} else {
height = min + Randomizer.nextDouble() * (max - min);
}
newNode.setHeight(height);
}
}
if (getMinimumInactiveHeight() < height) {
throw new RuntimeException(
"This should never happen! Somehow the current active node is older than the next inactive node!\n"
+ "One possible solution you can try is to increase the population size of the population model.");
}
return height;
}
private Integer getDistrConstraint(final Node node) {
for (int i = 0; i < distributions.size(); i++) {
if (distributions.get(i) != null) {
final Set<String> taxonSet = taxonSets.get(i);
if (traverse(node, taxonSet, taxonSet.size(), new int[1]) == nrOfTaxa + 127) {
return i;
}
}
}
return null;
}
int traverse(final Node node, final Set<String> MRCATaxonSet, final int nrOfMRCATaxa, final int[] taxonCount) {
if (node.isLeaf()) {
taxonCount[0]++;
if (MRCATaxonSet.contains(node.getID())) {
return 1;
} else {
return 0;
}
} else {
int taxons = traverse(node.getLeft(), MRCATaxonSet, nrOfMRCATaxa, taxonCount);
final int leftTaxa = taxonCount[0];
taxonCount[0] = 0;
if (node.getRight() != null) {
taxons += traverse(node.getRight(), MRCATaxonSet, nrOfMRCATaxa, taxonCount);
final int rightTaxa = taxonCount[0];
taxonCount[0] = leftTaxa + rightTaxa;
}
if (taxons == nrOfTaxa + 127) {
taxons++;
}
if (taxons == nrOfMRCATaxa) {
// we are at the MRCA, return magic nr
return nrOfTaxa + 127;
}
return taxons;
}
}
@Override
public String[] getTaxaNames() {
if (m_sTaxaNames == null) {
final List<String> taxa;
if (taxaInput.get() != null) {
taxa = taxaInput.get().getTaxaNames();
} else {
taxa = m_taxonset.get().asStringList();
}
m_sTaxaNames = taxa.toArray(new String[taxa.size()]);
}
return m_sTaxaNames;
}
final private ArrayList<Node> nodeList = new ArrayList<>();
private int activeNodeCount = 0;
}
|
package com.alibaba.json.bvt.issue_1300;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.alibaba.fastjson.support.spring.FastJsonpHttpMessageConverter4;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.io.Serializable;
import java.util.List;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration
public class Issue1367 {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
.addFilter(new CharacterEncodingFilter("UTF-8", true)) // UTF-8
.build();
}
public static class AbstractController<ID extends Serializable, PO extends GenericEntity<ID>> {
@PostMapping(path = "/typeVariableBean",consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public PO save(@RequestBody PO dto) {
//do something
return dto;
}
}
@RestController
@RequestMapping()
public static class BeanController extends AbstractController<Long, TypeVariableBean> {
@PostMapping(path = "/parameterizedTypeBean",consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String parameterizedTypeBean(@RequestBody ParameterizedTypeBean<String> parameterizedTypeBean){
return parameterizedTypeBean.t;
}
}
@ComponentScan(basePackages = "com.alibaba.json.bvt.issue_1300")
@Configuration
@Order(Ordered.LOWEST_PRECEDENCE + 1)
@EnableWebMvc
public static class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
converters.add(converter);
}
}
@Test
public void testParameterizedTypeBean() throws Exception {
mockMvc.perform(
(post("/parameterizedTypeBean").characterEncoding("UTF-8")
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
.content("{\"t\": \"neil dong\"}")
)).andExpect(status().isOk()).andDo(print());
}
@Test
public void testTypeVariableBean() throws Exception {
mockMvc.perform(
(post("/typeVariableBean").characterEncoding("UTF-8")
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
.content("{\"id\": 1}")
)).andExpect(status().isOk()).andDo(print());
}
static abstract class GenericEntity<ID extends Serializable> {
public abstract ID getId();
}
static class TypeVariableBean extends GenericEntity<Long> {
private Long id;
@Override
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
static class ParameterizedTypeBean<T> {
private T t;
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
}
}
|
package net.whydah.crmservice.util;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.name.Named;
import org.valuereporter.agent.activity.ObservedActivityDistributer;
import org.valuereporter.agent.http.HttpObservationDistributer;
public class ReporterModule extends AbstractModule {
@Override
protected void configure() {
}
@Provides
String reporterClient(@Named("valuereporter.host") String reporterHost,
@Named("valuereporter.port") String reporterPort,
@Named("applicationname") String prefix,
@Named("valuereporter.activity.batchsize") int cacheSize,
@Named("valuereporter.activity.postintervalms") int forwardInterval) {
//Start Valuereporter event distributer.
new Thread(new ObservedActivityDistributer(reporterHost, reporterPort, prefix, cacheSize, forwardInterval)).start();
new Thread(new HttpObservationDistributer(reporterHost, reporterPort, prefix)).start();
return "reporterClient started";
}
}
|
package next.operator.linebot.talker;
import com.linecorp.bot.client.LineMessagingClient;
import com.linecorp.bot.model.event.MessageEvent;
import com.linecorp.bot.model.event.message.TextMessageContent;
import next.operator.currency.enums.CurrencyType;
import next.operator.currency.model.CurrencyExrateModel;
import next.operator.currency.service.CurrencyService;
import next.operator.linebot.executor.impl.ExrateExecutor;
import next.operator.linebot.service.RespondentTalkable;
import org.ansj.domain.Term;
import org.ansj.splitWord.analysis.NlpAnalysis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Iterator;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.StreamSupport;
@Service
public class ExrateTalker implements RespondentTalkable {
@Autowired
private ExrateExecutor exrateExecutor;
@Autowired
private CurrencyService currencyService;
private ThreadLocal<CurrencyType> currentMached = new ThreadLocal<>();
@Override
public boolean isReadable(String message) {
final Iterator<Term> sourceIterator = NlpAnalysis.parse(message).iterator();
Iterable<Term> iterable = () -> sourceIterator;
final Optional<CurrencyType> matchedCurrenctType = StreamSupport.stream(iterable.spliterator(), false)
.map(Term::getName)
.map(CurrencyType::tryParseByName)
.filter(Optional::isPresent)
.filter(o -> CurrencyType.TWD != o.get())
.map(Optional::get)
.findFirst();
matchedCurrenctType.ifPresent(currentMached::set);
return matchedCurrenctType.isPresent();
}
@Override
public Consumer<MessageEvent<TextMessageContent>> doFirst(LineMessagingClient client) {
return null;
}
@Override
public String talk(String message) {
final CurrencyType matchedCurrenctType = currentMached.get();
currentMached.remove();
final CurrencyExrateModel exrate = currencyService.getExrate(matchedCurrenctType.name(), CurrencyType.TWD.name());
return "" + matchedCurrenctType.getFirstLocalName() + "\n" +
"1 " + exrate.getExFrom() + " = " + exrateExecutor.fullDecimalFormat.format(exrate.getExrate()) + " " + exrate.getExTo() +
", " + exrateExecutor.dateTimeFormatter.format(exrate.getTime());
}
}
|
package com.kryptnostic.crypto.v1.keys;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kryptnostic.crypto.EncryptedSearchPrivateKey;
import com.kryptnostic.crypto.PrivateKey;
import com.kryptnostic.crypto.PublicKey;
import com.kryptnostic.crypto.v1.ciphers.Cypher;
import com.kryptnostic.crypto.v1.keys.Kodex.CorruptKodexException;
import com.kryptnostic.crypto.v1.keys.Kodex.SealedKodexException;
import com.kryptnostic.kodex.v1.serialization.jackson.KodexObjectMapperFactory;
import com.kryptnostic.linear.EnhancedBitMatrix.SingularMatrixException;
import com.kryptnostic.users.v1.UserKey;
public class KodexTests {
private static KeyPair pair;
private static KodexMarshaller<UserKey> marshaller;
private static PrivateKey privateKey = new PrivateKey( 128, 64 );
private static PublicKey publicKey = new PublicKey( privateKey );
private static EncryptedSearchPrivateKey searchKey;
@BeforeClass
public static void generateKeys() throws NoSuchAlgorithmException, SingularMatrixException {
pair = Keys.generateRsaKeyPair( 1024 );
searchKey = new EncryptedSearchPrivateKey( 8 );
marshaller = new JacksonKodexMarshaller<UserKey>( UserKey.class );
}
@Test
public void testSerializeDeserialize() throws InvalidKeyException, InvalidKeySpecException,
NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException,
InvalidParameterSpecException, SealedKodexException, IOException, InvalidAlgorithmParameterException,
SignatureException, CorruptKodexException {
Kodex<String> expected = new Kodex<String>(
Cypher.RSA_OAEP_SHA1_1024,
Cypher.AES_CTR_PKCS5_128,
pair.getPublic() );
Assert.assertTrue( expected.isSealed() );
expected.unseal( pair.getPrivate() );
Assert.assertTrue( !expected.isSealed() );
expected.setKey( "test", marshaller, new UserKey( "kryptnostic", "tester" ) );
expected.seal();
Assert.assertTrue( expected.isSealed() );
expected.unseal( pair.getPrivate() );
Assert.assertTrue( !expected.isSealed() );
expected.setKeyWithJackson( PrivateKey.class.getCanonicalName(), privateKey, PrivateKey.class );
expected.setKeyWithJackson( PublicKey.class.getCanonicalName(), publicKey, PublicKey.class );
expected.setKeyWithJackson(
EncryptedSearchPrivateKey.class.getCanonicalName(),
searchKey,
EncryptedSearchPrivateKey.class );
ObjectMapper mapper = KodexObjectMapperFactory.getObjectMapper();
String k = mapper.writeValueAsString( expected );
Kodex<String> actual = mapper.readValue( k, new TypeReference<Kodex<String>>() {} );
Assert.assertTrue( actual.isSealed() );
actual.unseal( pair.getPrivate() );
Assert.assertEquals( expected.getKey( "test", marshaller ), actual.getKey( "test", marshaller ) );
Assert.assertEquals(
privateKey,
expected.getKeyWithJackson( PrivateKey.class.getCanonicalName(), PrivateKey.class ) );
Assert.assertEquals(
publicKey,
expected.getKeyWithJackson( PublicKey.class.getCanonicalName(), PublicKey.class ) );
EncryptedSearchPrivateKey recoveredSearchKey = expected.getKeyWithJackson(
EncryptedSearchPrivateKey.class.getCanonicalName(),
EncryptedSearchPrivateKey.class );
Assert.assertEquals( searchKey.getLeftSquaringMatrix(), recoveredSearchKey.getLeftSquaringMatrix() );
Assert.assertEquals( searchKey.getRightSquaringMatrix(), recoveredSearchKey.getRightSquaringMatrix() );
}
}
|
package nl.hsac.fitnesse.fixture.slim;
import fitnesse.slim.fixtureInteraction.FixtureInteraction;
import fitnesse.slim.fixtureInteraction.InteractionAwareFixture;
import nl.hsac.fitnesse.fixture.Environment;
import nl.hsac.fitnesse.fixture.util.FileUtil;
import nl.hsac.fitnesse.slim.interaction.ExceptionHelper;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.function.Supplier;
/**
* Base class for Slim fixtures.
*/
public class SlimFixture implements InteractionAwareFixture {
protected final Logger logger;
private Environment environment = Environment.getInstance();
private int repeatInterval = 100;
private int repeatMaxCount = 30_000;
private StopWatch repeatTimer = new StopWatch();
private int repeatCount = 0;
private long repeatTime = 0;
protected final String filesDir = getEnvironment().getFitNesseFilesSectionDir();
public SlimFixture() {
logger = LoggerFactory.getLogger(getClass());
}
@Override
public Object aroundSlimInvoke(FixtureInteraction interaction, Method method, Object... arguments)
throws InvocationTargetException, IllegalAccessException {
Object result;
try {
beforeInvoke(method, arguments);
result = invoke(interaction, method, arguments);
} catch (Throwable t) {
Throwable realEx = ExceptionHelper.stripReflectionException(t);
Throwable toThrow = handleException(method, arguments, realEx);
if (toThrow instanceof RuntimeException) {
throw (RuntimeException) toThrow;
} else if (toThrow instanceof Error) {
throw (Error) toThrow;
}
throw ExceptionHelper.wrapInReflectionException(toThrow);
}
result = afterCompletion(method, arguments, result);
return result;
}
protected void beforeInvoke(Method method, Object[] arguments) {
}
protected Object invoke(FixtureInteraction interaction, Method method, Object[] arguments)
throws Throwable {
return interaction.methodInvoke(method, this, arguments);
}
protected Throwable handleException(Method method, Object[] arguments, Throwable t) {
// convert any Fit, non-stacktrace, exception to our Slim equivalent
if (t instanceof fit.exception.FitFailureException) {
String m = t.getMessage();
t = new SlimFixtureException(false, "<div>" + m + "</div>");
}
return t;
}
protected Object afterCompletion(Method method, Object[] arguments, Object result) {
return result;
}
/**
* @return environment to be used.
*/
protected Environment getEnvironment() {
return environment;
}
protected String getUrl(String htmlLink) {
return getEnvironment().getHtmlCleaner().getUrl(htmlLink);
}
/**
* Stores a (global) value so it can be accessed by other fixtures/pages.
* @param symbolName name to store value under.
* @param value value to store.
*/
public void setGlobalValueTo(String symbolName, String value) {
getEnvironment().setSymbol(symbolName, value);
}
/**
* Retrieves a (global) value, which was previously stored using #setGlobalValueTo().
* @param symbolName name value was stored under.
*/
public String globalValue(String symbolName) {
return getEnvironment().getSymbol(symbolName);
}
/**
* Removes result of wiki formatting (for e.g. email addresses) if needed.
* @param rawValue value as received from FitNesse.
* @return rawValue if it was just text, cleaned version if it was not.
*/
protected <T> T cleanupValue(T rawValue) {
return getEnvironment().getHtmlCleaner().cleanupValue(rawValue);
}
public boolean waitSeconds(int i) {
return waitMilliseconds(i * 1000);
}
public boolean waitMilliseconds(int i) {
boolean result;
try {
Thread.sleep(i);
result = true;
} catch (InterruptedException e) {
result = false;
}
return result;
}
// Polling
public void setRepeatIntervalToMilliseconds(int milliseconds) {
repeatInterval = milliseconds;
}
public long repeatInterval() {
return repeatInterval;
}
public void repeatAtMostTimes(int maxCount) {
repeatMaxCount = maxCount;
}
public int repeatAtMostTimes() {
return repeatMaxCount;
}
public int repeatCount() {
return repeatCount;
}
public long timeSpentRepeating() {
return repeatTime;
}
protected boolean repeatUntil(RepeatCompletion repeat) {
repeatTime = 0;
repeatTimer.start();
StopWatch loopTimer = new StopWatch();
loopTimer.start();
boolean result = false;
try {
try {
result = repeat.isFinished();
} catch (RuntimeException e) {
logger.warn("Error while checking we can stop repeating before starting loop", e);
}
for (repeatCount = 0; !result && repeatCount < repeatMaxCount; repeatCount++) {
int nextInterval = getNextInterval(loopTimer);
waitMilliseconds(nextInterval);
loopTimer.start();
repeat.repeat();
try {
result = repeat.isFinished();
} catch (RuntimeException e) {
logger.warn("Error while checking whether we can stop repeating, loop count {} of {}",
repeatCount, repeatMaxCount, e);
}
}
} finally {
repeatTime = repeatTimer.getTime();
repeatTimer.reset();
}
return result;
}
private int getNextInterval(StopWatch loopTimer) {
int nextInterval;
long loopTime = loopTimer.getTime();
nextInterval = Math.max(0, ((int) (repeatInterval - loopTime)));
loopTimer.reset();
return nextInterval;
}
protected boolean repeatUntilNot(RepeatCompletion repeat) {
return repeatUntil(new Negate(repeat));
}
/**
* Interface to repeat a call until a condition is met.
*/
public interface RepeatCompletion {
/**
* @return true if no more repeats are needed.
*/
boolean isFinished();
/**
* Performs the action again.
*/
void repeat();
}
/**
* RepeatCompletion which negates the completion condition of another completion, but performs same action.
*/
public class Negate implements RepeatCompletion {
private final RepeatCompletion nested;
/**
* Creates new with same action, but the exact opposite completion condition.
* @param nested completion whose #isFinished() will be negated.
*/
public Negate(RepeatCompletion nested) {
this.nested = nested;
}
@Override
public boolean isFinished() {
return !nested.isFinished();
}
@Override
public void repeat() {
nested.repeat();
}
}
/**
* RepeatCompletion using optional Runnable in repeat, calls function to determine whether it is completed.
*/
public static class FunctionalCompletion implements RepeatCompletion {
private Supplier<Boolean> isFinishedSupplier;
private Runnable repeater;
public FunctionalCompletion() {
}
public FunctionalCompletion(Supplier<Boolean> isFinishedSupplier) {
this(isFinishedSupplier, null);
}
public FunctionalCompletion(Supplier<Boolean> isFinishedSupplier, Runnable repeater) {
setIsFinishedSupplier(isFinishedSupplier);
setRepeater(repeater);
}
@Override
public boolean isFinished() {
return Boolean.TRUE.equals(isFinishedSupplier.get());
}
@Override
public void repeat() {
if (repeater != null) {
repeater.run();
}
}
public void setIsFinishedSupplier(Supplier<Boolean> isFinishedSupplier) {
this.isFinishedSupplier = isFinishedSupplier;
}
public void setRepeater(Runnable repeater) {
this.repeater = repeater;
}
}
// Polling
/**
* Creates a file using the supplied content.
* @param dir directory to create file in.
* @param fileName name for file.
* @param content content to save.
* @return link to created file.
*/
protected String createFile(String dir, String fileName, byte[] content) {
String baseName = FilenameUtils.getBaseName(fileName);
String ext = FilenameUtils.getExtension(fileName);
String downloadedFile = FileUtil.saveToFile(dir + baseName, ext, content);
return linkToFile(downloadedFile);
}
/**
* Converts a file path into a relative wiki path, if the path is insides the wiki's 'files' section.
* @param filePath path to file.
* @return relative URL pointing to the file (so a hyperlink to it can be created).
*/
protected String getWikiUrl(String filePath) {
return getEnvironment().getWikiUrl(filePath);
}
/**
* Creates a wiki link to a file.
* @param f file.
* @return link referencing the file.
*/
protected String linkToFile(String f) {
return linkToFile(new File(f));
}
/**
* Creates a wiki link to a file.
* @param f file.
* @return link referencing the file.
*/
protected String linkToFile(File f) {
String url = getWikiUrl(f.getAbsolutePath());
if (url == null) {
url = f.toURI().toString();
}
return String.format("<a href=\"%s\" target=\"_blank\">%s</a>", url, f.getName());
}
/**
* Gets absolute path from wiki url, if file exists.
* @param wikiUrl a relative path that can be used in wiki page, or any file path.
* @return absolute path to the target of the url, if such a file exists; null if the target does not exist.
*/
protected String getFilePathFromWikiUrl(String wikiUrl) {
return getEnvironment().getFilePathFromWikiUrl(wikiUrl);
}
}
|
package hudson.plugins.warnings.parser;
import static org.junit.Assert.*;
import hudson.plugins.analysis.core.AnnotationDifferencer;
import hudson.plugins.analysis.util.TreeString;
import hudson.plugins.analysis.util.model.FileAnnotation;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
/**
* Tests the class {@link Warning}.
*
* @author Ulli Hafner
*/
public class WarningTest {
@Test
public void testEqualsIssue14821() {
Warning expected = createWarning();
expected.setContextHashCode(1);
Warning actual = createWarning();
expected.setContextHashCode(2);
assertEquals("The objects are not the same", expected, actual);
Set<FileAnnotation> current = new HashSet<FileAnnotation>();
current.add(expected);
Set<FileAnnotation> reference = new HashSet<FileAnnotation>();
reference.add(actual);
Set<FileAnnotation> annotations = AnnotationDifferencer.getNewAnnotations(current, reference);
assertTrue("There are new warnings", annotations.isEmpty());
}
@Test
public void testEqualsIssue15250() {
Warning first = createWarning();
Warning second = createWarning();
assertEquals("The objects are not the same", first, second);
first.setPackageName("something");
assertFalse("The objects are the same", first.equals(second));
first.setModuleName("something");
assertFalse("The objects are the same", first.equals(second));
}
private Warning createWarning() {
return new Warning("filename", 0, "type", "category", "message");
}
}
|
package no.ntnu.okse.web.controller;
import no.ntnu.okse.web.model.Log;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@RestController
@RequestMapping(value = "/api/log")
public class LogController {
@RequestMapping(method = RequestMethod.GET)
public ArrayList<Log> log() throws IOException {
ArrayList<Log> logs = new ArrayList<>();
File dir = new File("logs");
Collection<File> files = FileUtils.listFiles(dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
for (File file : files) {
String name = file.getName();
List<String> lines = FileUtils.readLines(file);
Log log = new Log(name, lines);
logs.add(log);
}
return logs;
}
}
|
package io.pivotal.cla.webdriver.smoke;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.eclipse.egit.github.core.PullRequest;
import org.eclipse.egit.github.core.PullRequestMarker;
import org.eclipse.egit.github.core.Reference;
import org.eclipse.egit.github.core.Repository;
import org.eclipse.egit.github.core.RepositoryId;
import org.eclipse.egit.github.core.client.GitHubClient;
import org.eclipse.egit.github.core.service.DataService;
import org.eclipse.egit.github.core.service.PullRequestService;
import org.eclipse.egit.github.core.service.RepositoryService;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.client.RestTemplate;
import io.pivotal.cla.webdriver.pages.SignClaPage;
import io.pivotal.cla.webdriver.pages.SignIclaPage;
import io.pivotal.cla.webdriver.pages.admin.AdminLinkClaPage;
import io.pivotal.cla.webdriver.pages.github.GitHubLoginPage;
import io.pivotal.cla.webdriver.pages.github.GitHubPullRequestPage;
@Category(io.pivotal.cla.junit.SmokeTests.class)
public class SmokeTests {
static WebDriver driverForLinkUser;
static WebDriver driverForSignUser;
static User linkUser;
static User signUser;
@BeforeClass
public static void setup() throws Exception {
linkUser = new User();
linkUser.setGitHubUsername("pivotal-cla-link");
linkUser.setGitHubPassword(getPasswordFor("linkUser"));
linkUser.setGitHubAccessToken(getTokenFor("linkUser"));
signUser = new User();
signUser.setGitHubUsername("pivotal-cla-signer");
signUser.setGitHubPassword(getPasswordFor("signUser"));
signUser.setGitHubAccessToken(getTokenFor("signUser"));
createTestRepository(linkUser);
forkRepositoryFor(linkUser.getGitHubUsername() + "/cla-test", signUser);
driverForLinkUser = new FirefoxDriver();
driverForSignUser = new FirefoxDriver();
}
private static String getPasswordFor(String user) {
return System.getProperty("smokeTest." + user + ".password");
}
private static String getTokenFor(String user) {
return System.getProperty("smokeTest." + user + ".token");
}
private static void forkRepositoryFor(String toFork, User user) throws IOException {
GitHubClient client = createClient(user.getGitHubAccessToken());
RepositoryService repository = new RepositoryService(client);
RestTemplate rest = new RestTemplate();
try {
rest.delete("https://api.github.com/repos/{owner}/{repo}?access_token={token}", user.getGitHubUsername(), "cla-test", user.getGitHubAccessToken());
}catch(Throwable t) {
t.printStackTrace();
}
repository.forkRepository(RepositoryId.createFromId(toFork));
}
private static void createTestRepository(User user) throws Exception {
GitHubClient client = createClient(user.getGitHubAccessToken());
RepositoryService repository = new RepositoryService(client);
Repository toCreate = new Repository();
toCreate.setName("cla-test");
RestTemplate rest = new RestTemplate();
try {
rest.delete("https://api.github.com/repos/{owner}/{repo}?access_token={token}", user.getGitHubUsername(), toCreate.getName(), user.getGitHubAccessToken());
}catch(Throwable t) {
t.printStackTrace();
}
repository.createRepository(toCreate);
Thread.sleep(TimeUnit.SECONDS.toMillis(1L));
// we need content to allow forking
Map<String,String> content = new HashMap<>();
content.put("message", "Initial");
content.put("content", "bXkgbmV3IGZpbGUgY29udGVudHM=");
rest.put("https://api.github.com/repos/{owner}/{repo}/contents/README.adoc?access_token={token}", content, user.getGitHubUsername(), toCreate.getName(), user.getGitHubAccessToken());
}
/**
* @return the HTML link of the Pull Request
* @throws InterruptedException
*/
private static String createPullRequest(User user, int count) throws IOException, InterruptedException {
GitHubClient client = createClient(user.getGitHubAccessToken());
PullRequestService pulls = new PullRequestService(client);
RestTemplate rest = new RestTemplate();
// get sha for master
DataService references = new DataService(client);
RepositoryId forkRepositoryId = RepositoryId.create(user.getGitHubUsername(), "cla-test");
Reference forked = references.getReference(forkRepositoryId, "heads/master");
// create a branch for our Pull Request
Reference createPullRequestBranch = new Reference();
createPullRequestBranch.setRef("refs/heads/pull-" + count);
createPullRequestBranch.setObject(forked.getObject());
references.createReference(forkRepositoryId, createPullRequestBranch);
// create a file for our Pull Request
Map<String,String> content = new HashMap<>();
content.put("message", "We added some content for "+ count);
content.put("content", "bXkgbmV3IGZpbGUgY29udGVudHM=");
content.put("branch", "pull-"+count);
rest.put("https://api.github.com/repos/{owner}/{repo}/contents/forPullRequest?access_token={token}", content, user.getGitHubUsername(), "cla-test", user.getGitHubAccessToken());
PullRequest request = new PullRequest();
request.setTitle("Please merge");
request.setBody("Please merge");
PullRequestMarker head = new PullRequestMarker();
head.setLabel(signUser.getGitHubUsername() + ":pull-" + count);
request.setHead(head);
PullRequestMarker base = new PullRequestMarker();
base.setLabel("master");
request.setBase(base);
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
PullRequest newPull = pulls.createPullRequest(RepositoryId.createFromId(linkUser.getGitHubUsername() + "/" + "cla-test"), request );
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
return newPull.getHtmlUrl();
}
private static GitHubClient createClient(String token) {
GitHubClient client = new GitHubClient();
client.setOAuth2Token(token);
return client;
}
@AfterClass
public static void cleanup() {
if(driverForLinkUser != null) {
driverForLinkUser.close();
}
if(driverForSignUser != null) {
driverForSignUser.close();
}
}
@Test
public void all() throws Exception {
AdminLinkClaPage link = AdminLinkClaPage.to(driverForLinkUser);
GitHubLoginPage login = new GitHubLoginPage(driverForLinkUser);
link = login.loginForm()
.username(linkUser.getGitHubUsername())
.password(linkUser.getGitHubPassword())
.submit(AdminLinkClaPage.class);
link.assertAt();
takeScreenShot(driverForLinkUser, "cla-link");
link = link.link(linkUser.getGitHubUsername() + "/cla-test", "pivotal", AdminLinkClaPage.class);
link.assertAt();
takeScreenShot(driverForLinkUser, "cla-link-success");
String pullHtmlUrl = createPullRequest(signUser, 1);
GitHubLoginPage signLogin = GitHubLoginPage.to(driverForSignUser);
signLogin.loginForm()
.username(signUser.getGitHubUsername())
.password(signUser.getGitHubPassword())
.submit(PullRequestService.class);
driverForSignUser.get(pullHtmlUrl);
GitHubPullRequestPage pull = new GitHubPullRequestPage(driverForSignUser);
pull.assertCommentPleaseSignFor(signUser.getGitHubUsername());
pull.assertBuildStatusSign();
takeScreenShot(driverForSignUser, "gh-pull-request-please-sign");
SignClaPage sign = pull.details();
sign.assertAt();
takeScreenShot(driverForSignUser, "cla-signclapage-please-sign");
SignIclaPage signIcla = sign.signIcla(SignIclaPage.class);
signIcla.assertAt();
signIcla.form()
.name("Big Bird")
.email(1)
.mailingAddress("123 Seasame St")
.telephone("123.456.7890")
.country("USA")
.confirm();
takeScreenShot(driverForSignUser, "cla-signicla-please-sign");
signIcla = signIcla.form()
.sign(SignIclaPage.class);
pull = signIcla.pullRequest();
pull.assertCommentThankYouFor(signUser.getGitHubUsername());
takeScreenShot(driverForSignUser, "gh-pull-request-thanks");
pullHtmlUrl = createPullRequest(signUser, 2);
driverForSignUser.get(pullHtmlUrl);
pull = new GitHubPullRequestPage(driverForSignUser);
pull.assertBuildStatusSuccess();
takeScreenShot(driverForSignUser, "gh-pull-request-already-signed");
}
int screenShotCount = 0;
private void takeScreenShot(WebDriver driver, String name) throws IOException {
if(!(driver instanceof TakesScreenshot)) {
return;
}
TakesScreenshot shot = (TakesScreenshot) driver;
byte[] screenshotAs = shot.getScreenshotAs(OutputType.BYTES);
String prefix = String.format("%03d", screenShotCount++) + "_";
File file = new File("build/" + prefix + name + ".png");
file.getParentFile().mkdirs();
file.createNewFile();
FileCopyUtils.copy(screenshotAs, file);
}
}
|
package orca.nodeagent2.oscarslib.util;
import java.util.Calendar;
import net.es.oscars.common.soap.gen.OSCARSFaultMessage;
import orca.nodeagent2.oscarslib.driver.Driver;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
/**
* Main program for OSCARS 06 ORCA driver
* @author ibaldin
*
*/
public class DriverMain {
private static final String CANCEL_CMD = "cancel";
private static final String CREATE_CMD = "create";
private static final String LIST_CMD = "list";
private static final String POLL_INTERVAL = "poll";
private static final String KEYSTOREPASS = "keystorepass";
private static final String KEY_ALIAS = "alias";
private static final String KEYSTORE = "keystore";
private static final String TRUSTSTORE = "truststore";
private static final String IDC_URL = "url";
private static final String INT_Z = "intZ";
private static final String INT_A = "intA";
private static final String BWUNITS = "bwunits";
private static final String GRI = "gri";
@SuppressWarnings("static-access")
public static void main(String[] argv) {
// create the command line parser
CommandLineParser parser = new GnuParser();
// create the Options
Options options = new Options();
options.addOption(OptionBuilder.
withArgName(IDC_URL )
.hasArg().isRequired()
.withDescription( "url of OSCARS IDC")
.create(IDC_URL));
options.addOption(OptionBuilder.
withArgName("jks file").
hasArg().isRequired().
withDescription("keystore with user cert").
create(KEYSTORE));
options.addOption(OptionBuilder.
withArgName("jks file").
hasArg().isRequired().
withDescription("truststore with IDC server certs").
create(TRUSTSTORE));
options.addOption(OptionBuilder.
withArgName("key alias").
hasArg().isRequired().
withDescription("alias of the key in keystore to use").
create(KEY_ALIAS));
options.addOption(OptionBuilder.
withArgName("password string").
hasArg().isRequired().
withDescription("password for the key alias and the keystore").
create(KEYSTOREPASS));
options.addOption(OptionBuilder.
withArgName("password string").
hasArg().
withDescription("password for the truststore file (optional - only if different from keystore password)").
create("truststorepass"));
options.addOption(OptionBuilder.
withArgName("interface urn").
hasArg().
withDescription("URN of the interface A of the path").
create(INT_A));
options.addOption(OptionBuilder.
withArgName("interface urn").
hasArg().
withDescription("URN of the interface Z of the path").
create(INT_Z));
options.addOption(OptionBuilder.
withArgName("vlan tag").
hasArg().
withDescription("VLAN tag of the interface A of the path").
create("tagA"));
options.addOption(OptionBuilder.
withArgName("vlan tag").
hasArg().
withDescription("VLAN tag of the interface Z of the path").
create("tagZ"));
options.addOption(OptionBuilder.
withArgName("bandwidth (default Mbps)").
hasArg().
withDescription("requested bandwidth of the path. zero means best-effort.").
create("bw"));
options.addOption(OptionBuilder.
withArgName("bandwidth units=<bps|kbps|mbps|gbps>").
hasArg().
withDescription("requested bandwidth units").
create(BWUNITS));
options.addOption(OptionBuilder.
withArgName("gri").
hasArg().
withDescription("GRI of the reservation of interest").
create("gri"));
options.addOption(OptionBuilder.
withArgName("command=<list|create|cancel>").
hasArg().isRequired().
withDescription("command to issue").
create("command"));
options.addOption(OptionBuilder.
withArgName("duration in seconds").
hasArg().
withDescription("duration of the reservation in seconds").
create("duration"));
options.addOption(OptionBuilder.
withArgName("reservation description").
hasArg().
withDescription("description of the reservation").
create("description"));
options.addOption(OptionBuilder.
withArgName("polling interval for create and cancel").
hasArg().
withDescription("polling interval in seconds").
create(POLL_INTERVAL));
options.addOption("d", false, "provide debugging information");
options.addOption("c", false, "use compact concatenated circuit description on create and cancel: GRI|intA|tagA|intZ|tagZ");
try {
// parse the command line arguments
CommandLine line = parser.parse( options, argv );
String command = line.getOptionValue("command");
boolean debugOn = false;
if (line.hasOption("d"))
debugOn = true;
boolean compact = false;
if (line.hasOption("c"))
compact = true;
if (command.equals(LIST_CMD)) {
// check command line parameters for list - none outside default
Driver d = new Driver(
line.getOptionValue(IDC_URL),
line.getOptionValue(TRUSTSTORE),
line.getOptionValue(KEYSTORE),
line.getOptionValue(KEY_ALIAS),
line.getOptionValue(KEYSTOREPASS), false);
System.out.println(d.printReservations(false));
} else if (command.equals("listactive")) {
// check command line parameters for list - none outside default
Driver d = new Driver(
line.getOptionValue(IDC_URL),
line.getOptionValue(TRUSTSTORE),
line.getOptionValue(KEYSTORE),
line.getOptionValue(KEY_ALIAS),
line.getOptionValue(KEYSTOREPASS), false);
System.out.println(d.printReservations(true));
} else if (command.equals(CREATE_CMD)) {
// check command line parameters for create
if (!line.hasOption(INT_A) ||
!line.hasOption(INT_Z) ||
!line.hasOption("tagA") ||
!line.hasOption("tagZ") ||
!line.hasOption("bw") ||
!line.hasOption("duration") ||
!line.hasOption("description"))
throw new ParseException("intA, intZ, tagA, tagZ, description, duration and bw must be specified");
int duration = Integer.parseInt(line.getOptionValue("duration"));
long bw = Long.parseLong(line.getOptionValue("bw"));
int tagA = Integer.parseInt(line.getOptionValue("tagA"));
int tagZ = Integer.parseInt(line.getOptionValue("tagZ"));
int poll = 10;
if (line.hasOption(POLL_INTERVAL)) {
poll = Integer.parseInt(line.getOptionValue(POLL_INTERVAL));
if (poll < 0)
throw new ParseException("Polling interval must be positive in seconds.");
}
if ((tagA <=0) || (tagA > 4096) || (tagZ <= 0) || (tagZ > 4096))
throw new ParseException("VLAN tags must be in 1-4096 range");
// deal with bandwidth units
if (line.hasOption(BWUNITS)) {
if (line.getOptionValue(BWUNITS).equalsIgnoreCase("mbps"))
;
else if (line.getOptionValue(BWUNITS).equalsIgnoreCase("kbps"))
bw /= 1000;
else if (line.getOptionValue(BWUNITS).equalsIgnoreCase("gbps"))
bw *= 1000;
else if (line.getOptionValue(BWUNITS).equalsIgnoreCase("bps"))
bw /= 1000000;
else
throw new ParseException("Only bps, kbps, mbps and gbps are allowed as units");
}
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
end.add(Calendar.SECOND, duration);
if (debugOn)
System.out.println("Creating reservation from " + line.getOptionValue(INT_A) + "/" + tagA + " to " +
line.getOptionValue(INT_A) + "/" + tagZ + " bw=" + bw + " for " + duration);
Driver d = new Driver(
line.getOptionValue(IDC_URL),
line.getOptionValue(TRUSTSTORE),
line.getOptionValue(KEYSTORE),
line.getOptionValue(KEY_ALIAS),
line.getOptionValue(KEYSTOREPASS), false);
String gri = d.createReservationPoll(line.getOptionValue("description"),
start.getTime(), end.getTime(),
(int)bw,
line.getOptionValue(INT_A), tagA,
line.getOptionValue(INT_Z), tagZ,
poll);
if (compact)
System.out.println(gri + "|" + line.getOptionValue(INT_A) + "|" + tagA + "|" + line.getOptionValue(INT_Z) + "|" + tagZ);
else
System.out.println("SUCCESS: gri=" + gri);
} else if (command.equals(CANCEL_CMD)) {
if (!line.hasOption(GRI))
throw new ParseException("GRI must be specified");
String gri = line.getOptionValue(GRI);
if (line.hasOption("c")) {
// get the gri
String[] splits = gri.split("\\|");
gri = splits[0].trim();
}
int poll = 10;
if (line.hasOption(POLL_INTERVAL)) {
poll = Integer.parseInt(line.getOptionValue(POLL_INTERVAL));
if (poll < 0)
throw new ParseException("Polling interval must be positive in seconds.");
}
Driver d = new Driver(
line.getOptionValue(IDC_URL),
line.getOptionValue(TRUSTSTORE),
line.getOptionValue(KEYSTORE),
line.getOptionValue(KEY_ALIAS),
line.getOptionValue(KEYSTOREPASS), false);
if (debugOn)
System.out.println("Canceling reservation " + gri);
d.cancelReservation(gri, poll);
System.out.println("SUCCESS");
}
}
catch( ParseException exp ) {
System.err.println("ERROR: Incorrect command line: " + exp.getMessage() );
}
catch (OSCARSFaultMessage ofe) {
System.err.println("ERROR: OSCARS Fault: " + ofe.getMessage());
}
catch (Exception e) {
System.err.println("ERROR: Generic exception: " + e.getMessage());
}
}
}
|
package mil.nga.geopackage.test;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.imageio.ImageIO;
import junit.framework.TestCase;
import mil.nga.geopackage.BoundingBox;
import mil.nga.geopackage.GeoPackage;
import mil.nga.geopackage.GeoPackageException;
import mil.nga.geopackage.attributes.AttributesColumn;
import mil.nga.geopackage.attributes.AttributesDao;
import mil.nga.geopackage.attributes.AttributesResultSet;
import mil.nga.geopackage.attributes.AttributesRow;
import mil.nga.geopackage.attributes.AttributesTable;
import mil.nga.geopackage.core.contents.Contents;
import mil.nga.geopackage.core.contents.ContentsDao;
import mil.nga.geopackage.core.contents.ContentsDataType;
import mil.nga.geopackage.core.srs.SpatialReferenceSystem;
import mil.nga.geopackage.core.srs.SpatialReferenceSystemDao;
import mil.nga.geopackage.db.DateConverter;
import mil.nga.geopackage.db.GeoPackageDataType;
import mil.nga.geopackage.extension.CrsWktExtension;
import mil.nga.geopackage.extension.ExtensionsDao;
import mil.nga.geopackage.extension.GeoPackageExtensions;
import mil.nga.geopackage.extension.GeometryExtensions;
import mil.nga.geopackage.extension.MetadataExtension;
import mil.nga.geopackage.extension.NGAExtensions;
import mil.nga.geopackage.extension.RTreeIndexExtension;
import mil.nga.geopackage.extension.SchemaExtension;
import mil.nga.geopackage.extension.WebPExtension;
import mil.nga.geopackage.extension.contents.ContentsIdExtension;
import mil.nga.geopackage.extension.coverage.CoverageData;
import mil.nga.geopackage.extension.coverage.CoverageDataPng;
import mil.nga.geopackage.extension.coverage.CoverageDataTiff;
import mil.nga.geopackage.extension.coverage.GriddedCoverage;
import mil.nga.geopackage.extension.coverage.GriddedCoverageDao;
import mil.nga.geopackage.extension.coverage.GriddedCoverageDataType;
import mil.nga.geopackage.extension.coverage.GriddedCoverageEncodingType;
import mil.nga.geopackage.extension.coverage.GriddedTile;
import mil.nga.geopackage.extension.coverage.GriddedTileDao;
import mil.nga.geopackage.extension.index.FeatureTableIndex;
import mil.nga.geopackage.extension.link.FeatureTileTableLinker;
import mil.nga.geopackage.extension.properties.PropertiesExtension;
import mil.nga.geopackage.extension.properties.PropertyNames;
import mil.nga.geopackage.extension.related.ExtendedRelation;
import mil.nga.geopackage.extension.related.RelatedTablesExtension;
import mil.nga.geopackage.extension.related.UserMappingDao;
import mil.nga.geopackage.extension.related.UserMappingRow;
import mil.nga.geopackage.extension.related.UserMappingTable;
import mil.nga.geopackage.extension.related.dublin.DublinCoreMetadata;
import mil.nga.geopackage.extension.related.dublin.DublinCoreType;
import mil.nga.geopackage.extension.related.media.MediaDao;
import mil.nga.geopackage.extension.related.media.MediaRow;
import mil.nga.geopackage.extension.related.media.MediaTable;
import mil.nga.geopackage.extension.related.simple.SimpleAttributesDao;
import mil.nga.geopackage.extension.related.simple.SimpleAttributesRow;
import mil.nga.geopackage.extension.related.simple.SimpleAttributesTable;
import mil.nga.geopackage.extension.scale.TileScaling;
import mil.nga.geopackage.extension.scale.TileScalingType;
import mil.nga.geopackage.extension.scale.TileTableScaling;
import mil.nga.geopackage.extension.style.FeatureStyleExtension;
import mil.nga.geopackage.extension.style.FeatureTableStyles;
import mil.nga.geopackage.extension.style.IconRow;
import mil.nga.geopackage.extension.style.StyleRow;
import mil.nga.geopackage.features.columns.GeometryColumns;
import mil.nga.geopackage.features.columns.GeometryColumnsDao;
import mil.nga.geopackage.features.user.FeatureColumn;
import mil.nga.geopackage.features.user.FeatureDao;
import mil.nga.geopackage.features.user.FeatureResultSet;
import mil.nga.geopackage.features.user.FeatureRow;
import mil.nga.geopackage.features.user.FeatureTable;
import mil.nga.geopackage.geom.GeoPackageGeometryData;
import mil.nga.geopackage.io.GeoPackageIOUtils;
import mil.nga.geopackage.manager.GeoPackageManager;
import mil.nga.geopackage.metadata.Metadata;
import mil.nga.geopackage.metadata.MetadataDao;
import mil.nga.geopackage.metadata.MetadataScopeType;
import mil.nga.geopackage.metadata.reference.MetadataReference;
import mil.nga.geopackage.metadata.reference.MetadataReferenceDao;
import mil.nga.geopackage.metadata.reference.ReferenceScopeType;
import mil.nga.geopackage.schema.columns.DataColumns;
import mil.nga.geopackage.schema.columns.DataColumnsDao;
import mil.nga.geopackage.schema.constraints.DataColumnConstraintType;
import mil.nga.geopackage.schema.constraints.DataColumnConstraints;
import mil.nga.geopackage.schema.constraints.DataColumnConstraintsDao;
import mil.nga.geopackage.style.Color;
import mil.nga.geopackage.style.ColorConstants;
import mil.nga.geopackage.test.extension.related.RelatedTablesUtils;
import mil.nga.geopackage.tiles.ImageUtils;
import mil.nga.geopackage.tiles.TileBoundingBoxUtils;
import mil.nga.geopackage.tiles.TileGenerator;
import mil.nga.geopackage.tiles.TileGrid;
import mil.nga.geopackage.tiles.features.DefaultFeatureTiles;
import mil.nga.geopackage.tiles.features.FeatureTileGenerator;
import mil.nga.geopackage.tiles.features.FeatureTiles;
import mil.nga.geopackage.tiles.matrix.TileMatrix;
import mil.nga.geopackage.tiles.matrix.TileMatrixDao;
import mil.nga.geopackage.tiles.matrixset.TileMatrixSet;
import mil.nga.geopackage.tiles.matrixset.TileMatrixSetDao;
import mil.nga.geopackage.tiles.user.TileDao;
import mil.nga.geopackage.tiles.user.TileRow;
import mil.nga.geopackage.tiles.user.TileTable;
import mil.nga.geopackage.user.ContentValues;
import mil.nga.geopackage.user.custom.UserCustomColumn;
import mil.nga.sf.CircularString;
import mil.nga.sf.CompoundCurve;
import mil.nga.sf.CurvePolygon;
import mil.nga.sf.Geometry;
import mil.nga.sf.GeometryEnvelope;
import mil.nga.sf.GeometryType;
import mil.nga.sf.LineString;
import mil.nga.sf.MultiLineString;
import mil.nga.sf.MultiPolygon;
import mil.nga.sf.Point;
import mil.nga.sf.Polygon;
import mil.nga.sf.proj.Projection;
import mil.nga.sf.proj.ProjectionConstants;
import mil.nga.sf.proj.ProjectionFactory;
import mil.nga.sf.proj.ProjectionTransform;
import mil.nga.sf.util.GeometryEnvelopeBuilder;
import mil.nga.sf.wkb.GeometryCodes;
import org.junit.Test;
/**
* Creates an example GeoPackage file
*
* @author osbornb
*/
public class GeoPackageExample {
private static final String GEOPACKAGE_FILE = "example.gpkg";
private static final boolean FEATURES = true;
private static final boolean TILES = true;
private static final boolean ATTRIBUTES = true;
private static final boolean SCHEMA = true;
private static final boolean NON_LINEAR_GEOMETRY_TYPES = true;
private static final boolean RTREE_SPATIAL_INDEX = true;
private static final boolean WEBP = true;
private static final boolean CRS_WKT = true;
private static final boolean METADATA = true;
private static final boolean COVERAGE_DATA = true;
private static final boolean RELATED_TABLES_MEDIA = true;
private static final boolean RELATED_TABLES_FEATURES = true;
private static final boolean RELATED_TABLES_SIMPLE_ATTRIBUTES = true;
private static final boolean GEOMETRY_INDEX = true;
private static final boolean FEATURE_TILE_LINK = true;
private static final boolean TILE_SCALING = true;
private static final boolean PROPERTIES = true;
private static final boolean CONTENTS_ID = true;
private static final boolean FEATURE_STYLE = true;
private static final String ID_COLUMN = "id";
private static final String GEOMETRY_COLUMN = "geometry";
private static final String TEXT_COLUMN = "text";
private static final String REAL_COLUMN = "real";
private static final String BOOLEAN_COLUMN = "boolean";
private static final String BLOB_COLUMN = "blob";
private static final String INTEGER_COLUMN = "integer";
private static final String TEXT_LIMITED_COLUMN = "text_limited";
private static final String BLOB_LIMITED_COLUMN = "blob_limited";
private static final String DATE_COLUMN = "date";
private static final String DATETIME_COLUMN = "datetime";
/**
* Main method to create the GeoPackage example file
*
* @param args
* arguments
* @throws SQLException
* upon error
* @throws IOException
* upon error
*/
public static void main(String[] args) throws SQLException, IOException {
create();
}
/**
* Test making the GeoPackage example
*
* @throws SQLException
* upon error
* @throws IOException
* upon error
*/
@Test
public void testExample() throws SQLException, IOException {
create();
File file = new File(GEOPACKAGE_FILE);
GeoPackage geoPackage = GeoPackageManager.open(file);
TestCase.assertNotNull(geoPackage);
geoPackage.close();
TestCase.assertTrue(file.delete());
}
/**
* Test the GeoPackage example extensions
*
* @throws SQLException
* upon error
* @throws IOException
* upon error
*/
@Test
public void testExampleExtensions() throws SQLException, IOException {
create();
File file = new File(GEOPACKAGE_FILE);
GeoPackage geoPackage = GeoPackageManager.open(file);
validateExtensions(geoPackage, true);
validateNGAExtensions(geoPackage, true);
GeoPackageExtensions.deleteExtensions(geoPackage);
validateExtensions(geoPackage, false);
validateNGAExtensions(geoPackage, false);
geoPackage.close();
TestCase.assertTrue(file.delete());
}
/**
* Test the GeoPackage example NGA extensions
*
* @throws SQLException
* upon error
* @throws IOException
* upon error
*/
@Test
public void testExampleNGAExtensions() throws SQLException, IOException {
create();
File file = new File(GEOPACKAGE_FILE);
GeoPackage geoPackage = GeoPackageManager.open(file);
validateExtensions(geoPackage, true);
validateNGAExtensions(geoPackage, true);
NGAExtensions.deleteExtensions(geoPackage);
validateExtensions(geoPackage, true);
validateNGAExtensions(geoPackage, false);
geoPackage.close();
TestCase.assertTrue(file.delete());
}
private void validateExtensions(GeoPackage geoPackage, boolean has)
throws SQLException {
ExtensionsDao extensionsDao = geoPackage.getExtensionsDao();
TestCase.assertEquals(has && RTREE_SPATIAL_INDEX,
new RTreeIndexExtension(geoPackage).has());
TestCase.assertEquals(
has
&& (RELATED_TABLES_FEATURES || RELATED_TABLES_MEDIA || RELATED_TABLES_SIMPLE_ATTRIBUTES),
new RelatedTablesExtension(geoPackage).has());
TestCase.assertEquals(
has && COVERAGE_DATA,
extensionsDao.isTableExists()
&& !extensionsDao.queryByExtension(
CoverageData.EXTENSION_NAME).isEmpty());
TestCase.assertEquals(has && SCHEMA,
new SchemaExtension(geoPackage).has());
TestCase.assertEquals(has && METADATA,
new MetadataExtension(geoPackage).has());
TestCase.assertEquals(
has && NON_LINEAR_GEOMETRY_TYPES,
extensionsDao.isTableExists()
&& !extensionsDao
.queryByExtension(
GeometryExtensions
.getExtensionName(GeometryType.CIRCULARSTRING))
.isEmpty());
TestCase.assertEquals(has && WEBP, extensionsDao.isTableExists()
&& !extensionsDao
.queryByExtension(WebPExtension.EXTENSION_NAME)
.isEmpty());
TestCase.assertEquals(has && CRS_WKT,
new CrsWktExtension(geoPackage).has());
}
private void validateNGAExtensions(GeoPackage geoPackage, boolean has)
throws SQLException {
ExtensionsDao extensionsDao = geoPackage.getExtensionsDao();
TestCase.assertEquals(
has && GEOMETRY_INDEX,
extensionsDao.isTableExists()
&& !extensionsDao.queryByExtension(
FeatureTableIndex.EXTENSION_NAME).isEmpty());
TestCase.assertEquals(has && FEATURE_TILE_LINK,
new FeatureTileTableLinker(geoPackage).has());
TestCase.assertEquals(
has && TILE_SCALING,
extensionsDao.isTableExists()
&& !extensionsDao.queryByExtension(
TileTableScaling.EXTENSION_NAME).isEmpty());
TestCase.assertEquals(has && PROPERTIES, new PropertiesExtension(
geoPackage).has());
TestCase.assertEquals(has && CONTENTS_ID, new ContentsIdExtension(
geoPackage).has());
TestCase.assertEquals(has && FEATURE_STYLE, new FeatureStyleExtension(
geoPackage).has());
}
/**
* Create the GeoPackage example file
*
* @throws SQLException
* upon error
* @throws IOException
* upon error
*/
private static void create() throws SQLException, IOException {
System.out.println("Creating: " + GEOPACKAGE_FILE);
GeoPackage geoPackage = createGeoPackage();
System.out.println("CRS WKT Extension: " + CRS_WKT);
if (CRS_WKT) {
createCrsWktExtension(geoPackage);
}
System.out.println("Features: " + FEATURES);
if (FEATURES) {
createFeatures(geoPackage);
System.out.println("Schema Extension: " + SCHEMA);
if (SCHEMA) {
createSchemaExtension(geoPackage);
}
System.out.println("Geometry Index Extension: " + GEOMETRY_INDEX);
if (GEOMETRY_INDEX) {
createGeometryIndexExtension(geoPackage);
}
System.out.println("Feature Tile Link Extension: "
+ FEATURE_TILE_LINK);
if (FEATURE_TILE_LINK) {
createFeatureTileLinkExtension(geoPackage);
}
System.out.println("Non-Linear Geometry Types Extension: "
+ NON_LINEAR_GEOMETRY_TYPES);
if (NON_LINEAR_GEOMETRY_TYPES) {
createNonLinearGeometryTypesExtension(geoPackage);
}
System.out.println("RTree Spatial Index Extension: "
+ RTREE_SPATIAL_INDEX);
if (RTREE_SPATIAL_INDEX) {
createRTreeSpatialIndexExtension(geoPackage);
}
System.out.println("Related Tables Media Extension: "
+ RELATED_TABLES_MEDIA);
if (RELATED_TABLES_MEDIA) {
createRelatedTablesMediaExtension(geoPackage);
}
System.out.println("Related Tables Features Extension: "
+ RELATED_TABLES_FEATURES);
if (RELATED_TABLES_FEATURES) {
createRelatedTablesFeaturesExtension(geoPackage);
}
System.out.println("Feature Style Extension: " + FEATURE_STYLE);
if (FEATURE_STYLE) {
createFeatureStyleExtension(geoPackage);
}
} else {
System.out.println("Schema Extension: " + FEATURES);
System.out.println("Geometry Index Extension: " + FEATURES);
System.out.println("Feature Tile Link Extension: " + FEATURES);
System.out.println("Non-Linear Geometry Types Extension: "
+ FEATURES);
System.out.println("RTree Spatial Index Extension: " + FEATURES);
System.out.println("Related Tables Media Extension: " + FEATURES);
System.out
.println("Related Tables Features Extension: " + FEATURES);
System.out.println("Feature Style Extension: " + FEATURES);
}
System.out.println("Tiles: " + TILES);
if (TILES) {
createTiles(geoPackage);
System.out.println("WebP Extension: " + WEBP);
if (WEBP) {
createWebPExtension(geoPackage);
}
System.out.println("Tile Scaling Extension: " + TILE_SCALING);
if (TILE_SCALING) {
createTileScalingExtension(geoPackage);
}
} else {
System.out.println("WebP Extension: " + TILES);
System.out.println("Tile Scaling Extension: " + TILES);
}
System.out.println("Attributes: " + ATTRIBUTES);
if (ATTRIBUTES) {
createAttributes(geoPackage);
System.out.println("Related Tables Simple Attributes Extension: "
+ RELATED_TABLES_SIMPLE_ATTRIBUTES);
if (RELATED_TABLES_SIMPLE_ATTRIBUTES) {
createRelatedTablesSimpleAttributesExtension(geoPackage);
}
} else {
System.out.println("Related Tables Simple Attributes Extension: "
+ ATTRIBUTES);
}
System.out.println("Metadata: " + METADATA);
if (METADATA) {
createMetadataExtension(geoPackage);
}
System.out.println("Coverage Data: " + COVERAGE_DATA);
if (COVERAGE_DATA) {
createCoverageDataExtension(geoPackage);
}
System.out.println("Properties: " + PROPERTIES);
if (PROPERTIES) {
createPropertiesExtension(geoPackage);
}
System.out.println("Contents Id: " + CONTENTS_ID);
if (CONTENTS_ID) {
createContentsIdExtension(geoPackage);
}
geoPackage.close();
System.out.println("Created: " + geoPackage.getPath());
}
private static GeoPackage createGeoPackage() {
File file = new File(GEOPACKAGE_FILE);
if (file.exists()) {
file.delete();
}
GeoPackageManager.create(file);
GeoPackage geoPackage = GeoPackageManager.open(file);
return geoPackage;
}
private static void createFeatures(GeoPackage geoPackage)
throws SQLException {
SpatialReferenceSystemDao srsDao = geoPackage
.getSpatialReferenceSystemDao();
SpatialReferenceSystem srs = srsDao.getOrCreateCode(
ProjectionConstants.AUTHORITY_EPSG,
(long) ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM);
geoPackage.createGeometryColumnsTable();
Point point1 = new Point(-104.801918, 39.720014);
String point1Name = "BIT Systems";
createFeatures(geoPackage, srs, "point1", GeometryType.POINT, point1,
point1Name);
Point point2 = new Point(-77.196736, 38.753370);
String point2Name = "NGA";
createFeatures(geoPackage, srs, "point2", GeometryType.POINT, point2,
point2Name);
LineString line1 = new LineString();
String line1Name = "East Lockheed Drive";
line1.addPoint(new Point(-104.800614, 39.720721));
line1.addPoint(new Point(-104.802174, 39.720726));
line1.addPoint(new Point(-104.802584, 39.720660));
line1.addPoint(new Point(-104.803088, 39.720477));
line1.addPoint(new Point(-104.803474, 39.720209));
createFeatures(geoPackage, srs, "line1", GeometryType.LINESTRING,
line1, line1Name);
LineString line2 = new LineString();
String line2Name = "NGA";
line2.addPoint(new Point(-77.196650, 38.756501));
line2.addPoint(new Point(-77.196414, 38.755979));
line2.addPoint(new Point(-77.195518, 38.755208));
line2.addPoint(new Point(-77.195303, 38.755272));
line2.addPoint(new Point(-77.195351, 38.755459));
line2.addPoint(new Point(-77.195863, 38.755697));
line2.addPoint(new Point(-77.196328, 38.756069));
line2.addPoint(new Point(-77.196568, 38.756526));
createFeatures(geoPackage, srs, "line2", GeometryType.LINESTRING,
line2, line2Name);
Polygon polygon1 = new Polygon();
String polygon1Name = "BIT Systems";
LineString ring1 = new LineString();
ring1.addPoint(new Point(-104.802246, 39.720343));
ring1.addPoint(new Point(-104.802246, 39.719753));
ring1.addPoint(new Point(-104.802183, 39.719754));
ring1.addPoint(new Point(-104.802184, 39.719719));
ring1.addPoint(new Point(-104.802138, 39.719694));
ring1.addPoint(new Point(-104.802097, 39.719691));
ring1.addPoint(new Point(-104.802096, 39.719648));
ring1.addPoint(new Point(-104.801646, 39.719648));
ring1.addPoint(new Point(-104.801644, 39.719722));
ring1.addPoint(new Point(-104.801550, 39.719723));
ring1.addPoint(new Point(-104.801549, 39.720207));
ring1.addPoint(new Point(-104.801648, 39.720207));
ring1.addPoint(new Point(-104.801648, 39.720341));
ring1.addPoint(new Point(-104.802246, 39.720343));
polygon1.addRing(ring1);
createFeatures(geoPackage, srs, "polygon1", GeometryType.POLYGON,
polygon1, polygon1Name);
Polygon polygon2 = new Polygon();
String polygon2Name = "NGA Visitor Center";
LineString ring2 = new LineString();
ring2.addPoint(new Point(-77.195299, 38.755159));
ring2.addPoint(new Point(-77.195203, 38.755080));
ring2.addPoint(new Point(-77.195410, 38.754930));
ring2.addPoint(new Point(-77.195350, 38.754884));
ring2.addPoint(new Point(-77.195228, 38.754966));
ring2.addPoint(new Point(-77.195135, 38.754889));
ring2.addPoint(new Point(-77.195048, 38.754956));
ring2.addPoint(new Point(-77.194986, 38.754906));
ring2.addPoint(new Point(-77.194897, 38.754976));
ring2.addPoint(new Point(-77.194953, 38.755025));
ring2.addPoint(new Point(-77.194763, 38.755173));
ring2.addPoint(new Point(-77.194827, 38.755224));
ring2.addPoint(new Point(-77.195012, 38.755082));
ring2.addPoint(new Point(-77.195041, 38.755104));
ring2.addPoint(new Point(-77.195028, 38.755116));
ring2.addPoint(new Point(-77.195090, 38.755167));
ring2.addPoint(new Point(-77.195106, 38.755154));
ring2.addPoint(new Point(-77.195205, 38.755233));
ring2.addPoint(new Point(-77.195299, 38.755159));
polygon2.addRing(ring2);
createFeatures(geoPackage, srs, "polygon2", GeometryType.POLYGON,
polygon2, polygon2Name);
List<Geometry> geometries1 = new ArrayList<>();
List<String> geometries1Names = new ArrayList<>();
geometries1.add(point1);
geometries1Names.add(point1Name);
geometries1.add(line1);
geometries1Names.add(line1Name);
geometries1.add(polygon1);
geometries1Names.add(polygon1Name);
createFeatures(geoPackage, srs, "geometry1", GeometryType.GEOMETRY,
geometries1, geometries1Names);
List<Geometry> geometries2 = new ArrayList<>();
List<String> geometries2Names = new ArrayList<>();
geometries2.add(point2);
geometries2Names.add(point2Name);
geometries2.add(line2);
geometries2Names.add(line2Name);
geometries2.add(polygon2);
geometries2Names.add(polygon2Name);
createFeatures(geoPackage, srs, "geometry2", GeometryType.GEOMETRY,
geometries2, geometries2Names);
}
private static void createFeatures(GeoPackage geoPackage,
SpatialReferenceSystem srs, String tableName, GeometryType type,
Geometry geometry, String name) throws SQLException {
List<Geometry> geometries = new ArrayList<>();
geometries.add(geometry);
List<String> names = new ArrayList<>();
names.add(name);
createFeatures(geoPackage, srs, tableName, type, geometries, names);
}
private static void createFeatures(GeoPackage geoPackage,
SpatialReferenceSystem srs, String tableName, GeometryType type,
List<Geometry> geometries, List<String> names) throws SQLException {
GeometryEnvelope envelope = null;
for (Geometry geometry : geometries) {
if (envelope == null) {
envelope = GeometryEnvelopeBuilder.buildEnvelope(geometry);
} else {
GeometryEnvelopeBuilder.buildEnvelope(geometry, envelope);
}
}
ContentsDao contentsDao = geoPackage.getContentsDao();
Contents contents = new Contents();
contents.setTableName(tableName);
contents.setDataType(ContentsDataType.FEATURES);
contents.setIdentifier(tableName);
contents.setDescription("example: " + tableName);
contents.setMinX(envelope.getMinX());
contents.setMinY(envelope.getMinY());
contents.setMaxX(envelope.getMaxX());
contents.setMaxY(envelope.getMaxY());
contents.setSrs(srs);
List<FeatureColumn> columns = new ArrayList<FeatureColumn>();
int columnNumber = 0;
columns.add(FeatureColumn.createPrimaryKeyColumn(columnNumber++,
ID_COLUMN));
columns.add(FeatureColumn.createGeometryColumn(columnNumber++,
GEOMETRY_COLUMN, type, false, null));
columns.add(FeatureColumn.createColumn(columnNumber++, TEXT_COLUMN,
GeoPackageDataType.TEXT, false, ""));
columns.add(FeatureColumn.createColumn(columnNumber++, REAL_COLUMN,
GeoPackageDataType.REAL, false, null));
columns.add(FeatureColumn.createColumn(columnNumber++, BOOLEAN_COLUMN,
GeoPackageDataType.BOOLEAN, false, null));
columns.add(FeatureColumn.createColumn(columnNumber++, BLOB_COLUMN,
GeoPackageDataType.BLOB, false, null));
columns.add(FeatureColumn.createColumn(columnNumber++, INTEGER_COLUMN,
GeoPackageDataType.INTEGER, false, null));
columns.add(FeatureColumn.createColumn(columnNumber++,
TEXT_LIMITED_COLUMN, GeoPackageDataType.TEXT, (long) UUID
.randomUUID().toString().length(), false, null));
columns.add(FeatureColumn
.createColumn(columnNumber++, BLOB_LIMITED_COLUMN,
GeoPackageDataType.BLOB, (long) UUID.randomUUID()
.toString().getBytes().length, false, null));
columns.add(FeatureColumn.createColumn(columnNumber++, DATE_COLUMN,
GeoPackageDataType.DATE, false, null));
columns.add(FeatureColumn.createColumn(columnNumber++, DATETIME_COLUMN,
GeoPackageDataType.DATETIME, false, null));
FeatureTable table = new FeatureTable(tableName, columns);
geoPackage.createFeatureTable(table);
contentsDao.create(contents);
GeometryColumnsDao geometryColumnsDao = geoPackage
.getGeometryColumnsDao();
GeometryColumns geometryColumns = new GeometryColumns();
geometryColumns.setContents(contents);
geometryColumns.setColumnName(GEOMETRY_COLUMN);
geometryColumns.setGeometryType(type);
geometryColumns.setSrs(srs);
geometryColumns.setZ((byte) 0);
geometryColumns.setM((byte) 0);
geometryColumnsDao.create(geometryColumns);
FeatureDao dao = geoPackage.getFeatureDao(geometryColumns);
for (int i = 0; i < geometries.size(); i++) {
Geometry geometry = geometries.get(i);
String name;
if (names != null) {
name = names.get(i);
} else {
name = UUID.randomUUID().toString();
}
FeatureRow newRow = dao.newRow();
GeoPackageGeometryData geometryData = new GeoPackageGeometryData(
geometryColumns.getSrsId());
geometryData.setGeometry(geometry);
newRow.setGeometry(geometryData);
newRow.setValue(TEXT_COLUMN, name);
newRow.setValue(REAL_COLUMN, Math.random() * 5000.0);
newRow.setValue(BOOLEAN_COLUMN, Math.random() < .5 ? false : true);
newRow.setValue(BLOB_COLUMN, UUID.randomUUID().toString()
.getBytes());
newRow.setValue(INTEGER_COLUMN, (int) (Math.random() * 500));
newRow.setValue(TEXT_LIMITED_COLUMN, UUID.randomUUID().toString());
newRow.setValue(BLOB_LIMITED_COLUMN, UUID.randomUUID().toString()
.getBytes());
newRow.setValue(DATE_COLUMN, new Date());
newRow.setValue(DATETIME_COLUMN, new Date());
dao.create(newRow);
}
}
private static void createTiles(GeoPackage geoPackage) throws IOException,
SQLException {
geoPackage.createTileMatrixSetTable();
geoPackage.createTileMatrixTable();
BoundingBox bitsBoundingBox = new BoundingBox(-11667347.997449303,
4824705.2253603265, -11666125.00499674, 4825928.217812888);
createTiles(geoPackage, "bit_systems", bitsBoundingBox, 15, 17, "png");
BoundingBox ngaBoundingBox = new BoundingBox(-8593967.964158937,
4685284.085768163, -8592744.971706374, 4687730.070673289);
createTiles(geoPackage, "nga", ngaBoundingBox, 15, 16, "png");
}
private static void createTiles(GeoPackage geoPackage, String name,
BoundingBox boundingBox, int minZoomLevel, int maxZoomLevel,
String extension) throws SQLException, IOException {
SpatialReferenceSystemDao srsDao = geoPackage
.getSpatialReferenceSystemDao();
SpatialReferenceSystem srs = srsDao.getOrCreateCode(
ProjectionConstants.AUTHORITY_EPSG,
(long) ProjectionConstants.EPSG_WEB_MERCATOR);
TileGrid totalTileGrid = TileBoundingBoxUtils.getTileGrid(boundingBox,
minZoomLevel);
BoundingBox totalBoundingBox = TileBoundingBoxUtils
.getWebMercatorBoundingBox(totalTileGrid, minZoomLevel);
ContentsDao contentsDao = geoPackage.getContentsDao();
Contents contents = new Contents();
contents.setTableName(name);
contents.setDataType(ContentsDataType.TILES);
contents.setIdentifier(name);
contents.setDescription(name);
contents.setMinX(totalBoundingBox.getMinLongitude());
contents.setMinY(totalBoundingBox.getMinLatitude());
contents.setMaxX(totalBoundingBox.getMaxLongitude());
contents.setMaxY(totalBoundingBox.getMaxLatitude());
contents.setSrs(srs);
TileTable tileTable = TestUtils.buildTileTable(contents.getTableName());
geoPackage.createTileTable(tileTable);
contentsDao.create(contents);
TileMatrixSetDao tileMatrixSetDao = geoPackage.getTileMatrixSetDao();
TileMatrixSet tileMatrixSet = new TileMatrixSet();
tileMatrixSet.setContents(contents);
tileMatrixSet.setSrs(contents.getSrs());
tileMatrixSet.setMinX(contents.getMinX());
tileMatrixSet.setMinY(contents.getMinY());
tileMatrixSet.setMaxX(contents.getMaxX());
tileMatrixSet.setMaxY(contents.getMaxY());
tileMatrixSetDao.create(tileMatrixSet);
TileMatrixDao tileMatrixDao = geoPackage.getTileMatrixDao();
final String tilesPath = "tiles/";
TileGrid tileGrid = totalTileGrid;
for (int zoom = minZoomLevel; zoom <= maxZoomLevel; zoom++) {
final String zoomPath = tilesPath + zoom + "/";
Integer tileWidth = null;
Integer tileHeight = null;
TileDao dao = geoPackage.getTileDao(tileMatrixSet);
for (long x = tileGrid.getMinX(); x <= tileGrid.getMaxX(); x++) {
final String xPath = zoomPath + x + "/";
for (long y = tileGrid.getMinY(); y <= tileGrid.getMaxY(); y++) {
final String yPath = xPath + y + "." + extension;
if (TestUtils.class.getResource("/" + yPath) != null) {
File tileFile = TestUtils.getTestFile(yPath);
byte[] tileBytes = GeoPackageIOUtils
.fileBytes(tileFile);
if (tileWidth == null || tileHeight == null) {
BufferedImage tileImage = ImageIO.read(tileFile);
if (tileImage != null) {
tileHeight = tileImage.getHeight();
tileWidth = tileImage.getWidth();
}
}
TileRow newRow = dao.newRow();
newRow.setZoomLevel(zoom);
newRow.setTileColumn(x - tileGrid.getMinX());
newRow.setTileRow(y - tileGrid.getMinY());
newRow.setTileData(tileBytes);
dao.create(newRow);
}
}
}
if (tileWidth == null) {
tileWidth = 256;
}
if (tileHeight == null) {
tileHeight = 256;
}
long matrixWidth = tileGrid.getMaxX() - tileGrid.getMinX() + 1;
long matrixHeight = tileGrid.getMaxY() - tileGrid.getMinY() + 1;
double pixelXSize = (tileMatrixSet.getMaxX() - tileMatrixSet
.getMinX()) / (matrixWidth * tileWidth);
double pixelYSize = (tileMatrixSet.getMaxY() - tileMatrixSet
.getMinY()) / (matrixHeight * tileHeight);
TileMatrix tileMatrix = new TileMatrix();
tileMatrix.setContents(contents);
tileMatrix.setZoomLevel(zoom);
tileMatrix.setMatrixWidth(matrixWidth);
tileMatrix.setMatrixHeight(matrixHeight);
tileMatrix.setTileWidth(tileWidth);
tileMatrix.setTileHeight(tileHeight);
tileMatrix.setPixelXSize(pixelXSize);
tileMatrix.setPixelYSize(pixelYSize);
tileMatrixDao.create(tileMatrix);
tileGrid = TileBoundingBoxUtils.tileGridZoomIncrease(tileGrid, 1);
}
}
private static void createAttributes(GeoPackage geoPackage) {
List<AttributesColumn> columns = new ArrayList<AttributesColumn>();
int columnNumber = 1;
columns.add(AttributesColumn.createColumn(columnNumber++, TEXT_COLUMN,
GeoPackageDataType.TEXT, false, ""));
columns.add(AttributesColumn.createColumn(columnNumber++, REAL_COLUMN,
GeoPackageDataType.REAL, false, null));
columns.add(AttributesColumn.createColumn(columnNumber++,
BOOLEAN_COLUMN, GeoPackageDataType.BOOLEAN, false, null));
columns.add(AttributesColumn.createColumn(columnNumber++, BLOB_COLUMN,
GeoPackageDataType.BLOB, false, null));
columns.add(AttributesColumn.createColumn(columnNumber++,
INTEGER_COLUMN, GeoPackageDataType.INTEGER, false, null));
columns.add(AttributesColumn.createColumn(columnNumber++,
TEXT_LIMITED_COLUMN, GeoPackageDataType.TEXT, (long) UUID
.randomUUID().toString().length(), false, null));
columns.add(AttributesColumn
.createColumn(columnNumber++, BLOB_LIMITED_COLUMN,
GeoPackageDataType.BLOB, (long) UUID.randomUUID()
.toString().getBytes().length, false, null));
columns.add(AttributesColumn.createColumn(columnNumber++, DATE_COLUMN,
GeoPackageDataType.DATE, false, null));
columns.add(AttributesColumn.createColumn(columnNumber++,
DATETIME_COLUMN, GeoPackageDataType.DATETIME, false, null));
AttributesTable attributesTable = geoPackage
.createAttributesTableWithId("attributes", columns);
AttributesDao attributesDao = geoPackage
.getAttributesDao(attributesTable.getTableName());
for (int i = 0; i < 10; i++) {
AttributesRow newRow = attributesDao.newRow();
newRow.setValue(TEXT_COLUMN, UUID.randomUUID().toString());
newRow.setValue(REAL_COLUMN, Math.random() * 5000.0);
newRow.setValue(BOOLEAN_COLUMN, Math.random() < .5 ? false : true);
newRow.setValue(BLOB_COLUMN, UUID.randomUUID().toString()
.getBytes());
newRow.setValue(INTEGER_COLUMN, (int) (Math.random() * 500));
newRow.setValue(TEXT_LIMITED_COLUMN, UUID.randomUUID().toString());
newRow.setValue(BLOB_LIMITED_COLUMN, UUID.randomUUID().toString()
.getBytes());
newRow.setValue(DATE_COLUMN, new Date());
newRow.setValue(DATETIME_COLUMN, new Date());
attributesDao.create(newRow);
}
}
private static void createGeometryIndexExtension(GeoPackage geoPackage) {
List<String> featureTables = geoPackage.getFeatureTables();
for (String featureTable : featureTables) {
FeatureDao featureDao = geoPackage.getFeatureDao(featureTable);
FeatureTableIndex featureTableIndex = new FeatureTableIndex(
geoPackage, featureDao);
featureTableIndex.index();
}
}
private static void createFeatureTileLinkExtension(GeoPackage geoPackage)
throws SQLException, IOException {
List<String> featureTables = geoPackage.getFeatureTables();
for (String featureTable : featureTables) {
FeatureDao featureDao = geoPackage.getFeatureDao(featureTable);
FeatureTiles featureTiles = new DefaultFeatureTiles(featureDao);
FeatureTableIndex featureIndex = new FeatureTableIndex(geoPackage,
featureDao);
featureTiles.setFeatureIndex(featureIndex);
BoundingBox boundingBox = featureDao.getBoundingBox();
Projection projection = featureDao.getProjection();
Projection requestProjection = ProjectionFactory
.getProjection(ProjectionConstants.EPSG_WEB_MERCATOR);
ProjectionTransform transform = projection
.getTransformation(requestProjection);
BoundingBox requestBoundingBox = boundingBox.transform(transform);
int zoomLevel = TileBoundingBoxUtils
.getZoomLevel(requestBoundingBox);
zoomLevel = Math.min(zoomLevel, 19);
int minZoom = zoomLevel - 2;
int maxZoom = zoomLevel + 2;
TileGenerator tileGenerator = new FeatureTileGenerator(geoPackage,
featureTable + "_tiles", featureTiles, minZoom, maxZoom,
requestBoundingBox, requestProjection);
tileGenerator.generateTiles();
}
}
private static int dataColumnConstraintIndex = 0;
private static void createSchemaExtension(GeoPackage geoPackage)
throws SQLException {
geoPackage.createDataColumnConstraintsTable();
DataColumnConstraintsDao dao = geoPackage.getDataColumnConstraintsDao();
DataColumnConstraints sampleRange = new DataColumnConstraints();
sampleRange.setConstraintName("sampleRange");
sampleRange.setConstraintType(DataColumnConstraintType.RANGE);
sampleRange.setMin(BigDecimal.ONE);
sampleRange.setMinIsInclusive(true);
sampleRange.setMax(BigDecimal.TEN);
sampleRange.setMaxIsInclusive(true);
sampleRange.setDescription("sampleRange description");
dao.create(sampleRange);
DataColumnConstraints sampleEnum1 = new DataColumnConstraints();
sampleEnum1.setConstraintName("sampleEnum");
sampleEnum1.setConstraintType(DataColumnConstraintType.ENUM);
sampleEnum1.setValue("1");
sampleEnum1.setDescription("sampleEnum description");
dao.create(sampleEnum1);
DataColumnConstraints sampleEnum3 = new DataColumnConstraints();
sampleEnum3.setConstraintName(sampleEnum1.getConstraintName());
sampleEnum3.setConstraintType(DataColumnConstraintType.ENUM);
sampleEnum3.setValue("3");
sampleEnum3.setDescription("sampleEnum description");
dao.create(sampleEnum3);
DataColumnConstraints sampleEnum5 = new DataColumnConstraints();
sampleEnum5.setConstraintName(sampleEnum1.getConstraintName());
sampleEnum5.setConstraintType(DataColumnConstraintType.ENUM);
sampleEnum5.setValue("5");
sampleEnum5.setDescription("sampleEnum description");
dao.create(sampleEnum5);
DataColumnConstraints sampleEnum7 = new DataColumnConstraints();
sampleEnum7.setConstraintName(sampleEnum1.getConstraintName());
sampleEnum7.setConstraintType(DataColumnConstraintType.ENUM);
sampleEnum7.setValue("7");
sampleEnum7.setDescription("sampleEnum description");
dao.create(sampleEnum7);
DataColumnConstraints sampleEnum9 = new DataColumnConstraints();
sampleEnum9.setConstraintName(sampleEnum1.getConstraintName());
sampleEnum9.setConstraintType(DataColumnConstraintType.ENUM);
sampleEnum9.setValue("9");
sampleEnum9.setDescription("sampleEnum description");
dao.create(sampleEnum9);
DataColumnConstraints sampleGlob = new DataColumnConstraints();
sampleGlob.setConstraintName("sampleGlob");
sampleGlob.setConstraintType(DataColumnConstraintType.GLOB);
sampleGlob.setValue("[1-2][0-9][0-9][0-9]");
sampleGlob.setDescription("sampleGlob description");
dao.create(sampleGlob);
geoPackage.createDataColumnsTable();
DataColumnsDao dataColumnsDao = geoPackage.getDataColumnsDao();
List<String> featureTables = geoPackage.getFeatureTables();
for (String featureTable : featureTables) {
FeatureDao featureDao = geoPackage.getFeatureDao(featureTable);
FeatureTable table = featureDao.getTable();
for (FeatureColumn column : table.getColumns()) {
if (!column.isPrimaryKey()
&& column.getDataType() == GeoPackageDataType.INTEGER) {
DataColumns dataColumns = new DataColumns();
dataColumns.setContents(featureDao.getGeometryColumns()
.getContents());
dataColumns.setColumnName(column.getName());
dataColumns.setName(featureTable);
dataColumns.setTitle("TEST_TITLE");
dataColumns.setDescription("TEST_DESCRIPTION");
dataColumns.setMimeType("TEST_MIME_TYPE");
DataColumnConstraintType constraintType = DataColumnConstraintType
.values()[dataColumnConstraintIndex];
dataColumnConstraintIndex++;
if (dataColumnConstraintIndex >= DataColumnConstraintType
.values().length) {
dataColumnConstraintIndex = 0;
}
int value = 0;
String constraintName = null;
switch (constraintType) {
case RANGE:
constraintName = sampleRange.getConstraintName();
value = 1 + (int) (Math.random() * 10);
break;
case ENUM:
constraintName = sampleEnum1.getConstraintName();
value = 1 + ((int) (Math.random() * 5) * 2);
break;
case GLOB:
constraintName = sampleGlob.getConstraintName();
value = 1000 + (int) (Math.random() * 2000);
break;
default:
throw new GeoPackageException(
"Unexpected Constraint Type: " + constraintType);
}
dataColumns.setConstraintName(constraintName);
ContentValues values = new ContentValues();
values.put(column.getName(), value);
featureDao.update(values, null, null);
dataColumnsDao.create(dataColumns);
break;
}
}
}
}
private static void createNonLinearGeometryTypesExtension(
GeoPackage geoPackage) throws SQLException {
SpatialReferenceSystemDao srsDao = geoPackage
.getSpatialReferenceSystemDao();
SpatialReferenceSystem srs = srsDao.getOrCreateCode(
ProjectionConstants.AUTHORITY_EPSG,
(long) ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM);
GeometryExtensions extensions = new GeometryExtensions(geoPackage);
String tableName = "non_linear_geometries";
List<Geometry> geometries = new ArrayList<>();
List<String> geometryNames = new ArrayList<>();
CircularString circularString = new CircularString();
circularString.addPoint(new Point(-122.358, 47.653));
circularString.addPoint(new Point(-122.348, 47.649));
circularString.addPoint(new Point(-122.348, 47.658));
circularString.addPoint(new Point(-122.358, 47.658));
circularString.addPoint(new Point(-122.358, 47.653));
for (int i = GeometryCodes.getCode(GeometryType.CIRCULARSTRING); i <= GeometryCodes
.getCode(GeometryType.SURFACE); i++) {
GeometryType geometryType = GeometryCodes.getGeometryType(i);
extensions.getOrCreate(tableName, GEOMETRY_COLUMN, geometryType);
Geometry geometry = null;
String name = geometryType.getName().toLowerCase();
switch (geometryType) {
case CIRCULARSTRING:
geometry = circularString;
break;
case COMPOUNDCURVE:
CompoundCurve compoundCurve = new CompoundCurve();
compoundCurve.addLineString(circularString);
geometry = compoundCurve;
break;
case CURVEPOLYGON:
CurvePolygon<CircularString> curvePolygon = new CurvePolygon<>();
curvePolygon.addRing(circularString);
geometry = curvePolygon;
break;
case MULTICURVE:
MultiLineString multiCurve = new MultiLineString();
multiCurve.addLineString(circularString);
geometry = multiCurve;
break;
case MULTISURFACE:
MultiPolygon multiSurface = new MultiPolygon();
Polygon polygon = new Polygon();
polygon.addRing(circularString);
multiSurface.addPolygon(polygon);
geometry = multiSurface;
break;
case CURVE:
CompoundCurve curve = new CompoundCurve();
curve.addLineString(circularString);
geometry = curve;
break;
case SURFACE:
CurvePolygon<CircularString> surface = new CurvePolygon<>();
surface.addRing(circularString);
geometry = surface;
break;
default:
throw new GeoPackageException("Unexpected Geometry Type: "
+ geometryType);
}
geometries.add(geometry);
geometryNames.add(name);
}
createFeatures(geoPackage, srs, tableName, GeometryType.GEOMETRY,
geometries, geometryNames);
}
private static void createWebPExtension(GeoPackage geoPackage)
throws SQLException, IOException {
WebPExtension webpExtension = new WebPExtension(geoPackage);
String tableName = "webp_tiles";
webpExtension.getOrCreate(tableName);
geoPackage.createTileMatrixSetTable();
geoPackage.createTileMatrixTable();
BoundingBox bitsBoundingBox = new BoundingBox(-11667347.997449303,
4824705.2253603265, -11666125.00499674, 4825928.217812888);
createTiles(geoPackage, tableName, bitsBoundingBox, 15, 15, "webp");
}
private static void createCrsWktExtension(GeoPackage geoPackage)
throws SQLException {
CrsWktExtension wktExtension = new CrsWktExtension(geoPackage);
wktExtension.getOrCreate();
SpatialReferenceSystemDao srsDao = geoPackage
.getSpatialReferenceSystemDao();
SpatialReferenceSystem srs = srsDao.queryForOrganizationCoordsysId(
ProjectionConstants.AUTHORITY_EPSG,
ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM);
SpatialReferenceSystem testSrs = new SpatialReferenceSystem();
testSrs.setSrsName("test");
testSrs.setSrsId(12345);
testSrs.setOrganization("test_org");
testSrs.setOrganizationCoordsysId(testSrs.getSrsId());
testSrs.setDefinition(srs.getDefinition());
testSrs.setDescription(srs.getDescription());
testSrs.setDefinition_12_063(srs.getDefinition_12_063());
srsDao.create(testSrs);
SpatialReferenceSystem testSrs2 = new SpatialReferenceSystem();
testSrs2.setSrsName("test2");
testSrs2.setSrsId(54321);
testSrs2.setOrganization("test_org");
testSrs2.setOrganizationCoordsysId(testSrs2.getSrsId());
testSrs2.setDefinition(srs.getDefinition());
testSrs2.setDescription(srs.getDescription());
srsDao.create(testSrs2);
}
private static void createMetadataExtension(GeoPackage geoPackage)
throws SQLException {
geoPackage.createMetadataTable();
MetadataDao metadataDao = geoPackage.getMetadataDao();
Metadata metadata1 = new Metadata();
metadata1.setId(1);
metadata1.setMetadataScope(MetadataScopeType.DATASET);
metadata1.setStandardUri("TEST_URI_1");
metadata1.setMimeType("text/xml");
metadata1.setMetadata("TEST METADATA 1");
metadataDao.create(metadata1);
Metadata metadata2 = new Metadata();
metadata2.setId(2);
metadata2.setMetadataScope(MetadataScopeType.FEATURE_TYPE);
metadata2.setStandardUri("TEST_URI_2");
metadata2.setMimeType("text/xml");
metadata2.setMetadata("TEST METADATA 2");
metadataDao.create(metadata2);
Metadata metadata3 = new Metadata();
metadata3.setId(3);
metadata3.setMetadataScope(MetadataScopeType.TILE);
metadata3.setStandardUri("TEST_URI_3");
metadata3.setMimeType("text/xml");
metadata3.setMetadata("TEST METADATA 3");
metadataDao.create(metadata3);
geoPackage.createMetadataReferenceTable();
MetadataReferenceDao metadataReferenceDao = geoPackage
.getMetadataReferenceDao();
MetadataReference reference1 = new MetadataReference();
reference1.setReferenceScope(ReferenceScopeType.GEOPACKAGE);
reference1.setMetadata(metadata1);
metadataReferenceDao.create(reference1);
List<String> tileTables = geoPackage.getTileTables();
if (!tileTables.isEmpty()) {
String table = tileTables.get(0);
MetadataReference reference2 = new MetadataReference();
reference2.setReferenceScope(ReferenceScopeType.TABLE);
reference2.setTableName(table);
reference2.setMetadata(metadata2);
reference2.setParentMetadata(metadata1);
metadataReferenceDao.create(reference2);
}
List<String> featureTables = geoPackage.getFeatureTables();
if (!featureTables.isEmpty()) {
String table = featureTables.get(0);
MetadataReference reference3 = new MetadataReference();
reference3.setReferenceScope(ReferenceScopeType.ROW_COL);
reference3.setTableName(table);
reference3.setColumnName(GEOMETRY_COLUMN);
reference3.setRowIdValue(1L);
reference3.setMetadata(metadata3);
metadataReferenceDao.create(reference3);
}
}
private static void createCoverageDataExtension(GeoPackage geoPackage)
throws SQLException {
createCoverageDataPngExtension(geoPackage);
createCoverageDataTiffExtension(geoPackage);
}
private static void createCoverageDataPngExtension(GeoPackage geoPackage)
throws SQLException {
BoundingBox bbox = new BoundingBox(-11667347.997449303,
4824705.2253603265, -11666125.00499674, 4825928.217812888);
int contentsEpsg = ProjectionConstants.EPSG_WEB_MERCATOR;
int tileMatrixSetEpsg = ProjectionConstants.EPSG_WEB_MERCATOR;
SpatialReferenceSystemDao srsDao = geoPackage
.getSpatialReferenceSystemDao();
srsDao.getOrCreateFromEpsg(ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM_GEOGRAPHICAL_3D);
SpatialReferenceSystem contentsSrs = srsDao
.getOrCreateFromEpsg(contentsEpsg);
SpatialReferenceSystem tileMatrixSetSrs = srsDao
.getOrCreateFromEpsg(tileMatrixSetEpsg);
ProjectionTransform transform = tileMatrixSetSrs.getProjection()
.getTransformation(contentsSrs.getProjection());
BoundingBox contentsBoundingBox = bbox;
if (!transform.isSameProjection()) {
contentsBoundingBox = bbox.transform(transform);
}
CoverageDataPng coverageData = CoverageDataPng
.createTileTableWithMetadata(geoPackage, "coverage_png",
contentsBoundingBox, contentsSrs.getId(), bbox,
tileMatrixSetSrs.getId());
TileDao tileDao = coverageData.getTileDao();
TileMatrixSet tileMatrixSet = coverageData.getTileMatrixSet();
GriddedCoverageDao griddedCoverageDao = coverageData
.getGriddedCoverageDao();
GriddedCoverage griddedCoverage = new GriddedCoverage();
griddedCoverage.setTileMatrixSet(tileMatrixSet);
griddedCoverage.setDataType(GriddedCoverageDataType.INTEGER);
griddedCoverage.setDataNull(new Double(Short.MAX_VALUE
- Short.MIN_VALUE));
griddedCoverage
.setGridCellEncodingType(GriddedCoverageEncodingType.CENTER);
griddedCoverageDao.create(griddedCoverage);
GriddedTileDao griddedTileDao = coverageData.getGriddedTileDao();
int width = 1;
int height = 1;
int tileWidth = 3;
int tileHeight = 3;
short[][] tilePixels = new short[tileHeight][tileWidth];
tilePixels[0][0] = (short) 1661.95;
tilePixels[0][1] = (short) 1665.40;
tilePixels[0][2] = (short) 1668.19;
tilePixels[1][0] = (short) 1657.18;
tilePixels[1][1] = (short) 1663.39;
tilePixels[1][2] = (short) 1669.65;
tilePixels[2][0] = (short) 1654.78;
tilePixels[2][1] = (short) 1660.31;
tilePixels[2][2] = (short) 1666.44;
byte[] imageBytes = coverageData.drawTileData(tilePixels);
TileMatrixDao tileMatrixDao = geoPackage.getTileMatrixDao();
TileMatrix tileMatrix = new TileMatrix();
tileMatrix.setContents(tileMatrixSet.getContents());
tileMatrix.setMatrixHeight(height);
tileMatrix.setMatrixWidth(width);
tileMatrix.setTileHeight(tileHeight);
tileMatrix.setTileWidth(tileWidth);
tileMatrix.setPixelXSize((bbox.getMaxLongitude() - bbox
.getMinLongitude()) / width / tileWidth);
tileMatrix
.setPixelYSize((bbox.getMaxLatitude() - bbox.getMinLatitude())
/ height / tileHeight);
tileMatrix.setZoomLevel(15);
tileMatrixDao.create(tileMatrix);
TileRow tileRow = tileDao.newRow();
tileRow.setTileColumn(0);
tileRow.setTileRow(0);
tileRow.setZoomLevel(tileMatrix.getZoomLevel());
tileRow.setTileData(imageBytes);
long tileId = tileDao.create(tileRow);
GriddedTile griddedTile = new GriddedTile();
griddedTile.setContents(tileMatrixSet.getContents());
griddedTile.setTableId(tileId);
griddedTileDao.create(griddedTile);
}
private static void createCoverageDataTiffExtension(GeoPackage geoPackage)
throws SQLException {
BoundingBox bbox = new BoundingBox(-8593967.964158937,
4685284.085768163, -8592744.971706374, 4687730.070673289);
int contentsEpsg = ProjectionConstants.EPSG_WEB_MERCATOR;
int tileMatrixSetEpsg = ProjectionConstants.EPSG_WEB_MERCATOR;
SpatialReferenceSystemDao srsDao = geoPackage
.getSpatialReferenceSystemDao();
srsDao.getOrCreateFromEpsg(ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM_GEOGRAPHICAL_3D);
SpatialReferenceSystem contentsSrs = srsDao
.getOrCreateFromEpsg(contentsEpsg);
SpatialReferenceSystem tileMatrixSetSrs = srsDao
.getOrCreateFromEpsg(tileMatrixSetEpsg);
ProjectionTransform transform = tileMatrixSetSrs.getProjection()
.getTransformation(contentsSrs.getProjection());
BoundingBox contentsBoundingBox = bbox;
if (!transform.isSameProjection()) {
contentsBoundingBox = bbox.transform(transform);
}
CoverageDataTiff coverageData = CoverageDataTiff
.createTileTableWithMetadata(geoPackage, "coverage_tiff",
contentsBoundingBox, contentsSrs.getId(), bbox,
tileMatrixSetSrs.getId());
TileDao tileDao = coverageData.getTileDao();
TileMatrixSet tileMatrixSet = coverageData.getTileMatrixSet();
GriddedCoverageDao griddedCoverageDao = coverageData
.getGriddedCoverageDao();
GriddedCoverage griddedCoverage = new GriddedCoverage();
griddedCoverage.setTileMatrixSet(tileMatrixSet);
griddedCoverage.setDataType(GriddedCoverageDataType.FLOAT);
griddedCoverage.setDataNull((double) Float.MAX_VALUE);
griddedCoverage
.setGridCellEncodingType(GriddedCoverageEncodingType.CENTER);
griddedCoverageDao.create(griddedCoverage);
GriddedTileDao griddedTileDao = coverageData.getGriddedTileDao();
int width = 1;
int height = 1;
int tileWidth = 4;
int tileHeight = 4;
float[][] tilePixels = new float[tileHeight][tileWidth];
tilePixels[0][0] = 71.78f;
tilePixels[0][1] = 74.31f;
tilePixels[0][2] = 70.19f;
tilePixels[0][3] = 68.07f;
tilePixels[1][0] = 61.01f;
tilePixels[1][1] = 69.66f;
tilePixels[1][2] = 68.65f;
tilePixels[1][3] = 72.02f;
tilePixels[2][0] = 41.58f;
tilePixels[2][1] = 69.46f;
tilePixels[2][2] = 67.56f;
tilePixels[2][3] = 70.42f;
tilePixels[3][0] = 54.03f;
tilePixels[3][1] = 71.32f;
tilePixels[3][2] = 57.61f;
tilePixels[3][3] = 54.96f;
byte[] imageBytes = coverageData.drawTileData(tilePixels);
TileMatrixDao tileMatrixDao = geoPackage.getTileMatrixDao();
TileMatrix tileMatrix = new TileMatrix();
tileMatrix.setContents(tileMatrixSet.getContents());
tileMatrix.setMatrixHeight(height);
tileMatrix.setMatrixWidth(width);
tileMatrix.setTileHeight(tileHeight);
tileMatrix.setTileWidth(tileWidth);
tileMatrix.setPixelXSize((bbox.getMaxLongitude() - bbox
.getMinLongitude()) / width / tileWidth);
tileMatrix
.setPixelYSize((bbox.getMaxLatitude() - bbox.getMinLatitude())
/ height / tileHeight);
tileMatrix.setZoomLevel(15);
tileMatrixDao.create(tileMatrix);
TileRow tileRow = tileDao.newRow();
tileRow.setTileColumn(0);
tileRow.setTileRow(0);
tileRow.setZoomLevel(tileMatrix.getZoomLevel());
tileRow.setTileData(imageBytes);
long tileId = tileDao.create(tileRow);
GriddedTile griddedTile = new GriddedTile();
griddedTile.setContents(tileMatrixSet.getContents());
griddedTile.setTableId(tileId);
griddedTileDao.create(griddedTile);
}
private static void createRTreeSpatialIndexExtension(GeoPackage geoPackage) {
RTreeIndexExtension extension = new RTreeIndexExtension(geoPackage);
List<String> featureTables = geoPackage.getFeatureTables();
for (String tableName : featureTables) {
FeatureDao featureDao = geoPackage.getFeatureDao(tableName);
FeatureTable featureTable = featureDao.getTable();
extension.create(featureTable);
}
}
private static void createRelatedTablesMediaExtension(GeoPackage geoPackage) {
RelatedTablesExtension relatedTables = new RelatedTablesExtension(
geoPackage);
List<UserCustomColumn> additionalMediaColumns = RelatedTablesUtils
.createAdditionalUserColumns(MediaTable.numRequiredColumns());
MediaTable mediaTable = MediaTable.create("media",
additionalMediaColumns);
List<UserCustomColumn> additionalMappingColumns = RelatedTablesUtils
.createAdditionalUserColumns(UserMappingTable
.numRequiredColumns());
String tableName1 = "geometry1";
UserMappingTable userMappingTable1 = UserMappingTable.create(tableName1
+ "_" + mediaTable.getTableName(), additionalMappingColumns);
ExtendedRelation relation1 = relatedTables.addMediaRelationship(
tableName1, mediaTable, userMappingTable1);
insertRelatedTablesMediaExtensionRows(geoPackage, relation1,
"BIT Systems%", "BIT Systems", "BITSystems_Logo.png",
"image/png", "BIT Systems Logo", "http:
String tableName2 = "geometry2";
UserMappingTable userMappingTable2 = UserMappingTable.create(tableName2
+ "_" + mediaTable.getTableName(), additionalMappingColumns);
ExtendedRelation relation2 = relatedTables.addMediaRelationship(
tableName2, mediaTable, userMappingTable2);
insertRelatedTablesMediaExtensionRows(geoPackage, relation2, "NGA%",
"NGA", "NGA_Logo.png", "image/png", "NGA Logo",
"http:
insertRelatedTablesMediaExtensionRows(geoPackage, relation2, "NGA",
"NGA", "NGA.jpg", "image/jpeg", "Aerial View of NGA East",
"http:
}
private static void insertRelatedTablesMediaExtensionRows(
GeoPackage geoPackage, ExtendedRelation relation, String query,
String name, String file, String contentType, String description,
String source) {
RelatedTablesExtension relatedTables = new RelatedTablesExtension(
geoPackage);
FeatureDao featureDao = geoPackage.getFeatureDao(relation
.getBaseTableName());
MediaDao mediaDao = relatedTables.getMediaDao(relation);
UserMappingDao userMappingDao = relatedTables.getMappingDao(relation);
MediaRow mediaRow = mediaDao.newRow();
mediaRow.setData(TestUtils.getTestFileBytes(file));
mediaRow.setContentType(contentType);
RelatedTablesUtils.populateUserRow(mediaDao.getTable(), mediaRow,
MediaTable.requiredColumns());
DublinCoreMetadata.setValue(mediaRow, DublinCoreType.TITLE, name);
DublinCoreMetadata.setValue(mediaRow, DublinCoreType.DESCRIPTION,
description);
DublinCoreMetadata.setValue(mediaRow, DublinCoreType.SOURCE, source);
long mediaRowId = mediaDao.create(mediaRow);
FeatureResultSet featureResultSet = featureDao.queryForLike(
TEXT_COLUMN, query);
while (featureResultSet.moveToNext()) {
FeatureRow featureRow = featureResultSet.getRow();
UserMappingRow userMappingRow = userMappingDao.newRow();
userMappingRow.setBaseId(featureRow.getId());
userMappingRow.setRelatedId(mediaRowId);
RelatedTablesUtils.populateUserRow(userMappingDao.getTable(),
userMappingRow, UserMappingTable.requiredColumns());
String featureName = featureRow.getValue(TEXT_COLUMN).toString();
DublinCoreMetadata.setValue(userMappingRow, DublinCoreType.TITLE,
featureName + " - " + name);
DublinCoreMetadata.setValue(userMappingRow,
DublinCoreType.DESCRIPTION, featureName + " - "
+ description);
DublinCoreMetadata.setValue(userMappingRow, DublinCoreType.SOURCE,
source);
userMappingDao.create(userMappingRow);
}
featureResultSet.close();
}
private static void createRelatedTablesFeaturesExtension(
GeoPackage geoPackage) {
createRelatedTablesFeaturesExtension(geoPackage, "point1", "polygon1");
createRelatedTablesFeaturesExtension(geoPackage, "point2", "line2");
}
private static void createRelatedTablesFeaturesExtension(
GeoPackage geoPackage, String tableName1, String tableName2) {
RelatedTablesExtension relatedTables = new RelatedTablesExtension(
geoPackage);
List<UserCustomColumn> additionalMappingColumns = RelatedTablesUtils
.createAdditionalUserColumns(UserMappingTable
.numRequiredColumns());
UserMappingTable userMappingTable = UserMappingTable.create(tableName1
+ "_" + tableName2, additionalMappingColumns);
ExtendedRelation relation = relatedTables.addFeaturesRelationship(
tableName1, tableName2, userMappingTable);
insertRelatedTablesFeaturesExtensionRows(geoPackage, relation);
}
private static void insertRelatedTablesFeaturesExtensionRows(
GeoPackage geoPackage, ExtendedRelation relation) {
RelatedTablesExtension relatedTables = new RelatedTablesExtension(
geoPackage);
UserMappingDao userMappingDao = relatedTables.getMappingDao(relation);
FeatureDao featureDao1 = geoPackage.getFeatureDao(relation
.getBaseTableName());
FeatureDao featureDao2 = geoPackage.getFeatureDao(relation
.getRelatedTableName());
FeatureResultSet featureResultSet1 = featureDao1.queryForAll();
while (featureResultSet1.moveToNext()) {
FeatureRow featureRow1 = featureResultSet1.getRow();
String featureName = featureRow1.getValue(TEXT_COLUMN).toString();
FeatureResultSet featureResultSet2 = featureDao2.queryForEq(
TEXT_COLUMN, featureName);
while (featureResultSet2.moveToNext()) {
FeatureRow featureRow2 = featureResultSet2.getRow();
UserMappingRow userMappingRow = userMappingDao.newRow();
userMappingRow.setBaseId(featureRow1.getId());
userMappingRow.setRelatedId(featureRow2.getId());
RelatedTablesUtils.populateUserRow(userMappingDao.getTable(),
userMappingRow, UserMappingTable.requiredColumns());
DublinCoreMetadata.setValue(userMappingRow,
DublinCoreType.TITLE, featureName);
DublinCoreMetadata.setValue(userMappingRow,
DublinCoreType.DESCRIPTION, featureName);
DublinCoreMetadata.setValue(userMappingRow,
DublinCoreType.SOURCE, featureName);
userMappingDao.create(userMappingRow);
}
featureResultSet2.close();
}
featureResultSet1.close();
}
private static void createRelatedTablesSimpleAttributesExtension(
GeoPackage geoPackage) {
RelatedTablesExtension relatedTables = new RelatedTablesExtension(
geoPackage);
List<UserCustomColumn> simpleUserColumns = RelatedTablesUtils
.createSimpleUserColumns(SimpleAttributesTable
.numRequiredColumns());
SimpleAttributesTable simpleTable = SimpleAttributesTable.create(
"simple_attributes", simpleUserColumns);
String tableName = "attributes";
List<UserCustomColumn> additionalMappingColumns = RelatedTablesUtils
.createAdditionalUserColumns(UserMappingTable
.numRequiredColumns());
UserMappingTable userMappingTable = UserMappingTable.create(tableName
+ "_" + simpleTable.getTableName(), additionalMappingColumns);
ExtendedRelation relation = relatedTables
.addSimpleAttributesRelationship(tableName, simpleTable,
userMappingTable);
SimpleAttributesDao simpleAttributesDao = relatedTables
.getSimpleAttributesDao(simpleTable);
List<Long> simpleAttributesIds = new ArrayList<>();
for (int i = 1; i <= 3; i++) {
SimpleAttributesRow simpleAttributesRow = simpleAttributesDao
.newRow();
RelatedTablesUtils.populateUserRow(simpleAttributesRow.getTable(),
simpleAttributesRow,
SimpleAttributesTable.requiredColumns());
DublinCoreMetadata.setValue(simpleAttributesRow,
DublinCoreType.TITLE, DublinCoreType.TITLE.getName() + i);
DublinCoreMetadata.setValue(simpleAttributesRow,
DublinCoreType.DESCRIPTION,
DublinCoreType.DESCRIPTION.getName() + i);
DublinCoreMetadata.setValue(simpleAttributesRow,
DublinCoreType.SOURCE, DublinCoreType.SOURCE.getName() + i);
simpleAttributesIds.add(simpleAttributesDao
.create(simpleAttributesRow));
}
UserMappingDao userMappingDao = relatedTables.getMappingDao(relation);
AttributesDao attributesDao = geoPackage.getAttributesDao(tableName);
AttributesResultSet attributesResultSet = attributesDao.queryForAll();
while (attributesResultSet.moveToNext()) {
AttributesRow attributesRow = attributesResultSet.getRow();
long randomSimpleRowId = simpleAttributesIds.get((int) (Math
.random() * simpleAttributesIds.size()));
SimpleAttributesRow simpleAttributesRow = simpleAttributesDao
.getRow(simpleAttributesDao
.queryForIdRow(randomSimpleRowId));
UserMappingRow userMappingRow = userMappingDao.newRow();
userMappingRow.setBaseId(attributesRow.getId());
userMappingRow.setRelatedId(simpleAttributesRow.getId());
RelatedTablesUtils.populateUserRow(userMappingDao.getTable(),
userMappingRow, UserMappingTable.requiredColumns());
String attributesName = attributesRow.getValue(TEXT_COLUMN)
.toString();
DublinCoreMetadata.setValue(
userMappingRow,
DublinCoreType.TITLE,
attributesName
+ " - "
+ DublinCoreMetadata.getValue(simpleAttributesRow,
DublinCoreType.TITLE));
DublinCoreMetadata.setValue(
userMappingRow,
DublinCoreType.DESCRIPTION,
attributesName
+ " - "
+ DublinCoreMetadata.getValue(simpleAttributesRow,
DublinCoreType.DESCRIPTION));
DublinCoreMetadata.setValue(
userMappingRow,
DublinCoreType.SOURCE,
attributesName
+ " - "
+ DublinCoreMetadata.getValue(simpleAttributesRow,
DublinCoreType.SOURCE));
userMappingDao.create(userMappingRow);
}
attributesResultSet.close();
}
private static void createTileScalingExtension(GeoPackage geoPackage) {
for (String tileTable : geoPackage.getTileTables()) {
TileTableScaling tileTableScaling = new TileTableScaling(
geoPackage, tileTable);
TileScaling tileScaling = new TileScaling();
tileScaling.setScalingType(TileScalingType.IN_OUT);
tileScaling.setZoomIn(2l);
tileScaling.setZoomOut(2l);
tileTableScaling.create(tileScaling);
}
}
private static void createPropertiesExtension(GeoPackage geoPackage) {
PropertiesExtension properties = new PropertiesExtension(geoPackage);
String dateTime = DateConverter.dateTimeConverter().stringValue(
new Date());
properties.addValue(PropertyNames.TITLE, "GeoPackage Java Example");
properties.addValue(PropertyNames.VERSION, "3.0.2");
properties.addValue(PropertyNames.CREATOR, "NGA");
properties.addValue(PropertyNames.PUBLISHER, "NGA");
properties.addValue(PropertyNames.CONTRIBUTOR, "Brian Osborn");
properties.addValue(PropertyNames.CONTRIBUTOR, "Dan Barela");
properties.addValue(PropertyNames.CREATED, dateTime);
properties.addValue(PropertyNames.DATE, dateTime);
properties.addValue(PropertyNames.MODIFIED, dateTime);
properties
.addValue(
PropertyNames.DESCRIPTION,
"GeoPackage example created by http://github.com/ngageoint/geopackage-java/blob/master/src/test/java/mil/nga/geopackage/test/GeoPackageExample.java");
properties.addValue(PropertyNames.IDENTIFIER, "geopackage-java");
properties.addValue(PropertyNames.LICENSE, "MIT");
properties
.addValue(
PropertyNames.SOURCE,
"http://github.com/ngageoint/GeoPackage/blob/master/docs/examples/java/example.gpkg");
properties.addValue(PropertyNames.SUBJECT, "Examples");
properties.addValue(PropertyNames.TYPE, "Examples");
properties.addValue(PropertyNames.URI,
"http://github.com/ngageoint/geopackage-java");
properties.addValue(PropertyNames.TAG, "NGA");
properties.addValue(PropertyNames.TAG, "Example");
properties.addValue(PropertyNames.TAG, "BIT Systems");
}
private static void createContentsIdExtension(GeoPackage geoPackage) {
ContentsIdExtension contentsId = new ContentsIdExtension(geoPackage);
contentsId.createIds(ContentsDataType.FEATURES);
}
private static void createFeatureStyleExtension(GeoPackage geoPackage)
throws IOException {
Color color1 = new Color(ColorConstants.BLUE);
Color color2 = new Color(255, 0, 0, .4f);
Color color3 = new Color(0x000000);
StyleRow style1 = new StyleRow();
style1.setName("Style 1");
style1.setDescription("Style 1");
style1.setColor(ColorConstants.GREEN);
style1.setWidth(2.0);
StyleRow style2 = new StyleRow();
style2.setName("Style 2");
style2.setDescription("Style 2");
style2.setColor(color1);
style2.setWidth(1.5);
style2.setFillColor(color2);
StyleRow style3 = new StyleRow();
style3.setName("Style 3");
style3.setDescription("Style 3");
style3.setColor(color3);
File iconImageFile = TestUtils
.getTestFile(TestConstants.ICON_POINT_IMAGE);
byte[] iconBytes = GeoPackageIOUtils.fileBytes(iconImageFile);
BufferedImage iconImage = ImageUtils.getImage(iconBytes);
IconRow icon = new IconRow();
icon.setName("Icon 1");
icon.setDescription("Icon 1");
icon.setData(iconBytes);
icon.setContentType("image/png");
icon.setHeight(iconImage.getHeight() * .9);
icon.setWidth(iconImage.getWidth() * .9);
icon.setAnchorU(0.5);
icon.setAnchorV(1.0);
FeatureTableStyles geometry1Styles = new FeatureTableStyles(geoPackage,
"geometry1");
geometry1Styles.setTableStyleDefault(style1);
geometry1Styles.setTableStyle(GeometryType.POLYGON, style2);
geometry1Styles.setTableIconDefault(icon);
FeatureDao featureDao = geoPackage.getFeatureDao("geometry2");
FeatureTableStyles geometry2Styles = new FeatureTableStyles(geoPackage,
featureDao.getTable());
geometry2Styles.setTableStyle(GeometryType.POINT, style1);
geometry2Styles.setTableStyle(GeometryType.LINESTRING, style2);
geometry2Styles.setTableStyle(GeometryType.POLYGON, style1);
geometry2Styles.setTableStyle(GeometryType.GEOMETRY, style3);
geometry2Styles.createStyleRelationship();
geometry2Styles.createIconRelationship();
FeatureResultSet features = featureDao.queryForAll();
while (features.moveToNext()) {
FeatureRow featureRow = features.getRow();
switch (featureRow.getGeometryType()) {
case POINT:
geometry2Styles.setIcon(featureRow, icon);
break;
case LINESTRING:
geometry2Styles.setStyle(featureRow, style1);
break;
case POLYGON:
geometry2Styles.setStyle(featureRow, style2);
break;
default:
}
}
features.close();
}
}
|
package net.imagej.updater;
import static net.imagej.updater.FilesCollection.DEFAULT_UPDATE_SITE;
import static net.imagej.updater.UpdaterTestUtils.addUpdateSite;
import static net.imagej.updater.UpdaterTestUtils.assertStatus;
import static net.imagej.updater.UpdaterTestUtils.cleanup;
import static net.imagej.updater.UpdaterTestUtils.initialize;
import static net.imagej.updater.UpdaterTestUtils.main;
import static net.imagej.updater.UpdaterTestUtils.writeFile;
import static net.imagej.updater.UpdaterTestUtils.writeGZippedFile;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.scijava.util.FileUtils.deleteRecursively;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import net.imagej.updater.FileObject;
import net.imagej.updater.FilesCollection;
import net.imagej.updater.FileObject.Status;
import net.imagej.updater.util.StderrProgress;
import org.junit.After;
import org.junit.Test;
/**
* Tests the command-line updater.
*
* @author Johannes Schindelin
*/
public class CommandLineUpdaterTest {
protected FilesCollection files;
protected StderrProgress progress = new StderrProgress();
@After
public void after() {
if (files != null) cleanup(files);
}
@Test
public void testUploadCompleteSite() throws Exception {
final String to_remove = "macros/to_remove.ijm";
final String modified = "macros/modified.ijm";
final String installed = "macros/installed.ijm";
final String new_file = "macros/new_file.ijm";
files = initialize(to_remove, modified, installed);
File ijRoot = files.prefix("");
writeFile(new File(ijRoot, modified), "Zing! Zing a zong!");
writeFile(new File(ijRoot, new_file), "Aitch!");
assertTrue(new File(ijRoot, to_remove).delete());
files = main(files, "upload-complete-site", FilesCollection.DEFAULT_UPDATE_SITE);
assertStatus(Status.OBSOLETE_UNINSTALLED, files, to_remove);
assertStatus(Status.INSTALLED, files, modified);
assertStatus(Status.INSTALLED, files, installed);
assertStatus(Status.INSTALLED, files, new_file);
}
@Test
public void testUpload() throws Exception {
files = initialize();
final String path = "macros/test.ijm";
final File file = files.prefix(path);
writeFile(file, "// test");
files = main(files, "upload", "--update-site", DEFAULT_UPDATE_SITE, path);
assertStatus(Status.INSTALLED, files, path);
assertTrue(file.delete());
files = main(files, "upload", path);
assertStatus(Status.OBSOLETE_UNINSTALLED, files, path);
}
@Test
public void testUploadCompleteSiteWithShadow() throws Exception {
final String path = "macros/test.ijm";
final String obsolete = "macros/obsolete.ijm";
files = initialize(path, obsolete);
assertTrue(files.prefix(obsolete).delete());
files = main(files, "upload", obsolete);
final File tmp = addUpdateSite(files, "second");
writeFile(files.prefix(path), "// shadowing");
writeFile(files.prefix(obsolete), obsolete);
files = main(files, "upload-complete-site", "--force-shadow", "second");
assertStatus(Status.INSTALLED, files, path);
assertStatus(Status.INSTALLED, files, obsolete);
files = main(files, "remove-update-site", "second");
assertStatus(Status.MODIFIED, files, path);
assertStatus(Status.OBSOLETE, files, obsolete);
assertTrue(deleteRecursively(tmp));
}
@Test
public void testForcedShadow() throws Exception {
final String path = "macros/test.ijm";
files = initialize(path);
final File tmp = addUpdateSite(files, "second");
files = main(files, "upload", "--update-site", "second", "--force-shadow", path);
final File onSecondSite = new File(tmp, path + "-" + files.get(path).current.timestamp);
assertTrue("File exists: " + onSecondSite, onSecondSite.exists());
}
@Test
public void testUploadCompleteSiteWithPlatforms() throws Exception {
final String macro = "macros/macro.ijm";
final String linux32 = "lib/linux32/libtest.so";
files = initialize(macro, linux32);
assertPlatforms(files.get(linux32), "linux32");
File ijRoot = files.prefix("");
final String win64 = "lib/win64/test.dll";
assertTrue(new File(ijRoot, linux32).delete());
writeFile(new File(ijRoot, win64), "Dummy");
writeFile(new File(ijRoot, macro), "New version");
files = main(files, "upload-complete-site", "--platforms", "win64", FilesCollection.DEFAULT_UPDATE_SITE);
assertStatus(Status.NOT_INSTALLED, files, linux32);
assertStatus(Status.INSTALLED, files, win64);
assertStatus(Status.INSTALLED, files, macro);
files = main(files, "upload-complete-site", "--platforms", "all", FilesCollection.DEFAULT_UPDATE_SITE);
assertStatus(Status.OBSOLETE_UNINSTALLED, files, linux32);
}
@Test
public void testRemoveFile() throws Exception {
final String macro = "macros/macro.ijm";
files = initialize(macro);
assertTrue(files.prefix(files.get(macro)).delete());
files = main(files, "upload", macro);
assertStatus(Status.OBSOLETE_UNINSTALLED, files, macro);
}
private void assertPlatforms(final FileObject file, final String... platforms) {
final Set<String> filePlatforms = new HashSet<String>();
for (final String platform : file.getPlatforms()) filePlatforms.add(platform);
assertEquals(platforms.length, filePlatforms.size());
for (final String platform : platforms) {
assertTrue(file.getFilename(true) + "'s platforms should contain " + platform
+ " (" + filePlatforms + ")", filePlatforms.contains(platform));
}
}
@Test
public void testCircularDependenciesInOtherSite() throws Exception {
files = initialize();
final File second = addUpdateSite(files, "second");
final File third = addUpdateSite(files, "third");
// fake circular dependencies
writeGZippedFile(second, "db.xml.gz", "<pluginRecords>"
+ "<plugin filename=\"jars/a.jar\">"
+ "<version checksum=\"1\" timestamp=\"2\" filesize=\"3\" />"
+ "<dependency filename=\"jars/b.jar\" timestamp=\"2\" />"
+ "</plugin>"
+ "<plugin filename=\"jars/b.jar\">"
+ "<version checksum=\"4\" timestamp=\"2\" filesize=\"5\" />"
+ "<dependency filename=\"jars/a.jar\" timestamp=\"2\" />"
+ "</plugin>"
+ "</pluginRecords>");
writeFile(files, "macros/a.ijm");
files = main(files, "upload", "--update-site", "third", "macros/a.ijm");
final File uploaded = new File(third, "macros/a.ijm-" + files.get("macros/a.ijm").current.timestamp);
assertTrue(uploaded.exists());
// make sure that circular dependencies are still reported when uploading to the site
writeFile(files, "macros/b.ijm");
try {
files = main(files, "upload", "--update-site", "second", "macros/b.ijm");
assertTrue("Circular dependency not reported!", false);
} catch (RuntimeException e) {
assertEquals("Circular dependency detected: jars/b.jar -> jars/a.jar -> jars/b.jar\n",
e.getMessage());
}
}
@Test
public void testUploadUnchangedNewVersion() throws Exception {
final String path1 = "jars/test-1.0.0.jar";
final String path2 = "jars/test-1.0.1.jar";
files = initialize(path1);
files = main(files, "upload", "--update-site", DEFAULT_UPDATE_SITE, path1);
assertStatus(Status.INSTALLED, files, path1);
final File file1 = files.prefix(path1);
final File file2 = files.prefix(path2);
assertTrue(file1.renameTo(file2));
files = main(files, "upload", path2);
assertFalse(file1.exists());
assertTrue(file2.delete());
files = main(files, "update-force-pristine");
assertEquals(path2, files.get(path2).filename);
assertStatus(Status.INSTALLED, files, path2);
assertFalse(file1.exists());
assertTrue(file2.exists());
}
}
|
package com.ThirtyNineEighty.Base.Collisions;
import android.opengl.Matrix;
import com.ThirtyNineEighty.Base.Common.Math.*;
import com.ThirtyNineEighty.Base.EngineObject;
import com.ThirtyNineEighty.Base.Resources.Sources.FilePhGeometrySource;
import com.ThirtyNineEighty.Base.Resources.Entities.PhGeometry;
import com.ThirtyNineEighty.Base.GameContext;
import java.io.Serializable;
import java.util.ArrayList;
public class Collidable
extends EngineObject
implements Serializable
{
private static final long serialVersionUID = 1L;
private String name;
private Vector3 position;
private Vector3 lastInputPosition;
private Vector3 lastInputAngles;
private float[] verticesMatrix;
private float[] normalsMatrix;
private ArrayList<Vector3> normals;
private ArrayList<Vector3> vertices;
private transient PhGeometry geometryData;
public Collidable(String name)
{
this.name = name;
verticesMatrix = new float[16];
normalsMatrix = new float[16];
position = new Vector3();
normals = new ArrayList<>();
vertices = new ArrayList<>();
}
@Override
public void initialize()
{
geometryData = GameContext.resources.getPhGeometry(new FilePhGeometrySource(name));
fill(normals, geometryData.normals.size());
fill(vertices, geometryData.vertices.size());
super.initialize();
}
@Override
public void uninitialize()
{
super.uninitialize();
clear(normals);
clear(vertices);
GameContext.resources.release(geometryData);
}
public Vector3 getPosition()
{
return position;
}
public ArrayList<Vector3> getVertices()
{
return vertices;
}
public ArrayList<Vector3> getNormals()
{
return normals;
}
public float getRadius()
{
return geometryData.radius;
}
public void setLocation(Vector3 inputPosition, Vector3 inputAngles)
{
// check position or angles is changed
if (!isLocationChanged(inputPosition, inputAngles))
return;
// matrix
setMatrix(inputPosition, inputAngles);
// position
Matrix.multiplyMV(position.getRaw(), 0, verticesMatrix, 0, Vector3.zero.getRaw(), 0);
// vertices
for (int i = 0; i < geometryData.vertices.size(); i++)
{
Vector3 local = geometryData.vertices.get(i);
Vector3 global = vertices.get(i);
Matrix.multiplyMV(global.getRaw(), 0, verticesMatrix, 0, local.getRaw(), 0);
}
// normals
for (int i = 0; i < geometryData.normals.size(); i++)
{
Vector3 local = geometryData.normals.get(i);
Vector3 global = normals.get(i);
Matrix.multiplyMV(global.getRaw(), 0, normalsMatrix, 0, local.getRaw(), 0);
global.normalize();
}
}
private boolean isLocationChanged(Vector3 inputPosition, Vector3 inputAngles)
{
if (lastInputPosition == null || lastInputAngles == null)
{
lastInputPosition = new Vector3(inputPosition);
lastInputAngles = new Vector3(inputAngles);
}
else
{
if (inputPosition.equals(lastInputPosition) && inputAngles.equals(lastInputAngles))
return false;
lastInputPosition.setFrom(inputPosition);
lastInputAngles.setFrom(inputAngles);
}
return true;
}
private void setMatrix(Vector3 inputPosition, Vector3 inputAngles)
{
// Reset vertices matrix
Matrix.setIdentityM(verticesMatrix, 0);
// Set global
Matrix.translateM(verticesMatrix, 0, inputPosition.getX(), inputPosition.getY(), inputPosition.getZ());
Matrix.rotateM(verticesMatrix, 0, inputAngles.getX(), 1, 0, 0);
Matrix.rotateM(verticesMatrix, 0, inputAngles.getY(), 0, 1, 0);
Matrix.rotateM(verticesMatrix, 0, inputAngles.getZ(), 0, 0, 1);
// Set local
Matrix.translateM(verticesMatrix, 0, geometryData.position.getX(), geometryData.position.getY(), geometryData.position.getZ());
Matrix.rotateM(verticesMatrix, 0, geometryData.angles.getX(), 1, 0, 0);
Matrix.rotateM(verticesMatrix, 0, geometryData.angles.getY(), 0, 1, 0);
Matrix.rotateM(verticesMatrix, 0, geometryData.angles.getZ(), 0, 0, 1);
// Normals matrix
System.arraycopy(verticesMatrix, 0, normalsMatrix, 0, normalsMatrix.length);
// Reset translate
normalsMatrix[12] = 0;
normalsMatrix[13] = 0;
normalsMatrix[14] = 0;
}
private static void fill(ArrayList<Vector3> list, int count)
{
for (int i = 0; i < count; i++)
{
Vector3 vec = Vector3.getInstance();
list.add(vec);
}
}
private static void clear(ArrayList<Vector3> list)
{
Vector3.release(list);
list.clear();
}
}
|
package org.cojen.tupl.repl;
import java.io.File;
import java.net.ServerSocket;
import java.util.Arrays;
import java.util.Random;
import org.junit.*;
import static org.junit.Assert.*;
import org.cojen.tupl.TestUtils;
import static org.cojen.tupl.repl.MessageReplicator.*;
/**
*
*
* @author Brian S O'Neill
*/
// High load causes spurious timeouts.
@net.jcip.annotations.NotThreadSafe
public class MessageReplicatorTest {
public static void main(String[] args) throws Exception {
org.junit.runner.JUnitCore.main(MessageReplicatorTest.class.getName());
}
private static final long COMMIT_TIMEOUT_NANOS = 10_000_000_000L;
@Before
public void setup() throws Exception {
}
@After
public void teardown() throws Exception {
if (mReplicators != null) {
for (Replicator repl : mReplicators) {
if (repl != null) {
repl.close();
}
}
}
TestUtils.deleteTempFiles(getClass());
}
private File[] mReplBaseFiles;
private int[] mReplPorts;
private ReplicatorConfig[] mConfigs;
private MessageReplicator[] mReplicators;
/**
* @return first is the leader
*/
private MessageReplicator[] startGroup(int members) throws Exception {
return startGroup(members, Role.OBSERVER, true);
}
/**
* @return first is the leader
*/
private MessageReplicator[] startGroup(int members, Role replicaRole, boolean waitToJoin)
throws Exception
{
if (members < 1) {
throw new IllegalArgumentException();
}
ServerSocket[] sockets = new ServerSocket[members];
for (int i=0; i<members; i++) {
sockets[i] = new ServerSocket(0);
}
mReplBaseFiles = new File[members];
mReplPorts = new int[members];
mConfigs = new ReplicatorConfig[members];
mReplicators = new MessageReplicator[members];
for (int i=0; i<members; i++) {
mReplBaseFiles[i] = TestUtils.newTempBaseFile(getClass());
mReplPorts[i] = sockets[i].getLocalPort();
mConfigs[i] = new ReplicatorConfig()
.baseFile(mReplBaseFiles[i])
.groupToken(1)
.localSocket(sockets[i]);
if (i > 0) {
mConfigs[i].addSeed(sockets[0].getLocalSocketAddress());
mConfigs[i].localRole(replicaRole);
}
MessageReplicator repl = MessageReplicator.open(mConfigs[i]);
mReplicators[i] = repl;
repl.start();
readyCheck: {
for (int trial=0; trial<100; trial++) {
Thread.sleep(100);
if (i == 0) {
// Wait to become leader.
Reader reader = repl.newReader(0, false);
if (reader == null) {
break readyCheck;
}
reader.close();
} else if (waitToJoin) {
// Wait to join the group.
Reader reader = repl.newReader(0, true);
reader.close();
if (reader.term() > 0) {
break readyCheck;
}
} else {
break readyCheck;
}
}
throw new AssertionError(i == 0 ? "No leader" : "Not joined");
}
}
return mReplicators;
}
@Test
public void oneMember() throws Exception {
MessageReplicator[] repls = startGroup(1);
assertTrue(repls.length == 1);
MessageReplicator repl = repls[0];
Reader reader = repl.newReader(0, false);
assertNull(reader);
reader = repl.newReader(0, true);
assertNotNull(reader);
Writer writer = repl.newWriter(0);
assertNotNull(writer);
long term = writer.term();
assertEquals(1, term);
assertEquals(term, reader.term());
assertEquals(0, writer.termStartIndex());
assertEquals(0, reader.termStartIndex());
assertEquals(Long.MAX_VALUE, writer.termEndIndex());
assertEquals(Long.MAX_VALUE, reader.termEndIndex());
byte[] message = "hello".getBytes();
assertTrue(writer.writeMessage(message));
assertEquals(writer.index(), writer.waitForCommit(writer.index(), 0));
TestUtils.fastAssertArrayEquals(message, reader.readMessage());
}
@Test
public void twoMembers() throws Exception {
MessageReplicator[] repls = startGroup(2);
assertTrue(repls.length == 2);
MessageReplicator repl = repls[0];
Reader reader = repl.newReader(0, false);
assertNull(reader);
reader = repl.newReader(0, true);
assertNotNull(reader);
Writer writer = repl.newWriter();
assertNotNull(writer);
Reader replica = repls[1].newReader(0, false);
assertNotNull(replica);
long term = writer.term();
assertTrue(term > 0);
assertEquals(term, reader.term());
assertEquals(term, replica.term());
assertEquals(0, writer.termStartIndex());
assertEquals(0, reader.termStartIndex());
assertEquals(0, replica.termStartIndex());
assertEquals(Long.MAX_VALUE, writer.termEndIndex());
assertEquals(Long.MAX_VALUE, reader.termEndIndex());
assertEquals(Long.MAX_VALUE, replica.termEndIndex());
byte[] message = "hello".getBytes();
assertTrue(writer.writeMessage(message));
long highIndex = writer.index();
assertEquals(highIndex, writer.waitForCommit(highIndex, COMMIT_TIMEOUT_NANOS));
TestUtils.fastAssertArrayEquals(message, reader.readMessage());
TestUtils.fastAssertArrayEquals(message, replica.readMessage());
message = "world!".getBytes();
assertTrue(writer.writeMessage(message));
highIndex = writer.index();
assertEquals(highIndex, writer.waitForCommit(highIndex, COMMIT_TIMEOUT_NANOS));
TestUtils.fastAssertArrayEquals(message, reader.readMessage());
TestUtils.fastAssertArrayEquals(message, replica.readMessage());
}
@Test
public void threeMembers() throws Exception {
MessageReplicator[] repls = startGroup(3);
assertTrue(repls.length == 3);
Writer writer = repls[0].newWriter();
Reader r0 = repls[0].newReader(0, true);
Reader r1 = repls[1].newReader(0, true);
Reader r2 = repls[2].newReader(0, true);
byte[][] messages = {"hello".getBytes(), "world!".getBytes()};
for (byte[] message : messages) {
assertTrue(writer.writeMessage(message));
long highIndex = writer.index();
assertTrue(highIndex <= writer.waitForCommit(highIndex, COMMIT_TIMEOUT_NANOS));
TestUtils.fastAssertArrayEquals(message, r0.readMessage());
TestUtils.fastAssertArrayEquals(message, r1.readMessage());
TestUtils.fastAssertArrayEquals(message, r2.readMessage());
}
}
@Test
public void variableMessageSizes() throws Exception {
variableMessageSizes(false);
}
@Test
public void variableMessageSizesPartial() throws Exception {
variableMessageSizes(true);
}
private void variableMessageSizes(boolean partial) throws Exception {
MessageReplicator[] repls = startGroup(3);
int[] sizes = {
0, 1, 10, 100, 127,
128, 129, 1000, 8190, 8191, 8192, 8193, 10000, 16383, 16384, 16385, 16510, 16511,
16512, 16513, 20000, 100_000
};
final long seed = 9823745;
Random rnd = new Random(seed);
Writer writer = repls[0].newWriter();
for (int size : sizes) {
byte[] message = TestUtils.randomStr(rnd, size);
assertTrue(writer.writeMessage(message));
}
long highIndex = writer.index();
assertEquals(highIndex, writer.waitForCommit(highIndex, COMMIT_TIMEOUT_NANOS));
byte[] buf = new byte[1001];
for (MessageReplicator repl : repls) {
rnd = new Random(seed);
Reader reader = repl.newReader(0, true);
for (int size : sizes) {
byte[] expected = TestUtils.randomStr(rnd, size);
byte[] actual;
if (!partial) {
actual = reader.readMessage();
} else {
int result = reader.readMessage(buf, 1, 1000);
if (result >= 0) {
actual = Arrays.copyOfRange(buf, 1, 1 + result);
} else {
try {
reader.readMessage();
fail();
} catch (IllegalStateException e) {
// Cannot read next message when partial exists.
}
assertNotEquals(-1, result);
actual = new byte[1000 + ~result];
System.arraycopy(buf, 1, actual, 0, 1000);
reader.readMessage(actual, 1000, ~result);
}
}
TestUtils.fastAssertArrayEquals(expected, actual);
}
reader.close();
}
}
@Test
public void largeGroupNoWaitToJoin() throws Exception {
final int count = 10;
/*
FIXME: largeGroupNoWaitToJoin(org.cojen.tupl.repl.MessageReplicatorTest) Time elapsed: 18.344 s <<< ERROR!
org.cojen.tupl.repl.JoinException: group version mismatch
at org.cojen.tupl.repl.GroupJoiner.doJoin(GroupJoiner.java:269)
at org.cojen.tupl.repl.GroupJoiner.join(GroupJoiner.java:109)
at org.cojen.tupl.repl.Controller.init(Controller.java:171)
at org.cojen.tupl.repl.Controller.open(Controller.java:137)
at org.cojen.tupl.repl.StreamReplicator.open(StreamReplicator.java:113)
at org.cojen.tupl.repl.MessageReplicator.open(MessageReplicator.java:38)
at org.cojen.tupl.repl.MessageReplicatorTest.startGroup(MessageReplicatorTest.java:112)
at org.cojen.tupl.repl.MessageReplicatorTest.largeGroupNoWaitToJoin(MessageReplicatorTest.java:326)
*/
MessageReplicator[] repls = startGroup(count, Role.STANDBY, false);
Writer writer = repls[0].newWriter();
Reader[] readers = new Reader[count];
for (int i=0; i<count; i++) {
readers[i] = repls[i].newReader(0, true);
}
for (int q=0; q<20; q++) {
byte[] message = ("hello-" + q).getBytes();
assertTrue(writer.writeMessage(message));
long highIndex = writer.index();
// Note: Actual commit index might be higher, because of control messages which
// were sent by the replication system for membership changes.
assertTrue(highIndex >= writer.waitForCommit(highIndex, COMMIT_TIMEOUT_NANOS));
for (int j=0; j<readers.length; j++) {
Reader reader = readers[j];
byte[] actual;
while ((actual = reader.readMessage()) == null) {
// Reader was created at false term of 0. Move to the correct one.
reader.close();
reader = repls[j].newReader(reader.index(), true);
readers[j] = reader;
}
TestUtils.fastAssertArrayEquals(message, actual);
}
}
}
}
|
package com.acod.play.app.Activities;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.SearchManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import com.acod.play.app.R;
import com.acod.play.app.fragments.HomeFragment;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.google.analytics.tracking.android.EasyTracker;
import com.inscription.ChangeLogDialog;
/**
* @author Andrew Codispoti
* This is the main activtiy that will contain the vairous fragments and also do all of the searching system wide.
*/
public class HomescreenActivity extends SherlockActivity {
public static final String PLAY_ACTION = "com.acod.play.playmusic";
public static final String PAUSE_ACTION = "com.acod.play.pausemusic";
public static final String STOP_ACTION = "com.acod.play.stopmusic";
public static final boolean debugMode = false;
public static float APP_VERSION = 1;
FragmentManager manager;
FragmentTransaction fragmentTransaction;
Context c;
HomescreenActivity a;
private DrawerLayout drawerLayout;
private ListView drawerList;
private String[] drawertitles;
private ActionBarDrawerToggle toggle;
public static Intent getOpenFacebookIntent(Context context) {
try {
context.getPackageManager().getPackageInfo("com.facebook.katana", 0);
return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/296814327167093"));
} catch (Exception e) {
return new Intent(Intent.ACTION_VIEW, Uri.parse("https:
}
}
public static boolean checkNetworkState(Context context) {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
@Override
protected void onStop() {
super.onStop();
EasyTracker.getInstance(this).activityStop(this); // Add this method.
}
private void googlePlus() {
String communityPage = "communities/112916674490953671434";
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setClassName("com.google.android.apps.plus",
"com.google.android.apps.plus.phone.UrlGatewayActivity");
intent.putExtra("customAppUri", communityPage);
startActivity(intent);
} catch (ActivityNotFoundException e) {
// fallback if G+ app is not installed
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://plus.google.com/" + communityPage)));
}
}
@Override
protected void onStart() {
super.onStart();
EasyTracker.getInstance(this).activityStart(this); // Add this method.
if (!checkNetworkState(this))
Toast.makeText(this, "Check your internet connection", Toast.LENGTH_LONG).show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homescreen);
//put the homescreen view into place
c = this;
drawertitles = getResources().getStringArray(R.array.menutiems);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerList = (ListView) findViewById(R.id.left_drawer);
drawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, drawertitles));
drawerList.setOnItemClickListener(new DrawerItemClickListener());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
toggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.opendrawer, R.string.app_name);
drawerLayout.setDrawerListener(toggle);
manager = getFragmentManager();
fragmentTransaction = manager.beginTransaction();
HomeFragment frag = new HomeFragment();
fragmentTransaction.add(R.id.content_frame, frag).addToBackStack(null);
fragmentTransaction.commit();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case android.R.id.home:
if (!drawerLayout.isDrawerOpen(Gravity.LEFT))
drawerLayout.openDrawer(Gravity.LEFT);
else drawerLayout.closeDrawer(Gravity.LEFT);
break;
case R.id.changes:
ChangeLogDialog dialog = new ChangeLogDialog(c);
dialog.show();
break;
case R.id.report:
startEmailIntent();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
toggle.onConfigurationChanged(newConfig);
}
public void startEmailIntent() {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL, new String[]{"andrewcod749@gmail.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "Play (Android)");
i.putExtra(Intent.EXTRA_TEXT, "");
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
//TODO figure out why recent suggestions only works on search activity
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.homescreen, menu);
SearchView sv = (SearchView) menu.findItem(R.id.search).getActionView();
SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
sv.setSearchableInfo(manager.getSearchableInfo(getComponentName()));
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
startActivity(new Intent(getApplicationContext(), SearchActivity.class).putExtra(SearchManager.QUERY, s).setAction("android.intent.action.SEARCH"));
return false;
}
@Override
public boolean onQueryTextChange(String s) {
return false;
}
});
sv.setIconifiedByDefault(false);
return true;
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
toggle.syncState();
}
public void handleTwitter() {
try {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("twitter://user?screen_name=andrewcod749"));
startActivity(intent);
} catch (Exception e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("https://twitter.com/#!/andrewcod749")));
}
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
switch (i) {
case 0:
//my songs section
startActivity(new Intent(getApplicationContext(), SavedActivity.class));
break;
case 1:
//twitter list
handleTwitter();
break;
case 2:
//facebook page
startActivity(getOpenFacebookIntent(getApplicationContext()));
break;
case 3:
//google plus community
googlePlus();
break;
}
}
}
}
|
package uk.co.benjiweber.expressions;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static uk.co.benjiweber.expressions.Property.get;
public class PropertyTest {
static class Person {
private String name;
public final Property<String> Name = get(() -> name).set(value -> this.name = value);
}
@Test
public void property() {
Person person = new Person();
assertNull(person.Name.get());
assertNull(person.name);
person.Name.set("Bob");
assertEquals("Bob", person.Name.get());
assertEquals("Bob", person.name);
person.Name.set("Bill");
assertEquals("Bill", person.Name.get());
assertEquals("Bill", person.name);
}
}
|
package com.example.shalantor.connect4;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class GamePlayActivity extends SurfaceView implements Runnable{
private Thread thread = null;
private SurfaceHolder holder;
volatile boolean playingConnect4;
/*TODO: remove hard coded values from boolean variables*/
volatile boolean isSinglePlayer;
volatile boolean isMultiPlayer ;
volatile boolean isMuted;
volatile boolean isExitMenuVisible ;
volatile boolean isPlayersTurn ;
volatile boolean isColorChoiceVisible;
volatile boolean isChipFalling;
volatile boolean isGameOver;
private Paint paint;
private Canvas canvas;
/*fps*/
private long lastFrameTime;
/*Screen dimensions info*/
private int screenHeight;
private int screenWidth;
private int cellWidth;
private int cellheight;
/*arrays to store game info*/
private int[][] gameGrid;
private int[] howManyChips;
/*image variables*/
private Bitmap redChip;
private Bitmap yellowChip;
private Bitmap emptyCell;
private Bitmap yellowCell;
private Bitmap redCell;
private Bitmap soundOn;
private Bitmap soundOff;
private Bitmap backButton;
private Bitmap playerChipColor;
private Bitmap enemyChipColor;
/*Width of texts*/
private float noTextWidth;
private float yesTextWidth;
/*Associated activity*/
private Activity associatedActivity;
/*Variable to store which column was chose by the player, where -1 means that no column is chosen right now*/
private int activeColumnNumber;
/*where will next chip be inserted*/
private int finalChipHeight;
private Rect fallingChip;
private int fallingChipPosition;
private int playerChipColorInt;
private int enemyChipColorInt;
private int fallingChipColor;
/*End screen Message for player after match*/
private String endScreenMessage;
public GamePlayActivity(Context context){
super(context);
holder = getHolder();
paint = new Paint();
associatedActivity = (Activity) context;
Intent intent = associatedActivity.getIntent();
if(intent.getIntExtra("MODE",-1) == 0){
isSinglePlayer = true;
isMultiPlayer = false;
}
else{
isMultiPlayer = true;
isSinglePlayer = false;
}
fallingChip = null;
/*Boolean variables*/
isExitMenuVisible = false;
isMuted = false;
activeColumnNumber = -1;
isColorChoiceVisible = true;
isChipFalling = false;
isGameOver = false;
/*Will change after choosing menu, is just set true to stop AI from making a move*/
isPlayersTurn = true;
/*Get screen dimensions*/
Display display = associatedActivity.getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenHeight = size.y;
screenWidth = size.x;
/*Set dimensions of field*/
cellWidth = screenWidth/10;
cellheight = screenHeight/6;
/*Load images*/
redChip = BitmapFactory.decodeResource(getResources(),R.mipmap.redchip);
yellowChip = BitmapFactory.decodeResource(getResources(),R.mipmap.yellowchip);
emptyCell = BitmapFactory.decodeResource(getResources(),R.mipmap.emptycell);
redCell = BitmapFactory.decodeResource(getResources(),R.mipmap.redcell);
yellowCell = BitmapFactory.decodeResource(getResources(),R.mipmap.yellowcell);
soundOff = BitmapFactory.decodeResource(getResources(),R.mipmap.sound_off);
soundOn = BitmapFactory.decodeResource(getResources(),R.mipmap.sound_on);
backButton = BitmapFactory.decodeResource(getResources(),R.mipmap.back_button);
/*Create array for field, 0 means empty , 1 means red chip, 2 means yellow chip*/
gameGrid = new int[6][7];
howManyChips = new int[7];
}
@Override
public void run(){
while(playingConnect4){
if(!isPlayersTurn && !isChipFalling && !isGameOver){ /*wait for chip to fall and then get move of AI*/
int move = getMove();
makeMove(move);
}
updateGUIObjects();
drawScreen();
controlFPS();
}
}
/*Method to update GUI components that will animate the menu*/
public void updateGUIObjects(){
/*We have a chip*/
if(fallingChip != null){
/*Move down chip a bit*/
fallingChip.top += cellheight/8;
fallingChip.bottom += cellheight/8;
if(fallingChip.bottom >= finalChipHeight){
fallingChip = null; //remove
if(!isPlayersTurn)
gameGrid[5 - howManyChips[fallingChipPosition]][fallingChipPosition] = playerChipColorInt;
else
gameGrid[5 - howManyChips[fallingChipPosition]][fallingChipPosition] = enemyChipColorInt;
howManyChips[fallingChipPosition] += 1;
isChipFalling = false;
if(hasWon(fallingChipPosition,fallingChipColor,howManyChips,gameGrid)){
if(!isPlayersTurn){ /*the chip which is falling, falls after the turn change*/
endScreenMessage = "YOU WIN";
}
else{
endScreenMessage = "YOU LOSE";
}
isGameOver = true;
}
else if(isGridFull()){
endScreenMessage = "TIE";
isGameOver = true;
}
}
}
}
/*Method to draw the game fields and the menu on screen*/
public void drawScreen(){
if(holder.getSurface().isValid()){
canvas = holder.lockCanvas();
canvas.drawColor(Color.BLACK); /*Background*/
paint = new Paint();
/*Check if chip is falling and draw it if it is*/
if(isChipFalling){
if(!isPlayersTurn)
canvas.drawBitmap(playerChipColor,null,fallingChip,paint);
else
canvas.drawBitmap(enemyChipColor,null,fallingChip,paint);
}
/*Game grid*/
Rect destRect;
Bitmap imageToDraw;
/*Draw each cell*/
for( int i = 0; i < 6;i++){
for(int j =0; j < 7;j++){
destRect = new Rect(j*cellWidth,i*cellheight,(j+1)*cellWidth,(i+1)*cellheight);
if(gameGrid[i][j] == 0){
imageToDraw = emptyCell;
}
else if(gameGrid[i][j] == 1){
imageToDraw = redCell;
}
else{
imageToDraw = yellowCell;
}
canvas.drawBitmap(imageToDraw,null,destRect,paint);
}
}
/*Now draw rect for menu*/
paint.setColor(Color.argb(255,153,255,255));
canvas.drawRect(7*screenWidth/10,0,screenWidth,screenHeight,paint);
/*Write some info*/
paint.setTextSize(screenHeight/15);
paint.setTextAlign(Paint.Align.CENTER);
paint.setColor(Color.BLACK);
canvas.drawText("OPPONENT:",8*screenWidth/10 + screenWidth/20,screenHeight/15,paint);
if(isSinglePlayer){
paint.setTextSize(screenHeight/10);
canvas.drawText("AI",8*screenWidth/10 + screenWidth/20,screenHeight/4,paint);
paint.setTextSize(screenHeight/15);
}
canvas.drawText("TIME:",8*screenWidth/10 + screenWidth/20,screenHeight/2,paint);
if(isSinglePlayer){
canvas.drawText("-",8*screenWidth/10 + screenWidth/20,screenHeight/2 + 2*screenHeight/15,paint);
}
/*Draw back button and and sound button*/
int buttonDimension = screenWidth/10;
/*Destination rect for sound button*/
destRect = new Rect(7*screenWidth/10,screenHeight - buttonDimension,
7*screenWidth/10+ buttonDimension,screenHeight );
/*Draw sound button based on volume*/
if(isMuted){
imageToDraw = soundOff;
}
else{
imageToDraw = soundOn;
}
canvas.drawBitmap(imageToDraw,null,destRect,paint);
/*Destination for back button*/
destRect = new Rect(9*screenWidth/10,screenHeight - buttonDimension, screenWidth,screenHeight);
canvas.drawBitmap(backButton,null,destRect,paint);
/*Highlight the active column if there is one*/
if(activeColumnNumber >= 0) {
paint.setColor(Color.argb(128, 0, 255, 0));
canvas.drawRect(screenWidth/10 * activeColumnNumber,0,
(activeColumnNumber + 1) * screenWidth/10,screenHeight,paint);
}
/*Draw the chip color choice panel if visible*/
if(isColorChoiceVisible){
/*Draw background*/
paint.setColor(Color.argb(224,0,0,0));
canvas.drawRect(0,0,7*screenWidth/10,screenHeight,paint);
/*Draw text*/
paint.setTextAlign(Paint.Align.CENTER);
paint.setTextSize(screenHeight/8);
paint.setColor(Color.WHITE);
canvas.drawText("Choose a color:",screenWidth/3,screenHeight/4,paint);
/*Draw chips*/
Rect redChipDestRect = new Rect(screenWidth/10,screenHeight/3,3*screenWidth/10,2*screenHeight/3);
Rect yellowChipDestRect = new Rect(4*screenWidth/10,screenHeight/3,6*screenWidth/10,2*screenHeight/3);
canvas.drawBitmap(redChip,null,redChipDestRect,paint);
canvas.drawBitmap(yellowChip,null,yellowChipDestRect,paint);
}
/*Draw winning message*/
if(isGameOver){
paint.setColor(Color.argb(200,0,0,0));
canvas.drawRect(0,0,7*screenWidth/10,screenHeight,paint);
paint.setTextAlign(Paint.Align.CENTER);
paint.setTextSize(screenHeight/8);
paint.setColor(Color.WHITE);
canvas.drawText(endScreenMessage,screenWidth/3,screenHeight/4,paint);
}
/*Draw the exit menu if it is visible*/
if(isExitMenuVisible){
canvas.drawColor(Color.argb(200,0,0,0));
paint.setTextSize(screenHeight/4);
paint.setTextAlign(Paint.Align.CENTER);
paint.setColor(Color.WHITE);
canvas.drawText("EXIT?",screenWidth/2,screenHeight/3,paint);
paint.setTextSize(screenHeight/5);
canvas.drawText("YES",screenWidth/3,2*screenHeight/3,paint);
canvas.drawText("NO",2*screenWidth/3,2*screenHeight/3,paint);
yesTextWidth = paint.measureText("YES");
noTextWidth = paint.measureText("NO");
}
holder.unlockCanvasAndPost(canvas);
}
}
/*Method to control the refresh rate of screen*/
public void controlFPS(){
long timeThisFrame = System.currentTimeMillis() - lastFrameTime;
long timeToSleep = 10 - timeThisFrame;
if(timeToSleep > 0){
try{
thread.sleep(timeToSleep);
}catch (InterruptedException ex){
Log.d("THREAD_SLEEP","Interrupted exception occured");
}
}
lastFrameTime = System.currentTimeMillis();
}
/*To pause animation*/
public void pause(){
playingConnect4 = false;
boolean run = true;
while(run) {
try {
thread.join();
run = false;
} catch (InterruptedException ex) {
Log.d("THREAD_JOIN", "Interrupted exception occured");
}
}
}
/*To continue animation from a pause*/
public void resume(){
playingConnect4 = true;
thread = new Thread(this);
thread.start();
}
/*Validate touchevent*/
public boolean validateTouchEvent(MotionEvent event){
float initialY = event.getY();
float initialX = event.getX();
if(event.getActionMasked() == MotionEvent.ACTION_DOWN){
if(isExitMenuVisible){
/*YES BUTTON*/
if(initialX >= screenWidth/3 - yesTextWidth && initialX <= screenWidth/3 + yesTextWidth
&& initialY >= 2*screenHeight/3 - screenHeight/5
&& initialY <= 2*screenHeight/3){
pause();
Intent intent = new Intent(associatedActivity,MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
associatedActivity.startActivity(intent);
associatedActivity.finish();
}
/*NO BUTTON*/
if(initialX >= 2*screenWidth/3 - noTextWidth && initialX <= 2*screenWidth/3 + noTextWidth
&& initialY >= 2*screenHeight/3 - screenHeight/5
&& initialY <= 2*screenHeight/3){
isExitMenuVisible = false;
}
return true;
}
else if(isColorChoiceVisible){
/*BACK BUTTON*/
if(initialX >= 9*screenWidth/10 && initialX <= screenWidth
&& initialY >= screenHeight - screenWidth/10 && initialY <= screenHeight){
isExitMenuVisible = true;
}
/*SOUND BUTTON*/
else if(initialX >= 7*screenWidth/10 && initialX <= 8*screenWidth/10
&& initialY >= screenHeight - screenWidth/10 && initialY <= screenHeight) {
/*TODO:add code to mute sound when we have a soundtrack*/
isMuted = !isMuted;
}
/*RED CHIP ICON*/
else if(initialX >= screenWidth/10 && initialX <= 3*screenWidth/10
&& initialY >= screenHeight/3 && initialY <= 2*screenHeight/3){
playerChipColorInt = 1;
playerChipColor = redChip;
enemyChipColorInt = 2;
enemyChipColor = yellowChip;
isColorChoiceVisible = false;
}
/*YELLOW CHIP ICON*/
else if(initialX >= 4*screenWidth/10 && initialX <= 6*screenWidth/10
&& initialY >= screenHeight/3 && initialY <= 2*screenHeight/3){
playerChipColorInt = 2;
playerChipColor = yellowChip;
enemyChipColor = redChip;
enemyChipColorInt = 1;
isColorChoiceVisible = false;
}
if(!isColorChoiceVisible)
isPlayersTurn = Math.random() > 0.5;
}
else{
/*BACK BUTTON*/
if(initialX >= 9*screenWidth/10 && initialX <= screenWidth
&& initialY >= screenHeight - screenWidth/10 && initialY <= screenHeight){
isExitMenuVisible = true;
}
/*SOUND BUTTON*/
else if(initialX >= 7*screenWidth/10 && initialX <= 8*screenWidth/10
&& initialY >= screenHeight - screenWidth/10 && initialY <= screenHeight){
/*TODO:add code to mute sound when we have a soundtrack*/
isMuted = !isMuted;
}
else if(isPlayersTurn && !isChipFalling && !isGameOver){ /*Is it the players turn?*/
/*Check which column is active*/
if(initialX <= screenWidth/10){
if(activeColumnNumber == 0 && hasSpace(0)) {
makeMove(0);
activeColumnNumber = -1;
}
else if(!hasSpace(0)){
activeColumnNumber = -1;
}
else {
activeColumnNumber = 0;
}
}
else if(initialX <= 2*screenWidth/10){
if(activeColumnNumber ==1 && hasSpace(1)) {
makeMove(1);
activeColumnNumber = -1;
}
else if(!hasSpace(1)){
activeColumnNumber = -1;
}
else {
activeColumnNumber = 1;
}
}
else if(initialX <= 3*screenWidth/10){
if(activeColumnNumber ==2 && hasSpace(2)) {
makeMove(2);
activeColumnNumber = -1;
}
else if(!hasSpace(2)){
activeColumnNumber = -1;
}
else {
activeColumnNumber = 2;
}
}
else if(initialX <= 4*screenWidth/10){
if(activeColumnNumber ==3 && hasSpace(3)) {
makeMove(3);
activeColumnNumber = -1;
}
else if(!hasSpace(3)){
activeColumnNumber = -1;
}
else {
activeColumnNumber = 3;
}
}
else if(initialX <= 5*screenWidth/10){
if(activeColumnNumber ==4 && hasSpace(4)) {
makeMove(4);
activeColumnNumber = -1;
}
else if(!hasSpace(4)){
activeColumnNumber = -1;
}
else {
activeColumnNumber = 4;
}
}
else if(initialX <= 6*screenWidth/10){
if(activeColumnNumber ==5 && hasSpace(5)) {
makeMove(5);
activeColumnNumber = -1;
}
else if(!hasSpace(5)){
activeColumnNumber = -1;
}
else {
activeColumnNumber = 5;
}
}
else if(initialX <= 7*screenWidth/10){
if(activeColumnNumber ==6 && hasSpace(6)) {
makeMove(6);
activeColumnNumber = -1;
}
else if(!hasSpace(6)){
activeColumnNumber = -1;
}
else {
activeColumnNumber = 6;
}
}
return true;
}
}
}
return false;
}
/*Check if chip can be inserted in specified field*/
private boolean hasSpace(int columnNumber){
return howManyChips[columnNumber] < 6;
}
/*Insert chip in specified position*/
public void makeMove(int columnNumber){
isChipFalling = true;
finalChipHeight = screenHeight - howManyChips[columnNumber]*cellheight;
fallingChipPosition = columnNumber;
/*Create new chip and add it to list*/
fallingChip = new Rect(columnNumber*cellWidth,-cellheight,(columnNumber+1)*cellWidth,0);
if(isPlayersTurn){
fallingChipColor = playerChipColorInt;
}
else{
fallingChipColor = enemyChipColorInt;
}
isPlayersTurn = !isPlayersTurn;
}
/*Check if player has won*/
private boolean hasWon(int position,int color,int[] howManyChips, int[][]gameGrid){
int row = 6 - howManyChips[position];
int column = fallingChipPosition;
/*Check same line*/
int sameColor = 0;
for(int i =0; i < 7 ; i++){
if(gameGrid[row][i] == color){
sameColor += 1;
if (sameColor == 4)
return true;
}
else
sameColor = 0;
}
/*check same column*/
sameColor = 0;
for(int i =0;i < 6; i++){
if(gameGrid[i][column] == color){
sameColor += 1;
if(sameColor == 4)
return true;
}
else
sameColor = 0;
}
/*check same diagonal*/
sameColor = 0;
int rowStart = row;
int columnStart = column;
/*find the start of diagonal which goes from left up to right down*/
while(rowStart >= 0 && columnStart >= 0){
rowStart -= 1;
columnStart -= 1;
}
/*Fix negative values*/
rowStart += 1;
columnStart += 1;
/*Now check the color*/
while(rowStart <= 5 && columnStart <= 6){
if(gameGrid[rowStart][columnStart] == color){
sameColor += 1;
if(sameColor == 4)
return true;
}
else
sameColor = 0;
rowStart += 1;
columnStart += 1;
}
/*Now check the diagonal going from left down to right up*/
sameColor = 0;
rowStart = row;
columnStart = column;
/*Again find the start*/
while(rowStart <= 5 && columnStart >= 0){
rowStart += 1;
columnStart -= 1;
}
/*Fix values*/
columnStart += 1;
rowStart -= 1;
/*Now check the color*/
while(rowStart >= 0 && columnStart <= 6){
if(gameGrid[rowStart][columnStart] == color){
sameColor += 1;
if(sameColor == 4)
return true;
}
else
sameColor = 0;
rowStart -= 1;
columnStart += 1;
}
return false;
}
/*Check if grid is full without a player having won*/
private boolean isGridFull(){
for(int i =0; i < 6;i++){
for(int j =0;j<7;j++){
if(gameGrid[i][j] == 0)
return false;
}
}
return true;
}
/*TODO:complete method*/
/*Gets the next move from AI or other player*/
private int getMove(){
int[][] checkGrid = new int[6][7];
int[] checkGridChipCounter = new int[7];
/*if it is computers first move choose column 3
*If column 3 is already taken take column 2
*/
int spaceCounter = 0;
for(int i =0; i < 7; i++){
if(howManyChips[i] > 0){
spaceCounter += 1;
}
}
if(spaceCounter <= 1){
if(gameGrid[5][2] == 0)
return 2;
else
return 1;
}
/*copyGrid*/
for(int i = 0; i < 6; i++){
for(int j =0; j < 7; j++){
checkGrid[i][j] = gameGrid[i][j];
}
}
/*Copy counter array*/
for(int j =0; j < 7; j++){
checkGridChipCounter[j] = howManyChips[j];
}
/*Now check if computer can win with a move*/
for(int i = 0; i < 7; i++){
if(checkGridChipCounter[i] < 6) {
checkGrid[5 - checkGridChipCounter[i]][i] = enemyChipColorInt;
checkGridChipCounter[i] += 1;
if(hasWon(i,enemyChipColorInt,checkGridChipCounter,checkGrid)){
Log.d("WIN","COLUMN " + i);
return i;
}
checkGridChipCounter[i] -= 1;
checkGrid[5 - checkGridChipCounter[i]][i] = 0;
}
}
/*Now check if player can win , so that computer will stop him*/
for(int i = 0; i < 7; i++){
if(checkGridChipCounter[i] < 6) {
checkGrid[5 - checkGridChipCounter[i]][i] = playerChipColorInt;
checkGridChipCounter[i] += 1;
if(hasWon(i,playerChipColorInt,checkGridChipCounter,checkGrid)){
Log.d("WIN_STOP","COLUMN " + i);
return i;
}
checkGridChipCounter[i] -= 1;
checkGrid[5 - checkGridChipCounter[i]][i] = 0;
}
}
/*If none of the above holds, compute move from minimax algorithm*/
return 0;
}
/*Method to evaluate value of current grid state for the computer or the player
* According to the minimax algorithm for a connect 4 game, the value of fields
* is described below, where X stands for a chip and a 0 stands for an empty position:
* A neutral chip position is given a value of 0 points.
* 2 chips in the same row have a value of 10. (00XX) or (0X0X) or (X00X) or (X0X0) or (XX00)
* If those two chips don't have adjacent chips, they have a value of 20. (0XX0)
* 3 in the same row have a value of 1000 points. (XX0X) or (X0XX) or (XXX0) or (0XXX)
* If those three chips have no adjacent chips, they have a value of 2000 (0XXX0)
*
* The same holds for chips in the same column or diagonal, but there are some
* modifiers for their values.Those modifiers are:
*
* Vertical = 1
* Diagonal = 2
* Horizontal = 3*/
private int getGridValue(int[][] grid,int color){
int vertical = 1;
int diagonal = 2;
int horizontal = 3;
int twoSame = 10;
int threeSame = 1000;
int value = 0;
/*horizontal 2 in the same row */
for(int row =0;row < 6;row++){
for(int col = 0;col < 4; col++){
//XX00
if(grid[col][row] == color && grid[col+1][row] == color
&& grid[col+2][row] == 0 && grid[col+3][row] == 0){
value += twoSame * horizontal;
}
//X0X0
else if (grid[col][row] == color && grid[col+1][row] == 0
&& grid[col+2][row] == color && grid[col+3][row] == 0){
value += twoSame * horizontal;
}
//X00X
else if (grid[col][row] == color && grid[col+1][row] == 0
&& grid[col+2][row] == 0 && grid[col+3][row] == color){
value += twoSame * horizontal;
}
//0XX0
else if (grid[col][row] == 0 && grid[col+1][row] == color
&& grid[col+2][row] == color && grid[col+3][row] == 0){
value += 2*twoSame * horizontal;
}
//0X0X
else if (grid[col][row] == 0 && grid[col+1][row] == color
&& grid[col+2][row] == 0 && grid[col+3][row] == color){
value += twoSame * horizontal;
}
//00XX
else if (grid[col][row] == 0 && grid[col+1][row] == 0
&& grid[col+2][row] == color && grid[col+3][row] == color){
value += twoSame * horizontal;
}
}
}
/*Now check for vertical 2 in same column, with a space above like this:
* 0
* X
* X */
for(int row =0; row <= 3; row ++){
for(int col = 0; col < 7; col ++){
if(grid[row][col] == 0 && grid[row+1][col] == color && grid[row+2][col] == color)
value += twoSame * vertical;
}
}
/*Now check for 2 in the same diagonal from left down to right up (/)
*Possible arrangements are :
* 0 X X X 0 0
* 0 0 X 0 X X
* X 0 0 X 0 X
* X X 0 0 X 0
* We start from bottom to top this time.
*/
for(int row = 5; row >= 3; row
for(int col =0; col <= 3; col++){
if(grid[row][col] == color && grid[row-1][col+1] == color
&& grid[row-2][col+2] == 0 && grid[row-3][col+3] == 0){
value += twoSame * diagonal;
}
else if(grid[row][col] == color && grid[row-1][col+1] == 0
&& grid[row-2][col+2] == 0 && grid[row-3][col+3] == color){
value += twoSame * diagonal;
}
else if(grid[row][col] == 0 && grid[row-1][col+1] == 0
&& grid[row-2][col+2] == color && grid[row-3][col+3] == color){
value += twoSame * diagonal;
}
else if(grid[row][col] == 0 && grid[row-1][col+1] == color
&& grid[row-2][col+2] == 0 && grid[row-3][col+3] == color){
value += twoSame * diagonal;
}
else if(grid[row][col] == color && grid[row-1][col+1] == 0
&& grid[row-2][col+2] == color && grid[row-3][col+3] == 0){
value += twoSame * diagonal;
}
else if(grid[row][col] == 0 && grid[row-1][col+1] == color
&& grid[row-2][col+2] == color && grid[row-3][col+3] == 0){
value += 2 * twoSame * diagonal;
}
}
}
/*Now check for 2 in the same diagonal that are arranged like this (\)
* Possible arrangements are:
* X X 0 0 X 0
* X 0 0 X 0 X
* 0 0 X 0 X X
* 0 X X X 0 0*/
for(int row = 0; row <= 2 ; row ++){
for(int col = 0; col <= 3; col ++){
if(grid[row][col] == color && grid[row+1][col+1] == color
&& grid[row+2][col+2] == 0 && grid[row+3][col+3] == 0){
value += twoSame * diagonal;
}
else if(grid[row][col] == color && grid[row+1][col+1] == 0
&& grid[row+2][col+2] == 0 && grid[row+3][col+3] == color){
value += twoSame * diagonal;
}
else if(grid[row][col] == 0 && grid[row+1][col+1] == 0
&& grid[row+2][col+2] == color && grid[row+3][col+3] == color){
value += twoSame * diagonal;
}
else if(grid[row][col] == 0 && grid[row+1][col+1] == color
&& grid[row+2][col+2] == 0 && grid[row+3][col+3] == color){
value += twoSame * diagonal;
}
else if(grid[row][col] == color && grid[row+1][col+1] == 0
&& grid[row+2][col+2] == color && grid[row+3][col+3] == 0){
value += twoSame * diagonal;
}
else if(grid[row][col] == 0 && grid[row+1][col+1] == color
&& grid[row+2][col+2] == color && grid[row+3][col+3] == 0){
value += 2 * twoSame * diagonal;
}
}
}
/*Now check for 3 chips in the same row (horizontal)*/
for (int row=0; row < 6; row++){
for(int col=0; col < 4; col++){
/*(XX0X)*/
if(grid[row][col] == color && grid[row][col+1] == color
&& grid[row][col+2] == 0 && grid[row][col+3] == color)
value += threeSame * horizontal;
/*(X0XX)*/
if(grid[row][col] == color && grid[row][col+1] == 0
&& grid[row][col+2] == color && grid[row][col+3] == color)
value += threeSame * horizontal;
/*(0XXX)*/
if(grid[row][col] == 0 && grid[row][col+1] == color
&& grid[row][col+2] == color && grid[row][col+3] == color)
value += threeSame * horizontal;
/*(XXX0)*/
if(grid[row][col] == color && grid[row][col+1] == color
&& grid[row][col+2] == color && grid[row][col+3] == 0)
value += threeSame * horizontal;
}
}
/*Check for three chips in the same column with an empty space above it
like this:
0
X
X
X
*/
for (int row = 0; row <= 2 ; row ++){
for(int col = 0; col <= 6; col++){
if(grid[row][col] == 0 && grid[row+1][col] == color
&& grid[row+2][col] == color && grid[row+3][col] == color)
value += threeSame * vertical;
}
}
/*Now check for three chips in the same diagonal (/)
* Possible arrangements are:
* 0 X X X
X 0 X X
X X 0 X
X X X 0*/
for (int row=5;row >= 3; row
for(int col=0;col <= 3; col ++ ){
if(grid[row][col] == color && grid[row-1][col+1] == color
&& grid[row-2][col+2] == color && grid[row-3][col+3] == 0){
value += threeSame * diagonal;
}
else if(grid[row][col] == color && grid[row-1][col+1] == color
&& grid[row-2][col+2] == 0 && grid[row-3][col+3] == color){
value += threeSame * diagonal;
}
else if(grid[row][col] == color && grid[row-1][col+1] == 0
&& grid[row-2][col+2] == color && grid[row-3][col+3] == color){
value += threeSame * diagonal;
}
else if(grid[row][col] == 0 && grid[row-1][col+1] == color
&& grid[row-2][col+2] == color && grid[row-3][col+3] == color){
value += threeSame * diagonal;
}
}
}
/*now check again for 3 chips in the same diagonal (\)
* possible arrangements are:
*0 X X X
X 0 X X
X X 0 X
X X X 0*/
for(int row =0;row <=2;row++){
for(int col =0; col <=3; col++){
if(grid[row][col] == 0 && grid[row+1][col+1] == color
&& grid[row+2][col+2] == color && grid[row+3][col+3] == color){
value += threeSame * diagonal;
}
else if(grid[row][col] == color && grid[row+1][col+1] == 0
&& grid[row+2][col+2] == color && grid[row+3][col+3] == color){
value += threeSame * diagonal;
}
else if(grid[row][col] == color && grid[row+1][col+1] == color
&& grid[row+2][col+2] == 0 && grid[row+3][col+3] == color){
value += threeSame * diagonal;
}
else if(grid[row][col] == color && grid[row+1][col+1] == color
&& grid[row+2][col+2] == color && grid[row+3][col+3] == 0){
value += threeSame * diagonal;
}
}
}
return value;
}
}
|
package org.asteriskjava.util;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A ThreadFactory that creates daemon threads for use with an {@link Executor}.
*
* @author srt
* @version $Id$
* @since 0.3
*/
public class DaemonThreadFactory implements ThreadFactory
{
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
/**
* Creates a new instance.
*/
public DaemonThreadFactory() {
namePrefix = "AJ DaemonPool-"+ poolNumber.getAndIncrement() +'.';
}//new
@Override public Thread newThread (Runnable r) {
final Thread thread = new Thread(r);
thread.setDaemon(true);
thread.setName(namePrefix + threadNumber.getAndIncrement());
return thread;
}
}
|
package org.jdesktop.swingx.table;
import java.beans.PropertyChangeEvent;
import java.util.logging.Logger;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.TableColumnModelListener;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import junit.framework.TestCase;
import org.jdesktop.swingx.event.TableColumnModelExtListener;
import org.jdesktop.swingx.util.ColumnModelReport;
/**
* Skeleton to unit test DefaultTableColumnExt.
*
* Incomplete list of issues to test:
* fired added after setVisible(true)
* behaviour when adding/removing invisible columns
* selection state
*
*
* @author Jeanette Winzenburg
*/
public class TableColumnModelTest extends TestCase {
private static final Logger LOG = Logger
.getLogger(TableColumnModelTest.class.getName());
private static final int COLUMN_COUNT = 3;
public void testHideShowColumns() {
DefaultTableColumnModelExt model = (DefaultTableColumnModelExt) createColumnModel(10);
int[] columnsToHide = new int[] { 4, 7, 6, 8, };
for (int i = 0; i < columnsToHide.length; i++) {
model.getColumnExt(String.valueOf(columnsToHide[i])).setVisible(false);
}
// sanity: actually hidden
assertEquals(model.getColumnCount(true) - columnsToHide.length, model.getColumnCount());
for (int i = 0; i < columnsToHide.length; i++) {
model.getColumnExt(String.valueOf(columnsToHide[i])).setVisible(true);
}
// sanity: all visible again
assertEquals(10, model.getColumnCount());
for (int i = 0; i < model.getColumnCount(); i++) {
// the original sequence
assertEquals(i, model.getColumn(i).getModelIndex());
}
}
/**
* test sequence of visible columns after hide/move/show.
*
* Expected behaviour should be like in Thunderbird.
*
*/
public void testMoveColumns() {
DefaultTableColumnModelExt model = (DefaultTableColumnModelExt) createColumnModel(COLUMN_COUNT);
TableColumnExt columnExt = model.getColumnExt(1);
columnExt.setVisible(false);
model.moveColumn(1, 0);
columnExt.setVisible(true);
assertEquals(columnExt.getModelIndex(), model.getColumnExt(2).getModelIndex());
}
/**
* test the columnPropertyChangeEvent is fired as expected.
*
*/
public void testColumnPropertyChangeNotification() {
DefaultTableColumnModelExt model = (DefaultTableColumnModelExt) createColumnModel(COLUMN_COUNT);
ColumnModelReport report = new ColumnModelReport();
model.addColumnModelListener(report);
TableColumn column = model.getColumn(0);
column.setHeaderValue("somevalue");
assertEquals(1, report.getColumnPropertyEventCount());
PropertyChangeEvent event = report.getLastColumnPropertyEvent();
assertEquals(column, event.getSource());
assertEquals("headerValue", event.getPropertyName());
assertEquals("somevalue", event.getNewValue());
}
/**
* added TableColumnModelExtListener: test for add/remove extended listeners.
*
*/
public void testAddExtListener() {
DefaultTableColumnModelExt model = (DefaultTableColumnModelExt) createColumnModel(COLUMN_COUNT);
ColumnModelReport extListener = new ColumnModelReport();
model.addColumnModelListener(extListener);
assertEquals(1, model.getEventListenerList().getListenerCount(TableColumnModelExtListener.class));
assertEquals(2, model.getEventListenerList().getListenerCount());
model.removeColumnModelListener(extListener);
assertEquals(0, model.getEventListenerList().getListenerCount(TableColumnModelExtListener.class));
assertEquals(0, model.getEventListenerList().getListenerCount());
}
/**
* Issue #??-swingx: incorrect isRemovedToInvisible after
* removing an invisible column.
*
*/
public void testRemoveInvisibleColumn() {
DefaultTableColumnModelExt model = (DefaultTableColumnModelExt) createColumnModel(COLUMN_COUNT);
TableColumnExt tableColumnExt = ((TableColumnExt) model.getColumn(0));
tableColumnExt.setVisible(false);
model.removeColumn(tableColumnExt);
assertEquals("visible column count must be reduced", COLUMN_COUNT - 1, model.getColumns(false).size());
assertEquals("all columns count must be unchanged", COLUMN_COUNT - 1, model.getColumns(true).size());
assertFalse("removing invisible must update event cache", model.isRemovedToInvisibleEvent(0));
}
public void testGetColumns() {
TableColumnModelExt model = createColumnModel(COLUMN_COUNT);
((TableColumnExt) model.getColumn(0)).setVisible(false);
assertEquals("visible column count must be reduced", COLUMN_COUNT - 1, model.getColumns(false).size());
assertEquals("all columns count must be unchanged", COLUMN_COUNT, model.getColumns(true).size());
}
/**
* column count must be changed on changing
* column visibility.
*
*/
public void testColumnCountOnSetInvisible() {
TableColumnModel model = createColumnModel(COLUMN_COUNT);
int columnCount = model.getColumnCount();
TableColumnExt column = (TableColumnExt) model.getColumn(columnCount - 1);
assertTrue(column.isVisible());
column.setVisible(false);
assertEquals("columnCount must be decremented", columnCount - 1, model.getColumnCount());
}
/**
* Issue #156: must update internal state after setting invisible.
* Here: the cached totalWidth. Expect similar inconsistency
* with selection.
*
*/
public void testTotalColumnWidth() {
TableColumnModel model = createColumnModel(COLUMN_COUNT);
int totalWidth = model.getTotalColumnWidth();
TableColumnExt column = (TableColumnExt) model.getColumn(0);
int columnWidth = column.getWidth();
column.setVisible(false);
assertEquals("new total width must be old minus invisible column width " + columnWidth,
totalWidth - columnWidth, model.getTotalColumnWidth());
}
/**
* Issue #157: must fire columnRemoved after setting to invisible.
*
*/
public void testRemovedFired() {
TableColumnModel model = createColumnModel(COLUMN_COUNT);
ColumnModelReport l = new ColumnModelReport();
model.addColumnModelListener(l);
TableColumnExt column = (TableColumnExt) model.getColumn(0);
column.setVisible(false);
assertTrue("must have fired columnRemoved", l.hasRemovedEvent());
}
/**
* Issue #157: must fire columnAdded after setting to invisible.
*
*/
public void testAddedFired() {
TableColumnModel model = createColumnModel(COLUMN_COUNT);
ColumnModelReport l = new ColumnModelReport();
TableColumnExt column = (TableColumnExt) model.getColumn(0);
column.setVisible(false);
model.addColumnModelListener(l);
column.setVisible(true);
assertTrue("must have fired columnRemoved", l.hasAddedEvent());
}
/**
* columnAdded: event.getToIndex must be valid columnIndex.
*
*
*/
public void testAddInvisibleColumn() {
TableColumnModel model = createColumnModel(COLUMN_COUNT);
TableColumnModelListener l = new TableColumnModelListener() {
public void columnAdded(TableColumnModelEvent e) {
assertTrue("toIndex must be positive", e.getToIndex() >= 0);
((TableColumnModel) e.getSource()).getColumn(e.getToIndex());
}
public void columnRemoved(TableColumnModelEvent e) {
// TODO Auto-generated method stub
}
public void columnMoved(TableColumnModelEvent e) {
// TODO Auto-generated method stub
}
public void columnMarginChanged(ChangeEvent e) {
// TODO Auto-generated method stub
}
public void columnSelectionChanged(ListSelectionEvent e) {
// TODO Auto-generated method stub
}
};
model.addColumnModelListener(l);
// add invisible column
TableColumnExt invisibleColumn = new TableColumnExt(0);
invisibleColumn.setVisible(false);
model.addColumn(invisibleColumn);
// sanity check: add visible column
model.addColumn(createTableColumnExt(0));
}
/**
* columnAt must work on visible columns.
*
*/
public void testColumnAt() {
TableColumnModel model = createColumnModel(COLUMN_COUNT);
int totalWidth = model.getTotalColumnWidth();
int lastColumn = model.getColumnIndexAtX(totalWidth - 10);
assertEquals("lastColumn detected", model.getColumnCount() - 1, lastColumn);
TableColumnExt column = (TableColumnExt) model.getColumn(lastColumn);
column.setVisible(false);
assertEquals("out of range", -1, model.getColumnIndexAtX(totalWidth - 10));
}
private TableColumnModelExt createColumnModel(int columns) {
TableColumnModelExt model = new DefaultTableColumnModelExt();
for (int i = 0; i < columns; i++) {
model.addColumn(createTableColumnExt(i));
}
return model;
}
private TableColumnExt createTableColumnExt(int modelIndex) {
TableColumnExt column = new TableColumnExt(modelIndex);
column.setIdentifier(String.valueOf(modelIndex));
return column;
}
}
|
package org.cobbzilla.util.reflect;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.MethodUtils;
import org.apache.commons.collections.Transformer;
import org.apache.commons.lang3.ArrayUtils;
import org.cobbzilla.util.string.StringUtil;
import java.io.Closeable;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.reflect.Modifier.isFinal;
import static java.lang.reflect.Modifier.isStatic;
import static org.apache.commons.lang3.reflect.FieldUtils.getAllFields;
import static org.cobbzilla.util.collection.ArrayUtil.arrayToString;
import static org.cobbzilla.util.daemon.ZillaRuntime.*;
import static org.cobbzilla.util.string.StringUtil.uncapitalize;
/**
* Handy tools for working quickly with reflection APIs, which tend to be verbose.
*/
@Slf4j
public class ReflectionUtil {
public static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0];
public static final Class<?>[] SINGLE_STRING_ARG = {String.class};
public static Boolean toBoolean(Object object) {
if (object == null) return null;
if (object instanceof Boolean) return (Boolean) object;
if (object instanceof String) return Boolean.valueOf(object.toString());
return null;
}
public static Boolean toBoolean(Object object, String field, boolean defaultValue) {
final Boolean val = toBoolean(get(object, field));
return val == null ? defaultValue : val;
}
public static Long toLong(Object object) {
if (object == null) return null;
if (object instanceof Number) return ((Number) object).longValue();
if (object instanceof String) return Long.valueOf(object.toString());
return null;
}
public static Integer toInteger(Object object) {
if (object == null) return null;
if (object instanceof Number) return ((Number) object).intValue();
if (object instanceof String) return Integer.valueOf(object.toString());
return null;
}
public static Integer toIntegerOrNull(Object object) {
if (object == null) return null;
if (object instanceof Number) return ((Number) object).intValue();
if (object instanceof String) {
try {
return Integer.valueOf(object.toString());
} catch (Exception e) {
log.info("toIntegerOrNull("+object+"): "+e);
return null;
}
}
return null;
}
public static Short toShort(Object object) {
if (object == null) return null;
if (object instanceof Number) return ((Number) object).shortValue();
if (object instanceof String) return Short.valueOf(object.toString());
return null;
}
public static Float toFloat(Object object) {
if (object == null) return null;
if (object instanceof Number) return ((Number) object).floatValue();
if (object instanceof String) return Float.valueOf(object.toString());
return null;
}
public static Double toDouble(Object object) {
if (object == null) return null;
if (object instanceof Number) return ((Number) object).doubleValue();
if (object instanceof String) return Double.valueOf(object.toString());
return null;
}
public static BigDecimal toBigDecimal(Object object) {
if (object == null) return null;
if (object instanceof Double) return big((Double) object);
if (object instanceof Float) return big((Float) object);
if (object instanceof Number) return big(((Number) object).longValue());
if (object instanceof String) return big(object.toString());
return null;
}
/**
* Do a Class.forName and only throw unchecked exceptions.
* @param clazz full class name. May end in [] to indicate array class
* @param <T> The class type
* @return A Class<clazz> object
*/
public static <T> Class<? extends T> forName(String clazz) {
if (empty(clazz)) return (Class<? extends T>) Object.class;
if (clazz.endsWith("[]")) return arrayClass(forName(clazz.substring(0, clazz.length()-2)));
try {
return (Class<? extends T>) Class.forName(clazz);
} catch (Exception e) {
return die("Class.forName("+clazz+") error: "+e, e);
}
}
public static Collection<Class> forNames(String[] classNames) {
final List<Class> list = new ArrayList<>();
if (!empty(classNames)) for (String c : classNames) list.add(forName(c));
return list;
}
public static <T> Class<? extends T> arrayClass (Class clazz) { return forName("[L"+clazz.getName()+";"); }
/**
* Create an instance of a class, only throwing unchecked exceptions. The class must have a default constructor.
* @param clazz we will instantiate an object of this type
* @param <T> The class type
* @return An Object that is an instance of Class<clazz> object
*/
public static <T> T instantiate(Class<T> clazz) {
try {
return clazz.getDeclaredConstructor().newInstance();
} catch (Exception e) {
return die("Error instantiating "+clazz+": "+e, e);
}
}
/**
* Create an instance of a class based on a class name, only throwing unchecked exceptions. The class must have a default constructor.
* @param clazz full class name
* @param <T> The class type
* @return An Object that is an instance of Class<clazz> object
*/
public static <T> T instantiate(String clazz) {
try {
return (T) instantiate(forName(clazz));
} catch (Exception e) {
return die("instantiate("+clazz+"): "+e, e);
}
}
private static final Map<Class, Map<Object, Enum>> enumCache = new ConcurrentHashMap<>(1000);
/**
* Create an instance of a class using the supplied argument to a matching single-argument constructor.
* @param clazz The class to instantiate
* @param argument The object that will be passed to a matching single-argument constructor
* @param <T> Could be anything
* @return A new instance of clazz, created using a constructor that matched argument's class.
*/
public static <T> T instantiate(Class<T> clazz, Object argument) {
Constructor<T> constructor = null;
Class<?> tryClass = argument.getClass();
if (clazz.isPrimitive()) {
switch (clazz.getName()) {
case "boolean": return (T) Boolean.valueOf(argument.toString());
case "byte": return (T) Byte.valueOf(argument.toString());
case "short": return (T) Short.valueOf(argument.toString());
case "char": return (T) Character.valueOf(empty(argument) ? 0 : argument.toString().charAt(0));
case "int": return (T) Integer.valueOf(argument.toString());
case "long": return (T) Long.valueOf(argument.toString());
case "float": return (T) Float.valueOf(argument.toString());
case "double": return (T) Double.valueOf(argument.toString());
default: return die("instantiate: unrecognized primitive type: "+clazz.getName());
}
}
if (clazz.isEnum()) {
return argument == null ? null : (T) enumCache
.computeIfAbsent(clazz, c -> new ConcurrentHashMap<>(50))
.computeIfAbsent(argument, e -> {
try {
final Method valueOf = clazz.getMethod("valueOf", SINGLE_STRING_ARG);
return (Enum) valueOf.invoke(null, new Object[]{argument.toString()});
} catch (Exception ex) {
return die("instantiate: error instantiating enum "+clazz.getName()+": "+e);
}
});
}
while (constructor == null) {
try {
constructor = clazz.getConstructor(tryClass);
} catch (NoSuchMethodException e) {
if (tryClass.equals(Object.class)) {
// try interfaces
for (Class<?> iface : argument.getClass().getInterfaces()) {
try {
constructor = clazz.getConstructor(iface);
} catch (NoSuchMethodException e2) {
// noop
}
}
break;
} else {
tryClass = tryClass.getSuperclass();
}
}
}
if (constructor == null) {
die("instantiate: no constructor could be found for class "+clazz.getName()+", argument type "+argument.getClass().getName());
}
try {
return constructor.newInstance(argument);
} catch (Exception e) {
return die("instantiate("+clazz.getName()+", "+argument+"): "+e, e);
}
}
/**
* Create an instance of a class using the supplied argument to a matching single-argument constructor.
* @param clazz The class to instantiate
* @param arguments The objects that will be passed to a matching constructor
* @param <T> Could be anything
* @return A new instance of clazz, created using a constructor that matched argument's class.
*/
public static <T> T instantiate(Class<T> clazz, Object... arguments) {
try {
for (Constructor constructor : clazz.getConstructors()) {
final Class<?>[] cParams = constructor.getParameterTypes();
if (cParams.length == arguments.length) {
boolean match = true;
for (int i=0; i<cParams.length; i++) {
if (!cParams[i].isAssignableFrom(arguments[i].getClass())) {
match = false; break;
}
}
if (match) return (T) constructor.newInstance(arguments);
}
}
log.warn("instantiate("+clazz.getName()+"): no matching constructor found, trying with exact match (will probably fail), args="+ArrayUtils.toString(arguments));
final Class<?>[] parameterTypes = new Class[arguments.length];
for (int i=0; i<arguments.length; i++) {
parameterTypes[i] = getSimpleClass(arguments[i]);
}
return clazz.getConstructor(parameterTypes).newInstance(arguments);
} catch (Exception e) {
return die("instantiate("+clazz.getName()+", "+Arrays.toString(arguments)+"): "+e, e);
}
}
public static Class<?> getSimpleClass(Object argument) {
Class<?> argClass = argument.getClass();
final int enhancePos = argClass.getName().indexOf("$$Enhance");
if (enhancePos != -1) {
argClass = forName(argClass.getName().substring(0, enhancePos));
}
return argClass;
}
public static String getSimpleClassName(Object argument) { return getSimpleClass(argument).getClass().getSimpleName(); }
/**
* Make a copy of the object, assuming its class has a copy constructor
* @param thing The thing to copy
* @param <T> Whatevs
* @return A copy of the object, created using the thing's copy constructor
*/
public static <T> T copy(T thing) { return (T) instantiate(thing.getClass(), thing); }
/**
* Mirror the object. Create a new instance and copy all fields
* @param thing The thing to copy
* @param <T> Whatevs
* @return A mirror of the object, created using the thing's default constructor and copying all fields with 'copy'
*/
public static <T> T mirror(T thing) {
T copy = (T) instantiate(thing.getClass());
copy(copy, thing);
return copy;
}
public static Object invokeStatic(Method m, Object... values) {
try {
return m.invoke(null, values);
} catch (Exception e) {
return die("invokeStatic: "+m.getClass().getSimpleName()+"."+m.getName()+"("+arrayToString(values, ", ")+"): "+e, e);
}
}
public static Field getDeclaredField(Class<?> clazz, String field) {
try {
return clazz.getDeclaredField(field);
} catch (NoSuchFieldException e) {
if (clazz.equals(Object.class)) {
log.info("getDeclaredField: field not found "+clazz.getName()+"/"+field);
return null;
}
}
return getDeclaredField(clazz.getSuperclass(), field);
}
public static Field getField(Class<?> clazz, String field) {
try {
return clazz.getField(field);
} catch (NoSuchFieldException e) {
if (clazz.equals(Object.class)) {
log.info("getField: field not found "+clazz.getName()+"/"+field);
return null;
}
}
return getDeclaredField(clazz.getSuperclass(), field);
}
public static <T> Method factoryMethod(Class<T> clazz, Object value) {
// find a static method that takes the value and returns an instance of the class
for (Method m : clazz.getMethods()) {
if (m.getReturnType().equals(clazz)) {
final Class<?>[] parameterTypes = m.getParameterTypes();
if (parameterTypes != null && parameterTypes.length == 1 && parameterTypes[0].isAssignableFrom(value.getClass())) {
return m;
}
}
}
log.warn("factoryMethod: class "+clazz.getName()+" does not have static factory method that takes a String, returning null");
return null;
}
public static <T> T callFactoryMethod(Class<T> clazz, Object value) {
final Method m = factoryMethod(clazz, value);
return m != null ? (T) invokeStatic(m, value) : null;
}
public static Object scrubStrings(Object thing, String[] fields) {
if (empty(thing)) return thing;
if (thing.getClass().isPrimitive()
|| thing instanceof String
|| thing instanceof Number
|| thing instanceof Enum) return thing;
if (thing instanceof JsonNode) {
if (thing instanceof ObjectNode) {
for (String field : fields) {
if (((ObjectNode) thing).has(field)) {
((ObjectNode) thing).remove(field);
}
}
} else if (thing instanceof ArrayNode) {
ArrayNode arrayNode = (ArrayNode) thing;
for (int i = 0; i < arrayNode.size(); i++) {
scrubStrings(arrayNode.get(i), fields);
}
}
} else if (thing instanceof Map) {
final Map map = (Map) thing;
final Set toRemove = new HashSet();
for (Object e : map.entrySet()) {
Map.Entry entry = (Map.Entry) e;
if (ArrayUtils.contains(fields, entry.getKey().toString())) {
toRemove.add(entry.getKey());
} else {
scrubStrings(entry.getValue(), fields);
}
}
for (Object key : toRemove) map.remove(key);
} else if (Object[].class.isAssignableFrom(thing.getClass())) {
if ( !((Object[]) thing)[0].getClass().isPrimitive() ) {
for (Object obj : ((Object[]) thing)) {
scrubStrings(obj, fields);
}
}
} else if (thing instanceof Collection) {
for (Object obj : ((Collection) thing)) {
scrubStrings(obj, fields);
}
} else {
for (String field : ReflectionUtil.toMap(thing).keySet()) {
final Object val = get(thing, field, null);
if (val != null) {
if (ArrayUtils.contains(fields, field)) {
setNull(thing, field, String.class);
} else {
scrubStrings(val, fields);
}
}
}
}
return thing;
}
public static <T extends Annotation> List<String> fieldNamesWithAnnotation(String className, Class<T> aClass) {
return fieldsWithAnnotation(className, aClass).stream().map(Field::getName).collect(Collectors.toList());
}
public static <T extends Annotation> List<Field> fieldsWithAnnotation(String className, Class<T> aClass) {
final Set<Field> matches = new LinkedHashSet<>();
Class c = forName(className);
while (!c.equals(Object.class)) {
for (Field f : getAllFields(c)) {
if (f.getAnnotation(aClass) != null) matches.add(f);
}
c = c.getSuperclass();
}
return new ArrayList<>(matches);
}
private enum Accessor { get, set }
/**
* Copies fields from src to dest. Code is easier to read if this method is understdood to be like an assignment statement, dest = src
*
* We consider only 'getter' methods that meet the following criteria:
* (1) starts with "get"
* (2) takes zero arguments
* (3) has a return value
* (4) does not carry any annotation whose simple class name is "Transient"
*
* The value returned from the source getter will be copied to the destination (via setter), if a setter exists, and:
* (1) No getter exists on the destination, or (2) the destination's getter returns a different value (.equals returns false)
*
* Getters that return null values on the source object will not be copied.
*
* @param dest destination object
* @param src source object
* @param <T> objects must share a type
* @return count of fields copied
*/
public static <T> int copy (T dest, T src) {
return copy(dest, src, null, null);
}
/**
* Same as copy(dest, src) but only named fields are copied
* @param dest destination object
* @param src source object
* @param fields only fields with these names will be considered for copying
* @param <T> objects must share a type
* @return count of fields copied
*/
public static <T> int copy (T dest, T src, String[] fields) {
int copyCount = 0;
if (fields != null) {
for (String field : fields) {
try {
final Object value = get(src, field, null);
if (value != null) {
set(dest, field, value);
copyCount++;
}
} catch (Exception e) {
log.debug("copy: field=" + field + ": " + e);
}
}
}
return copyCount;
}
/**
* Same as copy(dest, src) but only named fields are copied
* @param dest destination object, or a Map<String, Object>
* @param src source object
* @param fields only fields with these names will be considered for copying
* @param exclude fields with these names will NOT be considered for copying
* @param <T> objects must share a type
* @return count of fields copied
*/
public static <T> int copy (T dest, T src, String[] fields, String[] exclude) {
int copyCount = 0;
final boolean isMap = dest instanceof Map;
try {
if (src instanceof Map) copyFromMap(dest, (Map<String, Object>) src, exclude);
checkGetter:
for (Method getter : src.getClass().getMethods()) {
// only look for getters on the source object (methods with no arguments that have a return value)
final Class<?>[] types = getter.getParameterTypes();
if (types.length != 0) continue;
if (getter.getReturnType().equals(Void.class)) continue;;
// and it must be named appropriately
final String fieldName = fieldName(getter.getName());
if (fieldName == null || ArrayUtils.contains(exclude, fieldName)) continue;
// if specific fields were given, it must be one of those
if (fields != null && !ArrayUtils.contains(fields, fieldName)) continue;
// getter must not be marked @Transient
if (isIgnored(src, fieldName, getter)) continue;
// what would the setter be called?
final String setterName = setterForGetter(getter.getName());
if (setterName == null) continue;
// get the setter method on the destination object
Method setter = null;
if (!isMap) {
try {
setter = dest.getClass().getMethod(setterName, getter.getReturnType());
} catch (Exception e) {
log.debug("copy: setter not found: " + setterName);
continue;
}
}
// do not copy null fields (should this be configurable?)
final Object srcValue = getter.invoke(src);
if (srcValue == null) continue;
// does the dest have a getter? if so grab the current value
Object destValue = null;
try {
if (isMap) {
destValue = ((Map) dest).get(fieldName);
} else {
destValue = getter.invoke(dest);
}
} catch (Exception e) {
log.debug("copy: error calling getter on dest: "+e);
}
// copy the value from src to dest, if it's different
if (!srcValue.equals(destValue)) {
if (isMap) {
((Map) dest).put(fieldName, srcValue);
} else {
setter.invoke(dest, srcValue);
}
copyCount++;
}
}
} catch (Exception e) {
throw new IllegalArgumentException("Error copying "+dest.getClass().getSimpleName()+" from src="+src+": "+e, e);
}
return copyCount;
}
private static <T> boolean isIgnored(T o, String fieldName, Method getter) {
Field field = null;
try {
field = o.getClass().getDeclaredField(fieldName);
} catch (NoSuchFieldException ignored) {}
return isIgnored(getter.getAnnotations()) || (field != null && isIgnored(field.getAnnotations()));
}
private static boolean isIgnored(Annotation[] annotations) {
if (annotations != null) {
for (Annotation a : annotations) {
final Class<?>[] interfaces = a.getClass().getInterfaces();
if (interfaces != null) {
for (Class<?> i : interfaces) {
if (i.getSimpleName().equals("Transient")) {
return true;
}
}
}
}
}
return false;
}
public static String fieldName(String method) {
if (method.startsWith("get")) return uncapitalize(method.substring(3));
if (method.startsWith("set")) return uncapitalize(method.substring(3));
if (method.startsWith("is")) return uncapitalize(method.substring(2));
return null;
}
public static String setterForGetter(String getter) {
if (getter.startsWith("get")) return "set"+getter.substring(3);
if (getter.startsWith("is")) return "set"+getter.substring(2);
return null;
}
/**
* Call setters on an object based on keys and values in a Map
* @param dest destination object
* @param src map of field name -> value
* @param <T> type of object
* @return the destination object
*/
public static <T> T copyFromMap (T dest, Map<String, Object> src) {
return copyFromMap(dest, src, null);
}
public static <T> T copyFromMap (T dest, Map<String, Object> src, String[] exclude) {
for (Map.Entry<String, Object> entry : src.entrySet()) {
final String key = entry.getKey();
if (exclude != null && ArrayUtils.contains(exclude, key)) continue;
final Object value = entry.getValue();
if (value != null && Map.class.isAssignableFrom(value.getClass())) {
if (hasGetter(dest, key)) {
Map m = (Map) value;
if (m.isEmpty()) continue;
if (m.keySet().iterator().next().getClass().equals(String.class)) {
copyFromMap(get(dest, key), (Map<String, Object>) m);
} else {
log.info("copyFromMap: not recursively copying Map (has non-String keys): " + key);
}
}
} else {
if (Map.class.isAssignableFrom(dest.getClass())) {// || dest.getClass().getName().equals(HashMap.class.getName())) {
((Map) dest).put(key, value);
} else {
if (hasSetter(dest, key, value.getClass())) {
set(dest, key, value);
} else {
final Class pc = getPrimitiveClass(value.getClass());
if (pc != null && hasSetter(dest, key, pc)) {
set(dest, key, value);
} else {
log.info("copyFromMap: skipping uncopyable property: "+key);
}
}
}
}
}
return dest;
}
public static Class getPrimitiveClass(Class<?> clazz) {
if (clazz.isArray()) return arrayClass(getPrimitiveClass(clazz.getComponentType()));
switch (clazz.getSimpleName()) {
case "Long": return long.class;
case "Integer": return int.class;
case "Short": return short.class;
case "Double": return double.class;
case "Float": return float.class;
case "Boolean": return boolean.class;
case "Character": return char.class;
default: return null;
}
}
public static final String[] TO_MAP_STANDARD_EXCLUDES = {"declaringClass", "class"};
/**
* Make a copy of the object, assuming its class has a copy constructor
* @param thing The thing to copy
* @return A copy of the object, created using the thing's copy constructor
*/
public static Map<String, Object> toMap(Object thing) { return toMap(thing, null, TO_MAP_STANDARD_EXCLUDES); }
public static Map<String, Object> toMap(Object thing, String[] fields) { return toMap(thing, fields, TO_MAP_STANDARD_EXCLUDES); }
public static Map<String, Object> toMap(Object thing, String[] fields, String[] exclude) {
final Map<String, Object> map = new HashMap<>();
copy(map, thing, fields, exclude);
return map;
}
/**
* Find the concrete class for the first declared parameterized class variable
* @param clazz The class to search for parameterized types
* @return The first concrete class for a parameterized type found in clazz
*/
public static <T> Class<T> getFirstTypeParam(Class clazz) { return getTypeParam(clazz, 0); }
public static <T> Class<T> getTypeParam(Class clazz, int index) {
// todo: add a cache on this thing... could do wonders
Class check = clazz;
while (check.getGenericSuperclass() == null || !(check.getGenericSuperclass() instanceof ParameterizedType)) {
check = check.getSuperclass();
if (check.equals(Object.class)) die("getTypeParam("+clazz.getName()+"): no type parameters found");
}
final ParameterizedType parameterizedType = (ParameterizedType) check.getGenericSuperclass();
final Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
if (index >= actualTypeArguments.length) die("getTypeParam("+clazz.getName()+"): "+actualTypeArguments.length+" type parameters found, index "+index+" out of bounds");
if (actualTypeArguments[index] instanceof Class) return (Class) actualTypeArguments[index];
if (actualTypeArguments[index] instanceof ParameterizedType) return (Class) ((ParameterizedType) actualTypeArguments[index]).getRawType();
return (Class<T>) ((Type) actualTypeArguments[index]).getClass();
}
/**
* Find the concrete class for a parameterized class variable.
* @param clazz The class to start searching. Search will continue up through superclasses
* @param impl The type (or a supertype) of the parameterized class variable
* @return The first concrete class found that is assignable to an instance of impl
*/
public static <T> Class<T> getFirstTypeParam(Class clazz, Class impl) {
// todo: add a cache on this thing... could do wonders
Class check = clazz;
while (check != null && !check.equals(Object.class)) {
Class superCheck = check;
Type superType = superCheck.getGenericSuperclass();
while (superType != null && !superType.equals(Object.class)) {
if (superType instanceof ParameterizedType) {
final ParameterizedType ptype = (ParameterizedType) superType;
final Class<?> rawType = (Class<?>) ptype.getRawType();
if (impl.isAssignableFrom(rawType)) {
return (Class<T>) rawType;
}
for (Type t : ptype.getActualTypeArguments()) {
if (impl.isAssignableFrom((Class<?>) t)) {
return (Class<T>) t;
}
}
} else if (superType instanceof Class) {
superType = ((Class) superType).getGenericSuperclass();
}
}
check = check.getSuperclass();
}
return null;
}
public static Object get(Object object, String field) {
Object target = object;
for (String token : field.split("\\.")) {
if (target == null) return null;
target = invoke_get(target, token);
}
return target;
}
public static <T> T get(Object object, String field, T defaultValue) {
try {
final Object val = get(object, field);
return val == null ? defaultValue : (T) val;
} catch (Exception e) {
log.warn("get: "+e);
return defaultValue;
}
}
public static boolean isGetter(Method method) {
return method.getName().startsWith("get") || method.getName().startsWith("is") && method.getParameters().length == 0;
}
public static boolean hasGetter(Object object, String field) {
Object target = object;
try {
for (String token : field.split("\\.")) {
final String methodName = getAccessorMethodName(Accessor.get, token);
target = MethodUtils.invokeExactMethod(target, methodName, null);
}
} catch (NoSuchMethodException e) {
return false;
} catch (Exception e) {
return false;
}
return true;
}
public static Class getterType(Object object, String field) {
try {
final Object o = get(object, field);
if (o == null) return die("getterType: cannot determine field type, value was null");
return o.getClass();
} catch (Exception e) {
return die("getterType: simple get failed: "+e, e);
}
}
/**
* Call a setter
* @param object the object to call set(field) on
* @param field the field name
* @param value the value to set
*/
public static void set(Object object, String field, Object value) {
set(object, field, value, value == null ? null : value.getClass());
}
/**
* Call a setter with a hint as to what the type should be
* @param object the object to call set(field) on
* @param field the field name
* @param value the value to set
* @param type type of the field
*/
public static void set(Object object, String field, Object value, Class<?> type) {
if (type != null) {
if (value == null) {
setNull(object, field, type);
return;
} else if (!type.isAssignableFrom(value.getClass())) {
// if value is not assignable to type, then the type class should have a constructor for the value class
value = instantiate(type, value);
}
}
final String[] tokens = field.split("\\.");
Object target = getTarget(object, tokens);
if (target != null) invoke_set(target, tokens[tokens.length - 1], value);
}
public static void setNull(Object object, String field, Class type) {
final String[] tokens = field.split("\\.");
Object target = getTarget(object, tokens);
if (target != null) invoke_set_null(target, tokens[tokens.length - 1], type);
}
private static Object getTarget(Object object, String[] tokens) {
Object target = object;
for (int i=0; i<tokens.length-1; i++) {
target = invoke_get(target, tokens[i]);
if (target == null) {
log.warn("getTarget("+object+", "+Arrays.toString(tokens)+"): exiting early, null object found at token="+tokens[i]);
return null;
}
}
return target;
}
public static boolean hasSetter(Object object, String field, Class type) {
Object target = object;
final String[] tokens = field.split("\\.");
try {
for (int i=0; i<tokens.length-1; i++) {
target = MethodUtils.invokeExactMethod(target, tokens[i], null);
}
target.getClass().getMethod(getAccessorMethodName(Accessor.set, tokens[tokens.length-1]), type);
} catch (NoSuchMethodException e) {
return false;
} catch (Exception e) {
return false;
}
return true;
}
private static String getAccessorMethodName(Accessor accessor, String token) {
return token.length() == 1 ? accessor.name() +token.toUpperCase() : accessor.name() + token.substring(0, 1).toUpperCase() + token.substring(1);
}
private static Object invoke_get(Object target, String token) {
final String methodName = getAccessorMethodName(Accessor.get, token);
try {
target = MethodUtils.invokeMethod(target, methodName, null);
} catch (Exception e) {
final String isMethod = methodName.replaceFirst("get", "is");
try {
target = MethodUtils.invokeMethod(target, isMethod, null);
} catch (Exception e2) {
if (target instanceof Map) return ((Map) target).get(token);
if (target instanceof ObjectNode) return ((ObjectNode) target).get(token);
throw new IllegalArgumentException("Error calling "+methodName+" and "+isMethod+": "+e+", "+e2);
}
}
return target;
}
private static Map<String, Method> setterCache = new ConcurrentHashMap<>(5000);
private static Map<Class, Object[]> nullArgCache = new ConcurrentHashMap<>(5000);
private static void invoke_set(Object target, String token, Object value) {
final String cacheKey = target.getClass().getName()+"."+token+"."+(value == null ? "null" : value.getClass().getName());
final Method method = setterCache.computeIfAbsent(cacheKey, s -> {
final String methodName = getAccessorMethodName(Accessor.set, token);
Method found = null;
if (value == null) {
// try to find a single-arg method named methodName...
for (Method m : target.getClass().getMethods()) {
if (m.getName().equals(methodName) && m.getParameterTypes().length == 1) {
if (found != null) {
return die("invoke_set: value was null and multiple single-arg methods named " + methodName + " exist");
} else {
found = m;
}
}
}
} else {
try {
found = MethodUtils.getMatchingAccessibleMethod(target.getClass(), methodName, new Class<?>[]{value.getClass()});
} catch (Exception e) {
return die("Error calling " + methodName + ": " + e);
}
}
return found != null ? found : die("invoke_set: no method " + methodName + " found on target: " + target);
});
if (value == null) {
try {
final Object[] nullArg = nullArgCache.computeIfAbsent(method.getParameterTypes()[0], type -> new Object[] {getNullArgument(type)});
method.invoke(target, nullArg);
} catch (Exception e) {
die("Error calling " + method.getName() + " on target: " + target + " - " + e);
}
} else {
try {
MethodUtils.invokeMethod(target, method.getName(), value);
} catch (Exception e) {
die("Error calling " + method.getName() + ": " + e);
}
}
}
private static void invoke_set_null(Object target, String token, Class type) {
final String methodName = getAccessorMethodName(Accessor.set, token);
try {
MethodUtils.invokeMethod(target, methodName, new Object[] {getNullArgument(type)}, new Class[] { type });
} catch (Exception e) {
die("Error calling "+methodName+": "+e);
}
}
private static Object getNullArgument(Class clazz) {
if (clazz.isPrimitive()) {
switch (clazz.getName()) {
case "boolean": return false;
case "byte": return (byte) 0;
case "short": return (short) 0;
case "char": return (char) 0;
case "int": return (int) 0;
case "long": return (long) 0;
case "float": return (float) 0;
case "double": return (double) 0;
default: return die("instantiate: unrecognized primitive type: "+clazz.getName());
}
}
return null;
}
/**
* Finds the type parameter for the given class.
*
* @param klass a parameterized class
* @return the class's type parameter
*/
public static Class<?> getTypeParameter(Class<?> klass) {
return getTypeParameter(klass, Object.class);
}
/**
* Finds the type parameter for the given class which is assignable to the bound class.
*
* @param klass a parameterized class
* @param bound the type bound
* @param <T> the type bound
* @return the class's type parameter
*/
@SuppressWarnings("unchecked")
public static <T> Class<T> getTypeParameter(Class<?> klass, Class<? super T> bound) {
Type t = checkNotNull(klass);
while (t instanceof Class<?>) {
t = ((Class<?>) t).getGenericSuperclass();
}
/* This is not guaranteed to work for all cases with convoluted piping
* of type parameters: but it can at least resolve straight-forward
* extension with single type parameter (as per [Issue-89]).
* And when it fails to do that, will indicate with specific exception.
*/
if (t instanceof ParameterizedType) {
// should typically have one of type parameters (first one) that matches:
for (Type param : ((ParameterizedType) t).getActualTypeArguments()) {
if (param instanceof Class<?>) {
final Class<T> cls = determineClass(bound, param);
if (cls != null) { return cls; }
}
else if (param instanceof TypeVariable) {
for (Type paramBound : ((TypeVariable<?>) param).getBounds()) {
if (paramBound instanceof Class<?>) {
final Class<T> cls = determineClass(bound, paramBound);
if (cls != null) { return cls; }
}
}
}
}
}
return die("Cannot figure out type parameterization for " + klass.getName());
}
@SuppressWarnings("unchecked")
private static <T> Class<T> determineClass(Class<? super T> bound, Type candidate) {
if (candidate instanceof Class<?>) {
final Class<?> cls = (Class<?>) candidate;
if (bound.isAssignableFrom(cls)) {
return (Class<T>) cls;
}
}
return null;
}
public static void close(Object o) throws Exception {
if (o == null) return;
if (o instanceof Closeable) {
((Closeable) o).close();
} else {
final Method closeMethod = o.getClass().getMethod("close", (Class<?>[]) null);
if (closeMethod == null) die("no close method found on " + o.getClass().getName());
closeMethod.invoke(o);
}
}
public static void closeQuietly(Object o) {
if (o == null) return;
try {
close(o);
} catch (Exception e) {
log.warn("close: error closing: "+e);
}
}
@NoArgsConstructor @AllArgsConstructor
public static class Setter<T> {
@Getter protected String field;
@Getter protected String value;
public void set(T data) { ReflectionUtil.set(data, field, value); }
@Override public String toString() { return getClass().getName() + '{' + field + ", " + value + '}'; }
}
private static class CallerInspector extends SecurityManager {
public String getCallerClassName() { return getClassContext()[2].getName(); }
public String getCallerClassName(int depth) { return getClassContext()[depth].getName(); }
}
private final static CallerInspector callerInspector = new CallerInspector();
public static String callerClassName() { return callerInspector.getCallerClassName(); }
public static String callerClassName(int depth) { return callerInspector.getCallerClassName(depth); }
public static String callerClassName(String match) {
final StackTraceElement s = callerFrame(match);
return s == null ? "callerClassName: no match: "+match : s.getMethodName();
}
public static String callerMethodName() { return new Throwable().getStackTrace()[2].getMethodName(); }
public static String callerMethodName(int depth) { return new Throwable().getStackTrace()[depth].getMethodName(); }
public static String callerMethodName(String match) {
final StackTraceElement s = callerFrame(match);
return s == null ? "callerMethodName: no match: "+match : s.getMethodName();
}
public static String caller () {
final StackTraceElement[] t = new Throwable().getStackTrace();
if (t == null || t.length == 0) return "caller: NO STACK TRACE!";
return caller(t[Math.max(t.length-1, 2)]);
}
public static String caller (int depth) {
final StackTraceElement[] t = new Throwable().getStackTrace();
if (t == null || t.length == 0) return "caller: NO STACK TRACE!";
return caller(t[Math.min(depth, t.length-1)]);
}
public static String caller(String match) {
final StackTraceElement s = callerFrame(match);
return s == null ? "caller: no match: "+match : caller(s);
}
public static StackTraceElement callerFrame(String match) {
final StackTraceElement[] t = new Throwable().getStackTrace();
if (t == null || t.length == 0) return null;
for (StackTraceElement s : t) if (caller(s).contains(match)) return s;
return null;
}
public static String caller(StackTraceElement s) { return s.getClassName() + "." + s.getMethodName() + ":" + s.getLineNumber(); }
/**
* Replace any string values with their transformed values
* @param map a map of things
* @param transformer a transformer
* @return the same map, but if any value was a string, the transformer has been applied to it.
*/
public static Map transformStrings(Map map, Transformer transformer) {
if (empty(map)) return map;
final Map setOps = new HashMap();
for (Object entry : map.entrySet()) {
final Map.Entry e = (Map.Entry) entry;
if (e.getValue() instanceof String) {
setOps.put(e.getKey(), transformer.transform(e.getValue()).toString());
} else if (e.getValue() instanceof Map) {
setOps.put(e.getKey(), transformStrings((Map) e.getValue(), transformer));
}
}
for (Object entry : setOps.entrySet()) {
final Map.Entry e = (Map.Entry) entry;
map.put(e.getKey(), e.getValue());
}
return map;
}
public static boolean isStaticFinalString(Field f) { return isStaticFinal(f, String.class, StringUtil.EMPTY); }
public static boolean isStaticFinalString(Field f, String prefix) { return isStaticFinal(f, String.class, prefix); }
public static boolean isStaticFinal(Field f, Class type) { return isStaticFinal(f, type, StringUtil.EMPTY); }
public static boolean isStaticFinal(Field f, Class type, String prefix) {
final int mods = f.getModifiers();
return isStatic(mods) && isFinal(mods) && type.isAssignableFrom(f.getType()) && f.getName().startsWith(prefix);
}
public static <T> T constValue(Field f) {
try {
return (T) f.get(null);
} catch (Exception e) {
return die("constValue: "+e);
}
}
}
|
package tk.genesishub.gFeatures.GenesisEconomy;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.entity.Player;
public class MoneyManager {
Connection c = new Connection();
CheckConfig cc = new CheckConfig();
String Address = cc.getAddress();
String Port = cc.getPort();
String Tablename = cc.getTablename();
String Username = cc.getUsername();
String Password = cc.getPassword();
String URL = c.toURL(Port, Address, Tablename);
public float getMoney(Player p){
List<String> rs = new ArrayList<>();
rs = c.ConnectReturn(URL, Username, Password, "SELECT Name, Money FROM People WHERE Name = '" + p.getUniqueId().toString() + "'");
return Float.parseFloat(rs.get(2));
}
public void giveMoney(Player p, float amount){
List<String> rs = new ArrayList<>();
rs = c.ConnectReturn(URL, Username, Password, "SELECT Name, Money FROM People WHERE Name = '" + p.getUniqueId().toString() + "'");
float num = Float.parseFloat(rs.get(2));
float money = num + amount;
rs = c.ConnectReturn(URL, Username, Password, "UPDATE People SET Money WHERE Name = '"+ p.getUniqueId().toString() +"'");
}
public void takeMoney(Player p, double amount){
}
}
|
package com.kylemsguy.tcasmobile.backend;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MessageManager {
private static final String MESSAGES_URL = SessionManager.BASE_URL + "messages/";
private static final String COMPOSE_URL = MESSAGES_URL + "compose/";
private static final String RECIPIENTS_KEY = "to";
private static final String TITLE_KEY = "title";
private static final String CONTENT_KEY = "body";
private static final String USER_NAME = "You";
private SessionManager sm;
private List<MessageThread> threads;
public MessageManager(SessionManager sm) {
this.sm = sm;
threads = new ArrayList<>();
}
/**
* Returns a shallow copy of the thread list
*
* @return threads list
*/
public List<MessageThread> getThreadList() {
return threads;
}
/**
* Returns an immutable list containing all the message threads.
*
* @return Immutable list of message threads
*/
public List<MessageThread> getThreads() {
return Collections.unmodifiableList(threads);
}
/**
* Creates a new message thread
*
* @param title Title of the thread
* @param users recipients, excluding the current user
* @param firstMessage First message sent to all recipients
*/
public void newThread(String title, List<String> users, String firstMessage) throws Exception {
int id = 0;
id = submitNewThread(users, title, firstMessage);
// TODO Only temporarily keeping try-catch block. Delete when we are done.
/* if(e instanceof NoSuchUserException){
throw new NoSuchUserException(e);
} else {
throw e;
}*/
Message message = new Message(id, USER_NAME, firstMessage, 0.0);
MessageThread thread = new MessageThread(id, title, users, message);
threads.add(thread);
}
private int submitNewThread(List<String> recipients, String title, String firstMessage) throws Exception {
SessionManager.GetRequestBuilder rb = new SessionManager.GetRequestBuilder();
StringBuilder sb = new StringBuilder();
for (String user : recipients) {
sb.append(user);
sb.append(",");
}
sb.setLength(sb.length() - 1);
rb.addParam(RECIPIENTS_KEY, sb.toString());
rb.addParam(TITLE_KEY, title);
rb.addParam(CONTENT_KEY, firstMessage);
String response = sm.sendPost(COMPOSE_URL, rb.toString());
Document dom = Jsoup.parse(response);
// TODO replace by getting an id!!! THIS IS TEMPORARY ONLY!!!
// the following is temporary. When a proper API is released rewrite this.
if (dom.getElementsByTag("title").text().equals("Two Cans and String : Messages in Inbox")) {
// success. get ID.
// TODO THIS IS TEMPORARY!!!!!!!!!!
Elements elements = dom.getElementsByAttribute("href");
for (Element e : elements) {
if (e.text().equals(title)) {
String url = e.attr("href");
String[] splitUrl = url.split("/");
String id = splitUrl[splitUrl.length - 1];
return Integer.parseInt(id);
}
}
return 0;
}
Elements elements = dom.getElementsByAttributeValue("style", "color:#f00;");
for (Element e : elements) {
if (e.text().matches("No registered user by the name of:"))
throw new NoSuchUserException(e.text());
}
throw new Exception("An unknown error occurred.");
}
/**
* Adds a thread to the list of threads
*
* @param thread the thread to be added
*/
private void addThread(MessageThread thread) {
threads.add(thread);
}
public static class NoSuchUserException extends Exception {
/**
* Constructs a new {@code Exception} that includes the current stack trace.
*/
public NoSuchUserException() {
}
/**
* Constructs a new {@code Exception} with the current stack trace and the
* specified detail message.
*
* @param detailMessage the detail message for this exception.
*/
public NoSuchUserException(String detailMessage) {
super(detailMessage);
}
/**
* Constructs a new {@code Exception} with the current stack trace, the
* specified detail message and the specified cause.
*
* @param detailMessage the detail message for this exception.
* @param throwable
*/
public NoSuchUserException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
}
/**
* Constructs a new {@code Exception} with the current stack trace and the
* specified cause.
*
* @param throwable the cause of this exception.
*/
public NoSuchUserException(Throwable throwable) {
super(throwable);
}
}
}
|
package org.deepsymmetry.beatlink.data;
import org.deepsymmetry.beatlink.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
/**
* <p>Watches the beat packets and transport information contained in player status update to infer the current
* track playback position based on the most recent information available, the time at which that was
* received, and the playback pitch and direction that was in effect at that time.</p>
*
* <p>Can only operate properly when track metadata and beat grids are available, as these are necessary to
* convert beat numbers into track positions.</p>
*
* @author James Elliott
*/
public class TimeFinder extends LifecycleParticipant {
private static final Logger logger = LoggerFactory.getLogger(TimeFinder.class);
/**
* Keeps track of the latest position information we have from each player, indexed by player number.
*/
private final ConcurrentHashMap<Integer, TrackPositionUpdate> positions = new ConcurrentHashMap<Integer, TrackPositionUpdate>();
/**
* Keeps track of the latest device update reported by each player, indexed by player number.
*/
private final ConcurrentHashMap<Integer, DeviceUpdate> updates = new ConcurrentHashMap<Integer, DeviceUpdate>();
/**
* Our announcement listener watches for devices to disappear from the network so we can discard all information
* about them.
*/
private final DeviceAnnouncementListener announcementListener = new DeviceAnnouncementListener() {
@Override
public void deviceFound(final DeviceAnnouncement announcement) {
logger.debug("Currently nothing for TimeFinder to do when devices appear.");
}
@Override
public void deviceLost(DeviceAnnouncement announcement) {
logger.info("Clearing position information in response to the loss of a device, {}", announcement);
positions.remove(announcement.getNumber());
updates.remove(announcement.getNumber());
}
};
/**
* Keep track of whether we are running
*/
private final AtomicBoolean running = new AtomicBoolean(false);
/**
* Check whether we are currently running.
*
* @return true if track playback positions are being kept track of for all active players
*/
public boolean isRunning() {
return running.get();
}
@SuppressWarnings("WeakerAccess")
public Map<Integer, TrackPositionUpdate> getLatestPositions() {
ensureRunning();
return Collections.unmodifiableMap(new HashMap<Integer, TrackPositionUpdate>(positions));
}
/**
* Get the latest device updates (either beats or status updates) available for all visible players.
*
* @return the latest beat or status update, whichever was more recent, for each current player
*/
public Map<Integer, DeviceUpdate> getLatestUpdates() {
ensureRunning();
return Collections.unmodifiableMap(new HashMap<Integer, DeviceUpdate>(updates));
}
public TrackPositionUpdate getLatestPositionFor(int player) {
ensureRunning();
return positions.get(player);
}
public TrackPositionUpdate getLatestPositionFor(DeviceUpdate update) {
return getLatestPositionFor(update.getDeviceNumber());
}
public DeviceUpdate getLatestUpdateFor(int player) {
ensureRunning();
return updates.get(player);
}
/**
* Figure out, based on how much time has elapsed since we received an update, and the playback position,
* speed, and direction at the time of that update, where the player will be now.
*
* @param update the most recent update received from a player
* @param currentTimestamp the nanosecond timestamp representing when we want to interpolate the track's position
*
* @return the playback position we believe that player has reached now
*/
private long interpolateTimeSinceUpdate(TrackPositionUpdate update, long currentTimestamp) {
if (!update.playing) {
return update.milliseconds;
}
long elapsedMillis = (currentTimestamp - update.timestamp) / 1000000;
long moved = Math.round(update.pitch * elapsedMillis);
if (update.reverse) {
return update.milliseconds - moved;
}
return update.milliseconds + moved;
}
/**
* Checks whether a CDJ status update seems to be close enough to a cue that if we just jumped there (or just
* loaded the track) it would be a reasonable assumption that we jumped to the cue.
*
* @param update the status update to check for proximity to hot cues and memory points
* @param beatGrid the beat grid of the track being played
* @return a matching memory point if we had a cue list available and were within a beat of one, or {@code null}
*/
private CueList.Entry findAdjacentCue(CdjStatus update, BeatGrid beatGrid) {
if (!MetadataFinder.getInstance().isRunning()) return null;
final TrackMetadata metadata = MetadataFinder.getInstance().getLatestMetadataFor(update);
final int newBeat = update.getBeatNumber();
if (metadata != null && metadata.getCueList() != null) {
for (CueList.Entry entry : metadata.getCueList().entries) {
final int entryBeat = beatGrid.findBeatAtTime(entry.cueTime);
if (Math.abs(newBeat - entryBeat) < 2) {
return entry; // We have found a cue we likely jumped to
}
if (entryBeat > newBeat) {
break; // We have moved past our location, no point scanning further.
}
}
}
return null;
}
/**
* Sanity-check a new non-beat update, make sure we are still interpolating a sensible position, and correct
* as needed.
*
* @param lastTrackUpdate the most recent digested update received from a player
* @param newDeviceUpdate a new status update from the player
* @param beatGrid the beat grid for the track that is playing, in case we have jumped
*
* @return the playback position we believe that player has reached at that point in time
*/
private long interpolateTimeFromUpdate(TrackPositionUpdate lastTrackUpdate, CdjStatus newDeviceUpdate,
BeatGrid beatGrid) {
final int beatNumber = newDeviceUpdate.getBeatNumber();
final boolean noLongerPlaying = !newDeviceUpdate.isPlaying();
// If we have just stopped, see if we are near a cue (assuming that information is available), and if so,
// the best assumption is that the DJ jumped to that cue.
if (lastTrackUpdate.playing && noLongerPlaying) {
final CueList.Entry jumpedTo = findAdjacentCue(newDeviceUpdate, beatGrid);
if (jumpedTo != null) return jumpedTo.cueTime;
}
// Handle the special case where we were not playing either in the previous or current update, but the DJ
// might have jumped to a different place in the track.
if (!lastTrackUpdate.playing) {
if (lastTrackUpdate.beatNumber == beatNumber && noLongerPlaying) { // Haven't moved
return lastTrackUpdate.milliseconds;
} else {
if (noLongerPlaying) { // Have jumped without playing.
if (beatNumber < 0) {
return -1; // We don't know the position any more; weird to get into this state and still have a grid?
}
// As a heuristic, assume we are right before the beat?
return timeOfBeat(beatGrid, beatNumber, newDeviceUpdate);
}
}
}
// One way or another, we are now playing.
long elapsedMillis = (newDeviceUpdate.getTimestamp() - lastTrackUpdate.timestamp) / 1000000;
long moved = Math.round(lastTrackUpdate.pitch * elapsedMillis);
long interpolated = (lastTrackUpdate.reverse)?
(lastTrackUpdate.milliseconds - moved) : lastTrackUpdate.milliseconds + moved;
if (Math.abs(beatGrid.findBeatAtTime(interpolated) - beatNumber) < 2) {
return interpolated; // Our calculations still look plausible
}
// The player has jumped or drifted somewhere unexpected, correct.
if (newDeviceUpdate.isPlayingForwards()) {
return timeOfBeat(beatGrid, beatNumber, newDeviceUpdate);
} else {
return beatGrid.getTimeWithinTrack(Math.min(beatNumber + 1, beatGrid.beatCount));
}
}
public long getTimeFor(int player) {
TrackPositionUpdate update = positions.get(player);
if (update != null) {
return interpolateTimeSinceUpdate(update, System.nanoTime());
}
return -1; // We don't know.
}
public long getTimeFor(DeviceUpdate update) {
return getTimeFor(update.getDeviceNumber());
}
/**
* Keeps track of the listeners that have registered interest in closely following track playback for a particular
* player. The keys are the listener interface, and the values are the last update that was sent to that
* listener.
*/
private final ConcurrentHashMap<TrackPositionListener, TrackPositionUpdate> trackPositionListeners =
new ConcurrentHashMap<TrackPositionListener, TrackPositionUpdate>();
/**
* Keeps track of the player numbers that registered track position listeners are interested in.
*/
private final ConcurrentHashMap<TrackPositionListener, Integer> listenerPlayerNumbers =
new ConcurrentHashMap<TrackPositionListener, Integer>();
/**
* This is used to represent the fact that we have told a listener that there is no information for it, since
* we can't actually store a {@code null} value in a {@link ConcurrentHashMap}.
*/
private final TrackPositionUpdate NO_INFORMATION = new TrackPositionUpdate(0, 0, 0,
false, false, 0, false, null);
/**
* Add a listener that wants to closely follow track playback for a particular player. The listener will be called
* as soon as there is an initial {@link TrackPositionUpdate} for the specified player, and whenever there is an
* unexpected change in playback position, speed, or state on that player.
*
* @param player the player number that the listener is interested in
* @param listener the interface that will be called when there are changes in track playback on the player
*/
public void addTrackPositionListener(int player, TrackPositionListener listener) {
listenerPlayerNumbers.put(listener, player);
TrackPositionUpdate currentPosition = positions.get(player);
if (currentPosition != null) {
listener.movementChanged(currentPosition);
trackPositionListeners.put(listener, currentPosition);
} else {
trackPositionListeners.put(listener, NO_INFORMATION);
}
}
/**
* Remove a listener that was following track playback movement.
*
* @param listener the interface that will no longer be called for changes in track playback
*/
public void removeTrackPositionListener(TrackPositionListener listener) {
trackPositionListeners.remove(listener);
listenerPlayerNumbers.remove(listener);
}
/**
* How many milliseconds is our interpolated time allowed to drift before we consider it a significant enough
* change to update listeners that are trying to track a player's playback position.
*/
private final AtomicLong slack = new AtomicLong(50);
/**
* Check how many milliseconds our interpolated time is allowed to drift from what is being reported by a player
* before we consider it a significant enough change to report to listeners that are trying to closely track a
* player's playback position.
*
* @return the maximum number of milliseconds we will allow our listeners to diverge from the reported playback
* position before reporting a jump
*/
public long getSlack() {
return slack.get();
}
/**
* Set how many milliseconds our interpolated time is allowed to drift from what is being reported by a player
* before we consider it a significant enough change to report to listeners that are trying to closely track a
* player's playback position.
*
* @param slack the maximum number of milliseconds we will allow our listeners to diverge from the reported playback
* position before reporting a jump
*/
public void setSlack(long slack) {
this.slack.set(slack);
}
/**
* Check whether we have diverged from what we would predict from the last update that was sent to a particular
* track position listener.
*
* @param lastUpdate the last update that was sent to the listener
* @param currentUpdate the latest update available for the same player
*
* @return {@code true }if the listener will have diverged by more than our permitted amount of slack, and so
* should be updated
*/
private boolean interpolationsDisagree(TrackPositionUpdate lastUpdate, TrackPositionUpdate currentUpdate) {
long now = System.nanoTime();
return Math.abs(interpolateTimeSinceUpdate(lastUpdate, now) - interpolateTimeSinceUpdate(currentUpdate, now)) >
slack.get();
}
/**
* Check if the current position tracking information for a player represents a significant change compared to
* what a listener was last informed to expect, and if so, send another update. If this is a definitive update
* (i.e. a new beat), and the listener wants all beats, always send it.
*
* @param player the device number for which an update has occurred
* @param update the latest track position tracking information for the specified player, or {@code null} if we
* no longer have any
* @param beat if this update was triggered by a beat packet, contains the packet to pass on to interested listeners
*/
private void updateListenersIfNeeded(int player, TrackPositionUpdate update, Beat beat) {
// Iterate over a copy to avoid issues with concurrent modification
for (Map.Entry<TrackPositionListener, TrackPositionUpdate> entry :
new HashMap<TrackPositionListener, TrackPositionUpdate>(trackPositionListeners).entrySet()) {
if (player == listenerPlayerNumbers.get(entry.getKey())) { // This listener is interested in this player
if (update == null) { // We are reporting a loss of information
if (entry.getValue() != NO_INFORMATION) {
if (trackPositionListeners.replace(entry.getKey(), entry.getValue(), NO_INFORMATION)) {
try {
entry.getKey().movementChanged(null);
} catch (Throwable t) {
logger.warn("Problem delivering null movementChanged update", t);
}
}
}
} else { // We have some information, see if it is a significant change from what was last reported
final TrackPositionUpdate lastUpdate = entry.getValue();
if (lastUpdate == NO_INFORMATION ||
lastUpdate.playing != update.playing ||
Math.abs(lastUpdate.pitch - update.pitch) > 0.000001 ||
interpolationsDisagree(lastUpdate, update)) {
if (trackPositionListeners.replace(entry.getKey(), entry.getValue(), update)) {
try {
entry.getKey().movementChanged(update);
} catch (Throwable t) {
logger.warn("Problem delivering movementChanged update", t);
}
}
}
// And regardless of whether this was a significant change, if this was a new beat and the listener
// implements the interface that requests all beats, send that information.
if (update.definitive && entry.getKey() instanceof TrackPositionBeatListener) {
try {
((TrackPositionBeatListener) entry.getKey()).newBeat(beat, update);
} catch (Throwable t) {
logger.warn("Problem delivering newBeat update", t);
}
}
}
}
}
}
/**
* Reacts to player status updates to update the predicted playback position and state and potentially inform
* registered track position listeners of significant changes.
*/
private final DeviceUpdateListener updateListener = new DeviceUpdateListener() {
@Override
public void received(DeviceUpdate update) {
if (update instanceof CdjStatus) {
updates.put(update.getDeviceNumber(), update);
final BeatGrid beatGrid = BeatGridFinder.getInstance().getLatestBeatGridFor(update);
final int beatNumber = ((CdjStatus) update).getBeatNumber();
if (beatGrid != null && (beatNumber >= 0)) {
boolean done = false;
TrackPositionUpdate lastPosition = positions.get(update.getDeviceNumber());
while (!done && ((lastPosition == null) || lastPosition.timestamp < update.getTimestamp())) {
TrackPositionUpdate newPosition;
if (lastPosition == null || lastPosition.beatGrid != beatGrid) {
// This is a new track, and we have not yet received a beat packet for it
long timeGuess = timeOfBeat(beatGrid, beatNumber, update);
final CueList.Entry likelyCue = findAdjacentCue((CdjStatus) update, beatGrid);
if (likelyCue != null) {
timeGuess = likelyCue.cueTime;
}
newPosition = new TrackPositionUpdate(update.getTimestamp(),
timeGuess, beatNumber, false,
((CdjStatus) update).isPlaying(),
Util.pitchToMultiplier(update.getPitch()),
((CdjStatus) update).isPlayingBackwards(), beatGrid);
} else {
newPosition = new TrackPositionUpdate(update.getTimestamp(),
interpolateTimeFromUpdate(lastPosition, (CdjStatus) update, beatGrid),
beatNumber, false, ((CdjStatus) update).isPlaying(),
Util.pitchToMultiplier(update.getPitch()),
((CdjStatus) update).isPlayingBackwards(), beatGrid);
}
if (lastPosition == null) {
done = (positions.putIfAbsent(update.getDeviceNumber(), newPosition) == null);
} else {
done = positions.replace(update.getDeviceNumber(), lastPosition, newPosition);
}
if (done) {
updateListenersIfNeeded(update.getDeviceNumber(), newPosition, null);
} else { // Some other thread updated the position while we were working, re-evaluate.
lastPosition = positions.get(update.getDeviceNumber());
}
}
} else {
positions.remove(update.getDeviceNumber()); // We can't say where that player is.
updateListenersIfNeeded(update.getDeviceNumber(), null, null);
}
}
}
};
/**
* Translates a beat number to a track time, given a beat grid. In almost all cases, simply delegates that task
* to the beat grid. However, since players sometimes report beats that are outside the beat grid (especially when
* looping tracks that extend for more than a beat's worth of time past the last beat in the beat grid), to avoid
* weird exceptions and infinitely-growing track time reports in such situations, we extrapolate an extension to
* the beat grid by repeating the interval between the last two beats in the track.
*
* In the completely degenerate case of a track with a single beat (which probably will never occur), we simply
* return that beat's time even if you ask for a later one.
*
* @param beatGrid the times at which known beats fall in the track whose playback time we are reporting.
*
* @param beatNumber the number of the beat that a player has just reported reaching, which may be slightly
* greater than the actual number of beats in the track.
*
* @param update the device update which caused this calculation to take place, in case we need to log a warning
* that the reported beat number falls outside the beat grid.
*
* @return the number of milliseconds into the track at which that beat falls, perhaps extrapolated past the final
* recorded beat.
*/
private long timeOfBeat(BeatGrid beatGrid, int beatNumber, DeviceUpdate update) {
if (beatNumber <= beatGrid.beatCount) {
return beatGrid.getTimeWithinTrack(beatNumber);
}
logger.warn("Received beat number " + beatNumber + " from " + update.getDeviceName() + " " +
update.getDeviceNumber() + ", but beat grid only goes up to beat " + beatGrid.beatCount +
". Packet: " + update);
if (beatGrid.beatCount < 2) {
return beatGrid.getTimeWithinTrack(1);
}
long lastTime = beatGrid.getTimeWithinTrack(beatGrid.beatCount);
long lastInterval = lastTime - beatGrid.getTimeWithinTrack(beatGrid.beatCount - 1);
return lastTime + (lastInterval * (beatNumber - beatGrid.beatCount));
}
/**
* Reacts to beat messages to update the definitive playback position for that player. Because we may sometimes get
* a beat packet before a corresponding device update containing the actual beat number, don't increment past the
* end of the beat grid, because we must be looping if we get an extra beat there.
*/
private final BeatListener beatListener = new BeatListener() {
@Override
public void newBeat(Beat beat) {
if (beat.getDeviceNumber() < 16) { // We only care about CDJs.
updates.put(beat.getDeviceNumber(), beat);
// logger.info("Beat: " + beat.getBeatWithinBar());
final BeatGrid beatGrid = BeatGridFinder.getInstance().getLatestBeatGridFor(beat);
if (beatGrid != null) {
TrackPositionUpdate lastPosition = positions.get(beat.getDeviceNumber());
int beatNumber;
boolean definitive;
if (lastPosition == null || lastPosition.beatGrid != beatGrid) {
// Crazy! We somehow got a beat before any other status update from the player. We have
// to assume it was the first beat of the track, we will recover soon.
beatNumber = 1;
definitive = false;
} else {
beatNumber = Math.min(lastPosition.beatNumber + 1, beatGrid.beatCount); // Handle loop at end
definitive = true;
}
// We know the player is playing forward because otherwise we don't get beats.
final TrackPositionUpdate newPosition = new TrackPositionUpdate(beat.getTimestamp(),
timeOfBeat(beatGrid, beatNumber, beat), beatNumber, definitive, true,
Util.pitchToMultiplier(beat.getPitch()), false, beatGrid);
positions.put(beat.getDeviceNumber(), newPosition);
updateListenersIfNeeded(beat.getDeviceNumber(), newPosition, beat);
} else {
positions.remove(beat.getDeviceNumber()); // We can't determine where the player is.
updateListenersIfNeeded(beat.getDeviceNumber(), null, beat);
}
}
}
};
/**
* Set up to automatically stop if anything we depend on stops.
*/
private final LifecycleListener lifecycleListener = new LifecycleListener() {
@Override
public void started(LifecycleParticipant sender) {
logger.debug("The TimeFinder does not auto-start when {} does.", sender);
}
@Override
public void stopped(LifecycleParticipant sender) {
if (isRunning()) {
logger.info("TimeFinder stopping because {} has.", sender);
stop();
}
}
};
/**
* <p>Start interpolating playback position for all active players. Starts the {@link BeatGridFinder},
* {@link BeatFinder}, and {@link VirtualCdj} if they are not already running, because we need them to
* perform our calculations. This in turn starts the {@link DeviceFinder}, so we can keep track of the
* comings and goings of players themselves.</p>
*
* @throws Exception if there is a problem starting the required components
*/
public synchronized void start() throws Exception {
if (!isRunning()) {
DeviceFinder.getInstance().addDeviceAnnouncementListener(announcementListener);
BeatGridFinder.getInstance().addLifecycleListener(lifecycleListener);
BeatGridFinder.getInstance().start();
VirtualCdj.getInstance().addUpdateListener(updateListener);
VirtualCdj.getInstance().addLifecycleListener(lifecycleListener);
VirtualCdj.getInstance().start();
BeatFinder.getInstance().addLifecycleListener(lifecycleListener);
BeatFinder.getInstance().addBeatListener(beatListener);
BeatFinder.getInstance().start();
running.set(true);
deliverLifecycleAnnouncement(logger, true);
}
}
/**
* Stop interpolating playback position for all active players.
*/
public synchronized void stop() {
if (isRunning()) {
BeatFinder.getInstance().removeBeatListener(beatListener);
VirtualCdj.getInstance().removeUpdateListener(updateListener);
running.set(false);
positions.clear();
updates.clear();
deliverLifecycleAnnouncement(logger, false);
}
}
/**
* Holds the singleton instance of this class.
*/
private static final TimeFinder ourInstance = new TimeFinder();
/**
* Get the singleton instance of this class.
*
* @return the only instance of this class which exists.
*/
public static TimeFinder getInstance() {
return ourInstance;
}
/**
* Prevent direct instantiation.
*/
private TimeFinder() {
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("TimeFinder[running:").append(isRunning());
sb.append(", listener count:").append(trackPositionListeners.size());
if (isRunning()) {
sb.append(", latestPositions:").append(getLatestPositions());
sb.append(", latestUpdates:").append(getLatestUpdates());
}
return sb.append("]").toString();
}
}
|
package com.wzhnsc.testframeanimation;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.ImageView;
public class CircularImageView extends ImageView
{
private enum ShapeType {
TYPE_CIRCULAR_SHAPE,
TYPE_CIRCULAR_BEAD
}
private ShapeType mShapeType;
private Paint mBitmapPaint;
private int mSelfWidth;
private int mRadius;
private RectF mCircularBeadRect;
private int mCornerRadius;
public CircularImageView(Context context) {
this(context, null);
}
public CircularImageView(Context context, AttributeSet attrs) {
super(context, attrs);
mBitmapPaint = new Paint();
mBitmapPaint.setAntiAlias(true);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircularImageView);
// 10dp
mCornerRadius = a.getDimensionPixelSize(R.styleable.CircularImageView_cornerRadius,
(int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
10,
getResources().getDisplayMetrics()));
mShapeType = a.getInt(R.styleable.CircularImageView_shapeType, 0) == 0 ?
ShapeType.TYPE_CIRCULAR_SHAPE : ShapeType.TYPE_CIRCULAR_BEAD;
a.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (ShapeType.TYPE_CIRCULAR_SHAPE == mShapeType) {
mSelfWidth = Math.min(getMeasuredWidth(), getMeasuredHeight());
mRadius = mSelfWidth / 2;
setMeasuredDimension(resolveSizeAndState(mSelfWidth, widthMeasureSpec, MeasureSpec.UNSPECIFIED),
resolveSizeAndState(mSelfWidth, heightMeasureSpec, MeasureSpec.UNSPECIFIED));
}
}
@Override
protected void onDraw(Canvas canvas)
{
Drawable drawable = getDrawable();
if (null == drawable) {
return;
}
fixBmpShader(drawable);
if (ShapeType.TYPE_CIRCULAR_BEAD == mShapeType) {
canvas.drawRoundRect(mCircularBeadRect, mCornerRadius, mCornerRadius, mBitmapPaint);
}
else {
canvas.drawCircle(mRadius, mRadius, mRadius, mBitmapPaint);
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w, h, oldw, oldh);
if (ShapeType.TYPE_CIRCULAR_BEAD == mShapeType) {
mCircularBeadRect = new RectF(0, 0, w, h);
}
}
private void fixBmpShader(Drawable drawable) {
Bitmap bmp = drawable2Bmp(drawable);
float scale = 1.0f;
if (ShapeType.TYPE_CIRCULAR_SHAPE == mShapeType) {
scale = (float)mSelfWidth / Math.min(bmp.getWidth(), bmp.getHeight());
}
else if (ShapeType.TYPE_CIRCULAR_BEAD == mShapeType) {
if (!(bmp.getWidth() == getWidth() && bmp.getHeight() == getHeight())) {
scale = Math.max((float)getWidth() / bmp.getWidth(),
(float)getHeight() / bmp.getHeight());
}
}
BitmapShader bmpShader = new BitmapShader(bmp,
TileMode.CLAMP, TileMode.CLAMP);
Matrix matrix = new Matrix();
matrix.setScale(scale, scale);
bmpShader.setLocalMatrix(matrix);
mBitmapPaint.setShader(bmpShader);
}
private Bitmap drawable2Bmp(Drawable drawable)
{
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable)drawable).getBitmap();
}
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
drawable.setBounds(0, 0, width, height);
drawable.draw(new Canvas(bmp));
return bmp;
}
private static final String INSTANCE_STATE = "instance_state";
private static final String SHAPE_TYPE = "shape_type";
private static final String CORNER_RADIUS = "corner_radius";
@Override
protected Parcelable onSaveInstanceState()
{
Bundle bundle = new Bundle();
bundle.putParcelable(INSTANCE_STATE, super.onSaveInstanceState());
bundle.putInt(SHAPE_TYPE, ShapeType.TYPE_CIRCULAR_SHAPE == mShapeType ? 0 : 1);
bundle.putInt(CORNER_RADIUS, mCornerRadius);
return bundle;
}
@Override
protected void onRestoreInstanceState(Parcelable state)
{
if (state instanceof Bundle) {
super.onRestoreInstanceState(((Bundle)state).getParcelable(INSTANCE_STATE));
mShapeType = ((Bundle)state).getInt(SHAPE_TYPE) == 0 ?
ShapeType.TYPE_CIRCULAR_SHAPE :
ShapeType.TYPE_CIRCULAR_BEAD;
mCornerRadius = ((Bundle)state).getInt(CORNER_RADIUS);
}
else {
super.onRestoreInstanceState(state);
}
}
}
|
package openaf.plugins;
import java.io.IOException;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.NativeObject;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.annotations.JSConstructor;
import org.mozilla.javascript.annotations.JSFunction;
import org.snmp4j.AbstractTarget;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.ScopedPDU;
import org.snmp4j.Snmp;
import org.snmp4j.Target;
import org.snmp4j.TransportMapping;
import org.snmp4j.UserTarget;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.SecurityLevel;
import org.snmp4j.security.SecurityModels;
import org.snmp4j.security.SecurityProtocols;
import org.snmp4j.security.USM;
import org.snmp4j.security.UsmUser;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.Counter32;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.Integer32;
import org.snmp4j.smi.Null;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.TimeTicks;
import org.snmp4j.smi.UnsignedInteger32;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultTcpTransportMapping;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import openaf.AFCmdBase;
import openaf.SimpleLog;
import openaf.SimpleLog.logtype;
/**
*
* @author Nuno Aguiar
*
*/
public class SNMP extends ScriptableObject {
private static final long serialVersionUID = 9163133329817783828L;
protected Snmp snmp;
protected String address;
protected long timeout;
protected int retries;
protected OctetString community;
protected String securityName;
protected OID authProtocol = org.snmp4j.security.AuthSHA.ID;
protected String authPassphrase;
protected OID privProtocol = org.snmp4j.security.PrivDES.ID;
protected String privPassphrase;
protected int version;
protected byte[] engineID;
@Override
public String getClassName() {
return "SNMP";
}
/**
* <odoc>
* <key>SNMP.SNMP(anAddress, aCommunity, aTimeout, retries, version, securityMap)</key>
* Tries to establish a SNMP connection to the given address (anAddress in the form of udp:x.x.x.x/port) of a specific community (aCommunity (e.g public))
* with a provided timeout (aTimeout) and number of retries. You can also specify the version (2 or 3). For version 3
* you can also provide a securityMap with the following entries:\
* \
* securityName (String)\
* authProtocol (String) HMAC128SHA224, HMAC192SHA256, HMAC256SHA384, HMAC384SHA512, MD5, SHA\
* privProtocol (String) 3DES, AES128, AES192, AES256, DES\
* authPassphrase (String)\
* privPassphrase (String)\
* engineId (String)\
* \
* </odoc>
*/
@JSConstructor
public void newSNMP(String addr, String community, int tout, int ret, int version, Object security) throws IOException {
address = addr;
if (tout <= 0) timeout = 1500; else timeout = tout;
if (ret <= 0) retries = 2; else retries = ret;
if (community != null)
this.community = new OctetString(community);
else
this.community = new OctetString("public");
if (version <= 1) this.version = 2; else this.version = version;
if (version >= 2 && security instanceof NativeObject) {
NativeObject smap = (NativeObject) security;
if (smap.containsKey("securityName")) this.securityName = (String) smap.get("securityName");
if (smap.containsKey("engineId")) this.engineID = ((String) smap.get("engineId")).getBytes();
}
if (version >= 3) {
if (security instanceof NativeObject) {
NativeObject smap = (NativeObject) security;
if (smap.containsKey("authProtocol")) {
switch((String) smap.get("authProtocol")) {
case "HMAC128SHA224": authProtocol = org.snmp4j.security.AuthHMAC128SHA224.ID; break;
case "HMAC192SHA256": authProtocol = org.snmp4j.security.AuthHMAC192SHA256.ID; break;
case "HMAC256SHA384": authProtocol = org.snmp4j.security.AuthHMAC256SHA384.ID; break;
case "HMAC384SHA512": authProtocol = org.snmp4j.security.AuthHMAC384SHA512.ID; break;
case "MD5": authProtocol = org.snmp4j.security.AuthMD5.ID; break;
case "SHA": authProtocol = org.snmp4j.security.AuthSHA.ID; break;
}
}
if (smap.containsKey("privProtocol")) {
switch((String) smap.get("privProtocol")) {
case "3DES": privProtocol = org.snmp4j.security.Priv3DES.ID; break;
case "AES128": privProtocol = org.snmp4j.security.PrivAES128.ID; break;
case "AES192": privProtocol = org.snmp4j.security.PrivAES192.ID; break;
case "AES256": privProtocol = org.snmp4j.security.PrivAES256.ID; break;
case "DES": privProtocol = org.snmp4j.security.PrivDES.ID; break;
}
}
if (smap.containsKey("authPassphrase")) {
this.authPassphrase = (String) smap.get("authPassphrase");
}
if (smap.containsKey("privPassphrase")) {
this.privPassphrase = (String) smap.get("privPassphrase");
}
}
}
start();
}
/**
* <odoc>
* <key>SNMP.start()</key>
* Starts the client connection (usually already invoked by the SNMP constructor, so there shouldn't
* be a need to invoke it).
* </odoc>
*/
@JSFunction
public void start() throws IOException {
TransportMapping<?> transport;
if (address.startsWith("tcp")) {
transport = new DefaultTcpTransportMapping();
} else {
transport = new DefaultUdpTransportMapping();
}
snmp = new Snmp(transport);
if (this.version >= 3) {
if (this.engineID == null) this.engineID = MPv3.createLocalEngineID();
USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(this.engineID), 0);
SecurityModels.getInstance().addSecurityModel(usm);
snmp.getUSM().addUser(new OctetString(this.securityName), new UsmUser(new OctetString(this.securityName), this.authProtocol, new OctetString(this.authPassphrase), this.privProtocol, new OctetString(this.privPassphrase)));
}
transport.listen();
}
/**
*
* @return
*/
protected Target getTarget() {
Address targetAddress = GenericAddress.parse(address);
AbstractTarget target;
if (this.authPassphrase != null || this.privPassphrase != null) {
target = new UserTarget();
} else {
target = new CommunityTarget();
((CommunityTarget) target).setCommunity(community);
}
target.setAddress(targetAddress);
target.setRetries(retries);
target.setTimeout(timeout);
if (this.version == 2) target.setVersion(SnmpConstants.version2c);
if (this.version == 3) target.setVersion(SnmpConstants.version3);
if (this.securityName != null) target.setSecurityName(new OctetString(securityName));
if (this.authPassphrase != null && this.privPassphrase == null) {
target.setSecurityLevel(SecurityLevel.AUTH_NOPRIV);
}
if (this.authPassphrase != null && this.privPassphrase != null) {
target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
}
if (this.authPassphrase == null && this.privPassphrase == null) {
target.setSecurityLevel(SecurityLevel.NOAUTH_NOPRIV);
}
return target;
}
public ResponseEvent getOIDs(OID oids[]) throws IOException {
PDU pdu = new PDU();
for(OID oid : oids) {
pdu.add(new VariableBinding(oid));
}
pdu.setType(PDU.GET);
ResponseEvent event = snmp.send(pdu, getTarget(), null);
if (event != null) {
return event;
}
throw new RuntimeException("GET timed out");
}
/**
*
* @param oid
* @return
* @throws Exception
*/
public VariableBinding[] getAsPDU(OID oid) throws Exception {
ResponseEvent event = getOIDs(new OID[] { oid } );
if (event != null) {
if (event.getError() != null) {
throw event.getError();
}
SimpleLog.log(logtype.DEBUG, "SNMP Event " + event.toString(), null);
if (event.getResponse() != null) {
//return event.getResponse().get(0).getVariable().toString();
return event.getResponse().toArray();
} else {
throw new Exception("SNMP Request timeout");
}
}
SimpleLog.log(logtype.DEBUG, "SNMP Event null", null);
return null;
}
/**
*
* @param oid
* @return
*/
public OID newOID(String oid) {
return new OID(oid);
}
/**
* <odoc>
* <key>SNMP.get(aOID) : Object</key>
* Gets a value for the provided aOID (expects value to be string or convertible to string).
* </odoc>
*/
@JSFunction
public Object get(String oid) throws Exception {
VariableBinding[] vars = getAsPDU(newOID(oid));
Context cx = (Context) AFCmdBase.jse.enterContext();
Scriptable no = cx.newObject((Scriptable) AFCmdBase.jse.getGlobalscope());
AFCmdBase.jse.exitContext();
if (vars != null) {
for(VariableBinding var : vars) {
no.put(var.getOid().toString(), no, var.getVariable().toString());
}
}
return no;
}
/**
* <odoc>
* <key>SNMP.trap(aOID, aDataArray, shouldInform)</key>
* Tries to send a trap based on aOID and using aDataArray where each element should be a map with
* oid, type (i - integer, u - unsigned, c - counter32, s - string, x - hex string, d - decimal string, n - nullobj, o - objid, t - timeticks, a - ipaddress,) and value.
* Optionally you can determine if shouldInform instead of sending the trap.
* </odoc>
*/
@JSFunction
public Object trap(String oid, Object data, boolean inform) throws IOException {
PDU trap;
if (this.version >= 3) {
trap = new ScopedPDU();
} else {
trap = new PDU();
}
if (!inform)
trap.setType(PDU.TRAP);
else
trap.setType(PDU.INFORM);
OID ooid = new OID(oid);
trap.add(new VariableBinding(SnmpConstants.snmpTrapOID, ooid));
if (data instanceof NativeArray) {
NativeArray no = (NativeArray) data;
for(Object mentry : no) {
if (mentry instanceof NativeObject) {
NativeObject nmentry = (NativeObject) mentry;
if (nmentry.containsKey("type") && nmentry.containsKey("value") && nmentry.containsKey("OID")) {
// Value types: i - integer, u - unsigned, c - counter32, s - string, x - hex string, d - decimal string, n - nullobj, o - objid, t - timeticks, a - ipaddress, b - bits
OID toid = new OID((String) nmentry.get("OID"));
switch((String) nmentry.get("type")) {
case "i":
trap.add(new VariableBinding(toid, new Integer32((Integer) nmentry.get("value"))));
break;
case "u":
trap.add(new VariableBinding(toid, new UnsignedInteger32((Integer) nmentry.get("value"))));
break;
case "c":
trap.add(new VariableBinding(toid, new Counter32((Integer) nmentry.get("value"))));
break;
case "n":
trap.add(new VariableBinding(toid, new Null()));
break;
case "o":
trap.add(new VariableBinding(toid, new OID((String) nmentry.get("value"))));
break;
case "t":
trap.add(new VariableBinding(toid, new TimeTicks((Integer) nmentry.get("value"))));
break;
case "a":
trap.add(new VariableBinding(toid, new TimeTicks((Integer) nmentry.get("value"))));
break;
case "b":
break;
case "s":
default:
trap.add(new VariableBinding(toid, new OctetString((String) nmentry.get("value"))));
}
} else {
System.out.println("ERR: doesn't have type, value and OID");
}
} else {
System.out.println("ERR: Not a native object");
}
}
} else {
System.out.println("ERR: Not a native array");
}
return this.snmp.send(trap, getTarget());
}
/** <odoc>
* <key>SNMP.inform(aOID, aDataArray)</key>
* Tries to send an inform based on aOID and using aDataArray where each element should be a map with
* oid, type (i - integer, u - unsigned, c - counter32, s - string, x - hex string, d - decimal string, n - nullobj, o - objid, t - timeticks, a - ipaddress,) and value.
* </odoc>
**/
@JSFunction
public Object inform(String oid, Object data) throws IOException {
return this.trap(oid, data, true);
}
}
|
package org.everit.expression;
public class ParserConfiguration {
private final ClassLoader classLoader;
private int startColumn = 1;
private int startRow = 1;
public ParserConfiguration(final ClassLoader classLoader) {
this.classLoader = classLoader;
}
public ParserConfiguration(final ParserConfiguration original) {
if (original == null) {
throw new NullPointerException("Parser configuration parameter cannot be null");
} else {
this.startRow = original.startRow;
this.startColumn = original.startColumn;
this.classLoader = original.classLoader;
}
}
public ClassLoader getClassLoader() {
return classLoader;
}
/**
* Get the current line offset. This measures the number of cursor positions back to the beginning of the line.
*
* @return int offset
*/
public int getStartColumn() {
return startColumn;
}
/**
* Get total number of lines declared in the current context.
*
* @return int of lines
*/
public int getStartRow() {
return startRow;
}
/**
* Sets the current line offset. (Generally only used by the compiler)
*
* @param lineOffset
* The offset amount
*/
public void setStartColumn(final int lineOffset) {
this.startColumn = lineOffset;
}
public void setStartRow(final int lineNumber) {
this.startRow = lineNumber;
}
}
|
package net.johnbrooks.nutrim.activities;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import net.johnbrooks.nutrim.R;
import net.johnbrooks.nutrim.utilities.MyApplicationContexts;
import net.johnbrooks.nutrim.utilities.Profile;
import net.johnbrooks.nutrim.wrapper.NutritionIXField;
import net.johnbrooks.nutrim.wrapper.NutritionIXItem;
import net.johnbrooks.nutrim.wrapper.NutritionIXQuery;
import java.util.ArrayList;
import java.util.List;
public class UpdateActivity extends AppCompatActivity
{
public static List<NutritionIXItem> queryResults = new ArrayList<>();
private NutritionIXItem selectedItem;
private static UpdateActivity instance;
public static UpdateActivity getInstance()
{
if (instance == null)
{
Log.d(UpdateActivity.class.getSimpleName(), "Null instance of class.");
}
return instance;
}
private EditText et_search;
private EditText et_quantity;
private LinearLayout ll_searchContents;
private List<RadioButton> radioButtonList;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
// Prepare back button
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
// Get required components and listeners
instance = this;
radioButtonList = new ArrayList<>();
selectedItem = null;
et_search = (EditText) findViewById(R.id.updateActivity_editText_search);
et_quantity = (EditText) findViewById(R.id.updateActivity_editText_quantity);
ll_searchContents = (LinearLayout) findViewById(R.id.updateActivity_linearLayout_searchContents);
findViewById(R.id.updateActivity_button_search).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
run();
}
});
et_search.setOnKeyListener(new View.OnKeyListener()
{
@Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER)
{
run();
return true;
}
return false;
}
});
findViewById(R.id.updateActivity_button_manual).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Intent intent = new Intent(UpdateActivity.this, ManualUpdateActivity.class);
startActivity(intent);
finish();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.update, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
this.finish();
return true;
case R.id.action_done:
if (finishSelection())
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private boolean finishSelection()
{
if (selectedItem != null)
{
Profile profile = Profile.getProfile();
if (profile != null)
{
profile.addCaloriesToday(selectedItem, Integer.parseInt(et_quantity.getText().toString()));
profile.save(MyApplicationContexts.getLatestContextWrapper(UpdateActivity.getInstance()));
}
return true;
}
return false;
}
public void refreshList()
{
ll_searchContents.removeAllViews();
radioButtonList.clear();
if (queryResults.isEmpty())
{
TextView tv_nothing_to_display = new TextView(UpdateActivity.this);
tv_nothing_to_display.setText("Nothing was returned from your search. ");
ll_searchContents.addView(tv_nothing_to_display);
}
else
{
// Add widgets for each result returned from query.
for (int i = 0; i < queryResults.size(); i++)
{
final int index = i;
NutritionIXItem item = queryResults.get(i);
LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.widget_updateresult, null);
ImageView picture = (ImageView) layout.findViewById(R.id.widget_updateResult_imageView);
TextView itemName = (TextView) layout.findViewById(R.id.widget_updateResult_itemName);
TextView calories = (TextView) layout.findViewById(R.id.widget_updateResult_caloriesTextView);
TextView brand = (TextView) layout.findViewById(R.id.widget_updateResult_brandTextView);
String shortItemName = item.getName().substring(0, Math.min(item.getName().length(), 20));
String shortBrand = item.getBrand().substring(0, Math.min(item.getBrand().length(), 20));
itemName.setText(shortItemName);
calories.setText("Calories: " + item.getCalories());
brand.setText("Brand: " + shortBrand);
picture.setImageResource(item.getPictureID());
ll_searchContents.addView(layout);
// Keep track of all buttons and manage their click events.
final RadioButton button = (RadioButton) layout.findViewById(R.id.widget_updateResult_ratioButton);
radioButtonList.add(button);
button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
for (RadioButton radioButton : radioButtonList)
if (radioButton != button)
radioButton.setChecked(false);
NutritionIXItem clickedItem = queryResults.get(index);
Log.d(UpdateActivity.class.getSimpleName(), "Clicked on " + clickedItem.getName() + "(" + index + ")");
selectedItem = clickedItem;
}
});
}
}
}
private void run()
{
if (getCurrentFocus() != null)
{
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
String keyword = et_search.getText().toString();
et_search.setText("");
NutritionIXQuery.searchForItems(keyword, NutritionIXField.ITEM_NAME, NutritionIXField.CALORIES, NutritionIXField.ITEM_BRAND, NutritionIXField.SERVING_SIZE);
}
}
|
package org.everit.test.doubleparser;
/**
* A parser that converts a string to double without using any in-built Java functionality such as
* {@link Double#valueOf(String)}, java.math package, etc.
*/
public interface DoubleParser {
double strtod(char[] str);
}
|
package nodomain.freeyourgadget.gadgetbridge.util;
import android.content.SharedPreferences;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
/**
* Wraps SharedPreferences to avoid ClassCastExceptions and others.
*/
public class Prefs {
private static final Logger LOG = LoggerFactory.getLogger(Prefs.class);
private final SharedPreferences preferences;
public Prefs(SharedPreferences preferences) {
this.preferences = preferences;
}
public String getString(String key, String defaultValue) {
String value = preferences.getString(key, defaultValue);
if (value == null || "".equals(value)) {
return defaultValue;
}
return value;
}
public Set<String> getStringSet(String key, Set<String> defaultValue) {
Set<String> value = preferences.getStringSet(key, defaultValue);
if (value == null || value.isEmpty()) {
return defaultValue;
}
return value;
}
/**
* Returns the preference saved under the given key as an integer value.
* Note that it is irrelevant whether the preference value was actually
* saved as an integer value or a string value.
* @param key the preference key
* @param defaultValue the default value to return if the preference value is unset
* @return the saved preference value or the given defaultValue
*/
public int getInt(String key, int defaultValue) {
try {
return preferences.getInt(key, defaultValue);
} catch (Exception ex) {
try {
String value = preferences.getString(key, String.valueOf(defaultValue));
if ("".equals(value)) {
return defaultValue;
}
return Integer.parseInt(value);
} catch (Exception ex2) {
logReadError(key, ex);
return defaultValue;
}
}
}
/**
* Returns the preference saved under the given key as a long value.
* Note that it is irrelevant whether the preference value was actually
* saved as a long value or a string value.
* @param key the preference key
* @param defaultValue the default value to return if the preference value is unset
* @return the saved preference value or the given defaultValue
*/
public long getLong(String key, long defaultValue) {
try {
return preferences.getLong(key, defaultValue);
} catch (Exception ex) {
try {
String value = preferences.getString(key, String.valueOf(defaultValue));
if ("".equals(value)) {
return defaultValue;
}
return Long.parseLong(value);
} catch (Exception ex2) {
logReadError(key, ex);
return defaultValue;
}
}
}
/**
* Returns the preference saved under the given key as a float value.
* Note that it is irrelevant whether the preference value was actually
* saved as a float value or a string value.
* @param key the preference key
* @param defaultValue the default value to return if the preference value is unset
* @return the saved preference value or the given defaultValue
*/
public float getFloat(String key, float defaultValue) {
try {
return preferences.getFloat(key, defaultValue);
} catch (Exception ex) {
try {
String value = preferences.getString(key, String.valueOf(defaultValue));
if ("".equals(value)) {
return defaultValue;
}
return Float.parseFloat(value);
} catch (Exception ex2) {
logReadError(key, ex);
return defaultValue;
}
}
}
/**
* Returns the preference saved under the given key as a boolean value.
* Note that it is irrelevant whether the preference value was actually
* saved as a boolean value or a string value.
* @param key the preference key
* @param defaultValue the default value to return if the preference value is unset
* @return the saved preference value or the given defaultValue
*/
public boolean getBoolean(String key, boolean defaultValue) {
try {
return preferences.getBoolean(key, defaultValue);
} catch (Exception ex) {
try {
String value = preferences.getString(key, String.valueOf(defaultValue));
if ("".equals(value)) {
return defaultValue;
}
return Boolean.parseBoolean(value);
} catch (Exception ex2) {
logReadError(key, ex);
return defaultValue;
}
}
}
private void logReadError(String key, Exception ex) {
LOG.error("Error reading preference value: " + key + "; returning default value", ex); // log the first exception
}
/**
* Access to the underlying SharedPreferences, typically only used for editing values.
* @return the underlying SharedPreferences object.
*/
public SharedPreferences getPreferences() {
return preferences;
}
}
|
package org.fakekoji.xmlrpc.server.core;
import hudson.plugins.scm.koji.Constants;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.fakekoji.xmlrpc.server.IsFailedBuild;
import org.fakekoji.xmlrpc.server.utils.DirFilter;
import org.fakekoji.xmlrpc.server.utils.FileFileFilter;
public class FakeBuild {
private final String name;
private final String version;
private final String release;
private final String nvr;
private final File dir;
private static final String logs = "logs";
private static final String data = "data";
public static final String notBuiltTagPart = "_notBuild-";
private static final String archesConfigFileName = "arches-expected";
public FakeBuild(String name, String version, String release, File releaseDir) {
this.dir = releaseDir;
this.name = name;
this.version = version;
this.release = release;
this.nvr = name + "-" + version + "-" + release;
}
public Map toBuildMap() {
Map<String, Object> buildMap = new HashMap();
buildMap.put(Constants.name, name);
buildMap.put(Constants.version, version);
buildMap.put(Constants.release, release);
buildMap.put(Constants.nvr, getNVR());
buildMap.put(Constants.build_id, getBuildID());
//"2016-08-02 21:23:37.487583");
buildMap.put(Constants.completion_time, Constants.DTF.format(getFinishingDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime()));
buildMap.put(Constants.rpms, getRpmsAsArrayOfMaps(getArches().toArray(new Object[0])));
return buildMap;
}
String getNVR() {
return nvr;
}
@Override
public String toString() {
return getNVR() + " " + getBuildID();
}
private List<File> getLogs() {
List<File> logs = new ArrayList();
List<String> arches = getArches();
for (String arch : arches) {
logs.addAll(getLogs(arch));
}
return logs;
}
public List<File> getLogs(String arch) {
File logDir = getLogsDir();
List<File> logs = new ArrayList();
if (logDir == null) {
return logs;
}
if (!getArches().contains(arch)) {
return logs;
}
File logFinalDir = new File(logDir, arch);
if (!logFinalDir.exists()) {
return logs;
}
File[] logfiles = logFinalDir.listFiles(new FileFileFilter());
for (File logfile : logfiles) {
logs.add(logfile.getAbsoluteFile());
}
return logs;
}
List<File> getNonLogs() {
List<File> files = new ArrayList();
List<String> arches = getArches();
for (String arche : arches) {
files.addAll(getNonLogs(arche));
}
return files;
}
public List<File> getNonLogs(String arch) {
List<File> files = new ArrayList();
if (!getArches().contains(arch)) {
return files;
}
File finalDir = new File(dir, arch);
File[] possibleFfiles = finalDir.listFiles(new FileFileFilter());
for (File file : possibleFfiles) {
files.add(file.getAbsoluteFile());
}
return files;
}
File getLogsDir() {
File data = getDataDir();
if (data == null) {
return null;
}
return new File(data, logs);
}
private File getDataDir() {
File[] possibleArchesDirs = dir.listFiles(new DirFilter());
//List<String> arches = new ArrayList<>(possibleArchesDirs.length);
for (File archDir : possibleArchesDirs) {
if (archDir.getName().equalsIgnoreCase(data)) {
return archDir;
} else {
}
}
return null;
}
private File getArchesConfigFile() {
return new File(getDataDir(), archesConfigFileName);
}
private File getProjectConfigFile1() {
return new File(dir + "/../../" + archesConfigFileName);
}
private File getProjectConfigFile2() {
return new File(dir + "/../../../" + name + "-" + archesConfigFileName);
}
public List<String> getArches() {
File[] possibleArchesDirs = dir.listFiles(new DirFilter());
List<String> arches = new ArrayList<>(possibleArchesDirs.length);
for (File archDir : possibleArchesDirs) {
if (archDir.getName().equalsIgnoreCase(data)) {
} else {
arches.add(archDir.getName());
}
}
return arches;
}
/**
* This method is crucial for fake koji and its cooperation with
* scm-koji-plugin.
*
* This method is trying to guess tags based on content of the build is it
* win? Windows is it specific rhel/fedora - that one is it static? all!
*
* x
*
* is it openjdk? is it oracle? is it ibm??
*
* x
*
* is the build finished?
*
* @return
* @throws java.io.IOException
*/
public String[] guessTags() throws IOException {
List<File> files = this.getNonLogs();
for (File file : files) {
if (file.getName().toLowerCase().contains("win") && file.getParentFile().getName().toLowerCase().contains("win")) {
return prefixIfNecessary(TagsProvider.getWinTags());
}
if (name.endsWith("openjdk")) {
//currently we have static only for linux
if (file.getName().toLowerCase().contains("static") || release.toLowerCase().contains("upstream")) {
return prefixIfNecessary(connect(TagsProvider.getFedoraTags(), TagsProvider.getRHELtags(), TagsProvider.getRhelTags(), TagsProvider.getWinTags()));
}
if (release.contains("el")) {
int osVersion = determineRhOs(release);
return prefixIfNecessary(new String[]{
TagsProvider.getRhel5Rhel6Base(osVersion),
TagsProvider.getRhel7Base(osVersion)});
}
if (release.contains("fc")) {
int osVersion = determineRhOs(release);
return prefixIfNecessary(new String[]{
TagsProvider.getFedoraBase(osVersion)
});
}
}
//oracle and ibm are far from being done. But at least start is sumarised there
if (name.endsWith("oracle")) {
//currently we have static only for linux
if (file.getName().toLowerCase().contains("static") || release.contains("upstream")) {
return prefixIfNecessary(connect(TagsProvider.getOracleTags()));
}
}
if (name.endsWith("ibm")) {
//currently we have static only for linux
if (file.getName().toLowerCase().contains("static") || release.contains("upstream")) {
return prefixIfNecessary(connect(TagsProvider.getSuplementaryRhel5LikeTag(), TagsProvider.getSuplementaryRhel6LikeTag(), TagsProvider.getSuplementaryRhel7LikeTag()));
}
}
}
return new String[0];
}
private String[] connect(String[]... tags) {
List<String> all = new ArrayList<>();
for (String[] tag : tags) {
all.addAll(Arrays.asList(tag));
}
String[] arr = new String[all.size()];
arr = all.toArray(arr);
return arr;
}
public int getProjectID() {
return name.hashCode();
}
public int getBuildID() {
//dir's hash is better then NVR's, as it will be really always unique
return dir.hashCode();
}
/*
[ 0] "size = 16" HashMap ObjectVariable
[ 0] "release => 1.b14.fc24" HashMap$Node ObjectVariable
[ 2] "nvr => java-1.8.0-openjdk-debuginfo-1.8.0.102-1.b14.fc24" HashMap$Node ObjectVariable
[ 3] "external_repo_id => 0" HashMap$Node ObjectVariable
[ 4] "version => 1.8.0.102" HashMap$Node ObjectVariable
[ 5] "external_repo_name => INTERNAL" HashMap$Node ObjectVariable
[ 6] "size => 82989458" HashMap$Node ObjectVariable
[ 7] "build_id => 794434" HashMap$Node ObjectVariable
[ 8] "buildtime => 1472142006" HashMap$Node ObjectVariable
[ 9] "metadata_only => false" HashMap$Node ObjectVariable
[10] "extra => null" HashMap$Node ObjectVariable
[11] "buildroot_id => 6287882" HashMap$Node ObjectVariable
[12] "name => java-1.8.0-openjdk-debuginfo" HashMap$Node ObjectVariable
[13] "payloadhash => a94abb6777419cfd8a3e9db537554293" HashMap$Node ObjectVariable
[14] "arch => x86_64" HashMap$Node ObjectVariable
[15] "id => 7988968" HashMap$Node ObjectVariable
[ 1] "epoch => 1" HashMap$Node ObjectVariable
[ 1] "size = 16" HashMap ObjectVariable
*/
public Object[] getRpmsAsArrayOfMaps(Object[] archs) {
List<File> files = getNonLogs();
List<Object> r = new ArrayList(files.size());
for (int i = 0; i < files.size(); i++) {
File get = files.get(i);
String fname = get.getName();
String pkgNAme = replaceLast(fname, "-.*", "");
pkgNAme = replaceLast(pkgNAme, "-.*", "");
String pkgFile = replaceLast(fname, "\\..*", ""); //.suffix
pkgFile = replaceLast(pkgFile, "\\..*", ""); //.arch
String arch = get.getParentFile().getName();
boolean mayBeFailed = new IsFailedBuild(get.getParentFile().getParentFile()).reCheck().getLastResult();
if (mayBeFailed) {
System.out.println(" Warning: " + get + " seems to be from failed build!");
}
if (arrayContains(archs, arch)) {
Map m = new HashMap();
r.add(m);
m.put(Constants.release, release);
m.put(Constants.version, version);
m.put(Constants.name, pkgNAme);
/*IMPORTANT filename is originally only for archives. misusing here*/
m.put(Constants.filename, fname);
m.put(Constants.nvr, pkgFile);
m.put(Constants.arch, arch);
m.put(Constants.build_id, getBuildID());
}
}
return r.toArray();
}
public static String replaceLast(String text, String regex, String replacement) {
return text.replaceFirst("(?s)(.*)" + regex, "$1" + replacement);
}
private Date getFinishingDate() {
File f = getNewestFile();
if (f == null) {
//keep running?
return new Date();
} else {
return new Date(f.lastModified());
}
}
private File getNewestFile() {
List<File> files = getNonLogs();
if (files == null || files.isEmpty()) {
files = getLogs();
}
if (files == null || files.isEmpty()) {
return null;
}
Collections.sort(files, (File o1, File o2) -> {
if (o1.lastModified() == o2.lastModified()) {
return 0;
}
if (o1.lastModified() > o2.lastModified()) {
return -1;
}
return 1;
});
return files.get(0);
}
/**
* Each src archive must be be attempted on all those archs.
*
* If the build fails, or arch is not accessible, the column must have
* FAILED file instead of build. (+ ideally logs).
*
* Little bit more generally - if the arch dir don't exists or is empty, is
* considered as not build
*/
private static final String[] defaultSupportedArchs = new String[]{"x86_64", "i686", "win"/*, "aarch64"*/};
//aarch64 is now added in rnutime, via per project settings. When ojdk9 will be oldest suported jdk, it have sense to put it here.
private String[] getSupportedArches() throws IOException {
System.out.println("For: " + getNVR());
if (getArchesConfigFile().exists()) {
System.out.println("Using expected arches from " + getArchesConfigFile().getAbsolutePath());
return readArchesFile(getArchesConfigFile());
}
if (getProjectConfigFile1().exists()) {
System.out.println("Using expected arches from " + getProjectConfigFile1().getAbsolutePath());
return readArchesFile(getProjectConfigFile1());
}
if (getProjectConfigFile2().exists()) {
System.out.println("Using expected arches from " + getProjectConfigFile2().getAbsolutePath());
return readArchesFile(getProjectConfigFile2());
}
System.out.println("Using hardcoded arches.");
return defaultSupportedArchs;
}
public void printExpectedArchesForThisBuild() {
try {
System.out.println("Expected to build on: "+Arrays.toString(getSupportedArches()));
} catch (IOException ex) {
ex.printStackTrace();
}
}
private String[] prefixIfNecessary(String[] connectedTags) throws IOException {
List<String> arches = getArches();
Collections.sort(getArches());
//primary case - the build have src, so we expect to build it in time onall arches
if (arches.contains("src")) {
boolean allBuilt = true;
//there may be IO involved
String[] thisOnesArches = getSupportedArches();
System.err.println(Arrays.toString(thisOnesArches));
List<String> tags = new ArrayList<>(connectedTags.length * thisOnesArches.length);
for (String connectedTag : connectedTags) {
for (String arch : thisOnesArches) {
File archDir = new File(dir, arch);
if (archDir.exists() && archDir.isDirectory() && archDir.list().length > 0) {
//hmm no op?
} else {
allBuilt = false;
tags.add(arch + notBuiltTagPart + connectedTag);
}
}
}
if (allBuilt) {
List<File> files = getNonLogs();
for (File file : files) {
if (file.getAbsolutePath().contains("fastdebug")) {
String[] nwTags = new String[connectedTags.length];
for (int i = 0; i < connectedTags.length; i++) {
nwTags[i] = "fastdebug-" + connectedTags[i];
}
return nwTags;
}
}
return connectedTags;
} else {
return tags.toArray(new String[0]);
}
}
//ok, the package was probably built on all/expected by uploader
return connectedTags;
}
private int determineRhOs(String release) {
String stripped = release.replaceAll(".*\\.fc", "").replaceAll(".*\\.el", "");
String result = "";
for (int i = 0; i < stripped.length(); i++) {
char ch = stripped.charAt(i);
if (Character.isDigit(ch)) {
result = result + ch;
} else {
return Integer.valueOf(result);
}
}
//probaby error, so throwing no-int exception
return Integer.valueOf(result);
}
private boolean arrayContains(Object[] archs, String arch) {
if (archs == null || archs.length == 0) {
return true;
}
for (Object arch1 : archs) {
if (arch1.equals(arch)) {
return true;
}
}
return false;
}
public File getDir() {
return dir;
}
public static void main(String... arg) throws IOException {
//arg = new String[]{"/mnt/raid1/local-builds/java-9-openjdk/" + archesConfigFileName};
if (arg.length == 0) {
System.out.println("Expected single argument - path to file to save the file. Suggested name is: " + archesConfigFileName);
System.exit(1);
}
generateDefaultArchesFile(new File(arg[0]));
System.out.println(new File(arg[0]).getAbsolutePath());
System.err.println(Arrays.toString(readArchesFile(new File(arg[0]))));
}
private static void generateDefaultArchesFile(File f) throws IOException {
try (
OutputStream fis = new FileOutputStream(f);
OutputStreamWriter isr = new OutputStreamWriter(fis, Charset.forName("UTF-8"));
BufferedWriter br = new BufferedWriter(isr);) {
String suggestedPath = "name/version/release/data/";
br.write("# note, " + suggestedPath + " is value which can (however unlikely) change in time\n");
br.write("# lines are trimmed before processing, and empty and # starting lines are skipped. First non # non empty line is considered as arches line and splitted on \\s+, returned, reading stopped \n");
br.write("
br.write("# this configfile contains architectures the build/project should be built\n");
br.write("# it can be palced as " + suggestedPath + "" + archesConfigFileName + "\n");
br.write("# where it takes priority, so you can configure *single* build to built on exacta architectures\n");
br.write("# if this single-build do not exists, then it is tried in name/" + archesConfigFileName + "\n");
br.write("# by doing so, you can configure a product to buitl on some architectures (unles its build specifies differently)\n");
br.write("# eg java-1.{7,9}.0-openjdk are supposed to build on x86_64, i686 and windows. However those from icedtea7-forest, aarch64/jdk8 and aarch64/shenandoah should build also on aarch64\n");
br.write("# in addition java-9-openjdk is supposedto build on x86_64, i686 and windows AND aarch64\n");
br.write("# last place where to search config is /name-" + archesConfigFileName + ". Eg java-1.8.0-openjdk-" + archesConfigFileName + ", where / is root of fake-koji.\n");
br.write("# This last configutration was added, as fake koji dont like files where only dirs should be (it works fine but...)\n");
br.write("
br.write("# Now, to enable per-project (== per forest) settings, the \n");
br.write("# TckScripts/jenkins/static/tempt-ojdk-repo.sh\n");
br.write("# always copy (if exists) project-name/" + archesConfigFileName + " togetehr with uploading src.tarxz to its " + suggestedPath + "\n");
br.write("# Please always keep comment here describing above, and explaining why listed arches are there.\n");
br.write("# generated from: "+System.getProperty("user.dir"));
br.write("# Defualt (hardcoded) arches are now: \n");
br.write("\n");
br.write(" ");
for (String arch : defaultSupportedArchs) {
br.write(arch + " ");
}
br.write("\n");
br.flush();
}
}
private static String[] readArchesFile(File f) throws IOException {
try (
InputStream fis = new FileInputStream(f);
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);) {
while (true) {
String line = br.readLine();
if (line == null) {
return null;
}
if (line.trim().startsWith("
continue;
}
if (line.trim().isEmpty()) {
continue;
}
String[] r = line.trim().split("\\s+");
return r;
}
}
}
}
|
package org.cnodejs.android.md.model.storage;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import org.cnodejs.android.md.util.Digest;
import java.util.UUID;
public final class DeviceInfo {
private DeviceInfo() {}
private static final String TAG = "DeviceInfo";
private static final String KEY_DEVICE_TOKEN = "deviceToken";
private volatile static String deviceToken = null;
private static SharedPreferences getSharedPreferences(@NonNull Context context) {
return context.getSharedPreferences(Digest.MD5.getHex(TAG), Context.MODE_PRIVATE);
}
@NonNull
public static String getDeviceToken(@NonNull Context context) {
if (TextUtils.isEmpty(deviceToken)) {
synchronized (DeviceInfo.class) {
if (TextUtils.isEmpty(deviceToken)) {
deviceToken = getSharedPreferences(context).getString(KEY_DEVICE_TOKEN, null);
}
if (TextUtils.isEmpty(deviceToken)) {
deviceToken = UUID.randomUUID().toString();
getSharedPreferences(context).edit().putString(KEY_DEVICE_TOKEN, deviceToken).apply();
}
}
}
return deviceToken;
}
}
|
package org.jatronizer.configurator;
import javax.naming.ConfigurationException;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.util.*;
final class ConfigSupport {
// Static class without instances, constructor is hidden
private ConfigSupport() {}
/**
* Retrieves the value of field from obj, attempts to set field to accessible if it is not.
* @param field
* @param obj
* @return
*/
static Object retrieve(Field field, Object obj) {
try {
if (!field.isAccessible()) {
// NOTE making field accessible is not reverted later.
field.setAccessible(true);
}
return field.get(obj);
} catch (Exception e) {
throw new ConfigException(field.toString() + " could not be accessed", e);
}
}
private static void addConfig(Collection<ConfigParameter> dest, String keyPrefix, Object conf) {
Class cc = conf.getClass();
if (keyPrefix == null) {
keyPrefix = "";
}
for (Field f : cc.getDeclaredFields()) {
addField(dest, keyPrefix, f, conf);
}
}
private static void addField(Collection<ConfigParameter> dest, String keyPrefix, Field f, Object conf) {
Parameter p = f.getAnnotation(Parameter.class);
if (p == null) {
return;
}
if (p.container()) {
Object subconf = retrieve(f, conf);
if (subconf == null) {
throw new ConfigException("configuration field " + f.getName() + keyPrefix + " is null");
}
addConfig(dest, keyPrefix + p.key(), subconf);
return;
}
String key = p.key();
if ("".equals(key)) {
key = f.getName();
}
dest.add(ConfigParameterField.create(
conf,
f,
keyPrefix + key,
p.tag(),
p.converter()
));
}
/**
* Fetches all fields annotated with {@link Parameter} from {@code configuration}.
* @param configuration An instance with {@code Parameter} annotated fields, must not be {@code null}.
* @param keyPrefix A prefix for all keys representing the parameters.
* @return The configuration parameters contained in the specified configuration.
*/
public static ConfigParameter[] fetchParameters(Object configuration, String keyPrefix) {
Class cc = configuration.getClass();
ArrayList<ConfigParameter> params = new ArrayList<ConfigParameter>();
addConfig(params, keyPrefix, configuration);
if (params.isEmpty()) {
throw new ConfigException(
"" + cc + " contains no configurations or parameters"
);
}
ConfigParameter[] parameters = params.toArray(new ConfigParameter[params.size()]);
Arrays.sort(parameters, new Comparator<ConfigParameter>() {
public int compare(ConfigParameter o1, ConfigParameter o2) {
return o1.key().compareTo(o2.key());
}
});
return parameters;
}
public interface KeyFormatter {
String from(String key);
}
public enum KeyFormat implements KeyFormatter {
arg {
public String from(String key) {
return formatKey(key, "-").replaceAll("--+", "-").toLowerCase();
}
},
env {
public String from(String key) {
return formatKey(key, "_").replaceAll("__+", "-").toUpperCase();
}
};
private static String formatKey(String key, String separator) {
return key
// prefix each sequence of capital letters with separator
.replaceAll("([A-Z]+)", separator + "$1")
// change all non alphanumeric char sequences to separator
.replaceAll("[^A-Za-z0-9]+", separator)
;
}
}
/**
* Retrieves the description of elem if it is annotated with {@link Description}.
* @param elem The element with a {@code Description} annotation.
* @return value of the {@code Description} or {@code ""};
*/
public static String description(AnnotatedElement elem) {
Description d = elem.getAnnotation(Description.class);
if (d == null) {
return "";
}
return d.value();
}
public static String[] collisions(KeyFormatter format, String[] keys) {
HashMap<String, String> map = new HashMap<String, String>(keys.length, 1.0f);
ArrayList<String> collisions = new ArrayList<String>();
for (String key : keys) {
String mapped = format.from(key);
String clashing = map.get(mapped);
if (clashing != null) {
if (!collisions.contains(clashing)) {
collisions.add(clashing);
}
collisions.add(key);
}
map.put(mapped, key);
}
String[] result = collisions.toArray(new String[collisions.size()]);
Arrays.sort(result);
return result;
}
public static int values(
Map<String, String> dest,
String[] keys,
String keyPrefix,
KeyFormatter format,
Map<String, String> src) {
if (keyPrefix == null) {
keyPrefix = "";
}
int numSet = 0;
for (String key : keys) {
String mapped = format.from(keyPrefix + key);
String value = src.get(mapped);
if (value != null) {
if (dest != null) {
dest.put(key, value);
}
numSet++;
}
}
return numSet;
}
public static int parseValues(
Map<String, String> dest,
Collection<String> destUnused,
String[] keys,
String keyPrefix,
KeyFormatter format,
String[] src) {
if (keyPrefix == null) {
keyPrefix = "";
}
HashMap<String, String> map = new HashMap<String, String>(keys.length, 1.0f);
for (String key : keys) {
map.put(format.from(keyPrefix + key), key);
}
int numSet = 0;
for (String raw : src) {
String[] pair = raw.split("=", 2);
switch (pair.length) {
case 1:
if (map.containsKey(raw)) {
// handle booleans without requiring "=true"
if (dest != null) {
dest.put(map.get(raw), "true");
}
numSet++;
continue;
}
break;
case 2:
if (map.containsKey(pair[0])) {
if (dest != null) {
dest.put(map.get(pair[0]), pair[1]);
}
numSet++;
continue;
}
break;
}
destUnused.add(raw);
}
return numSet;
}
}
|
package org.stepic.droid.ui.adapters;
import android.app.Activity;
import android.graphics.Point;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.AppCompatRadioButton;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.CompoundButton;
import org.jetbrains.annotations.NotNull;
import org.stepic.droid.R;
import org.stepic.droid.model.TableChoiceAnswer;
import org.stepic.droid.ui.custom.ProgressLatexView;
import org.stepic.droid.ui.listeners.CheckedChangeListenerWithPosition;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class TableChoiceAdapter extends RecyclerView.Adapter<TableChoiceAdapter.GenericViewHolder> implements CheckedChangeListenerWithPosition {
private static final int DESCRIPTION_TYPE = 0;
private static final int CHECKBOX_TYPE = 1;
private static final int RADIO_BUTTON_TYPE = 2;
private static final int ROW_HEADER_TYPE = 3;
private static final int COLUMN_HEADER_TYPE = 4;
private final List<String> columns;
private final List<String> rows;
private final String description;
private final boolean isCheckbox;
private final List<TableChoiceAnswer> answers;
private final int doublePadding;
private final int minUXTouchableSize;
private final int deviceWidthPx75Percent;
private boolean isAllEnabled = true;
@Override
public int getItemViewType(int position) {
if (position == 0) {
return DESCRIPTION_TYPE;
} else if (position <= rows.size()) {
return ROW_HEADER_TYPE;
} else if (position % (rows.size() + 1) == 0) {
return COLUMN_HEADER_TYPE;
} else if (isCheckbox) {
return CHECKBOX_TYPE;
} else {
return RADIO_BUTTON_TYPE;
}
}
public TableChoiceAdapter(Activity context, List<String> rows, List<String> columns, String description, boolean isCheckbox, List<TableChoiceAnswer> answers) {
this.columns = columns;
this.rows = rows;
this.description = description;
this.isCheckbox = isCheckbox;
this.answers = answers;
Display display = context.getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
deviceWidthPx75Percent = (int) (size.x * 0.75);
doublePadding = (int) context.getResources().getDimension(R.dimen.half_padding) * 2;
minUXTouchableSize = (int) context.getResources().getDimension(R.dimen.min_ux_touchable_size);
}
@Override
public GenericViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == RADIO_BUTTON_TYPE) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_table_quiz_radio_button_cell, parent, false);
return new RadioButtonCellViewHolder(v, this);
} else if (viewType == CHECKBOX_TYPE) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_table_quiz_checkbox_cell, parent, false);
return new CheckboxCellViewHolder(v, this);
} else if (viewType == DESCRIPTION_TYPE || viewType == ROW_HEADER_TYPE || viewType == COLUMN_HEADER_TYPE) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_table_quiz_text_cell, parent, false);
final DescriptionViewHolder descriptionViewHolder = new DescriptionViewHolder(v);
descriptionViewHolder.latexView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
int localWidth = descriptionViewHolder.latexView.getMeasuredWidthOfInnerLayout() + doublePadding;
if (localWidth > deviceWidthPx75Percent) {
descriptionViewHolder.latexView.getLayoutParams().width = Math.min(Math.max(localWidth, minUXTouchableSize), deviceWidthPx75Percent);
descriptionViewHolder.latexView.getViewTreeObserver().removeOnPreDrawListener(this);
}
return true;
}
});
return descriptionViewHolder;
} else {
throw new IllegalStateException("viewType with index " + viewType + " is not supported in table quiz");
}
}
@Override
public void onBindViewHolder(GenericViewHolder holder, int position) {
int itemViewType = getItemViewType(position);
if (itemViewType == DESCRIPTION_TYPE) {
holder.setData(description);
} else if (itemViewType == ROW_HEADER_TYPE) {
String headerText = rows.get(position - 1);
holder.setData(headerText);
} else if (itemViewType == COLUMN_HEADER_TYPE) {
int columnPosition = getColumnPosition(position); // -1 is description cell at top left cell
String headerText = columns.get(columnPosition);
holder.setData(headerText);
} else {
List<TableChoiceAnswer.Companion.Cell> oneRowAnswers = getOneRowAnswersFromPosition(position);
int columnPosition = getColumnPosition(position);
TableChoiceAnswer.Companion.Cell cell = oneRowAnswers.get(columnPosition);
holder.setData(cell.getAnswer());
}
holder.makeEnabled(isAllEnabled);
}
private int getColumnPosition(int position) {
return position / (rows.size() + 1) - 1;
}
private List<TableChoiceAnswer.Companion.Cell> getOneRowAnswersFromPosition(int position) {
int rowPosition = (position - 1) % (rows.size() + 1);
TableChoiceAnswer tableChoiceAnswer = answers.get(rowPosition);
return tableChoiceAnswer.getColumns();
}
@Override
public int getItemCount() {
return rows.size() + columns.size() + 1 + rows.size() * columns.size();
}
@Override
public void onCheckedChanged(CompoundButton view, boolean isChecked, int position) {
List<TableChoiceAnswer.Companion.Cell> oneRowAnswers = getOneRowAnswersFromPosition(position);
int columnPosition = getColumnPosition(position);
int multiplier = rows.size() + 1;
int remainder = position % multiplier;
List<Integer> changed = new ArrayList<>();
if (!isCheckbox && isChecked) {
//radio button, check something -> uncheck others
int i = 1;
for (TableChoiceAnswer.Companion.Cell eachCellInRow : oneRowAnswers) {
if (eachCellInRow.getAnswer()) {
//if something is checked
int currentAdapterPosition = multiplier * i + remainder;
eachCellInRow.setAnswer(false);
if (currentAdapterPosition != position) {
changed.add(currentAdapterPosition);
}
}
i++;
}
}
// change checked state
TableChoiceAnswer.Companion.Cell cell = oneRowAnswers.get(columnPosition);
cell.setAnswer(isChecked);
if (!changed.isEmpty()) {
for (Integer changedPosition : changed) {
notifyItemChanged(changedPosition); // In the perfect world there is only one for radiobutton
}
}
}
public void setAllItemsEnabled(boolean isAllEnabled) {
this.isAllEnabled = isAllEnabled;
int i = rows.size() + 2; // the first option cell element
while (i < getItemCount()) {
notifyItemRangeChanged(i, rows.size());
i += rows.size() + 1;
}
}
static abstract class GenericViewHolder extends RecyclerView.ViewHolder {
GenericViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public abstract void setData(@NotNull String text);
public abstract void setData(@NotNull Boolean needCheckModel);
public abstract void makeEnabled(boolean isAllEnabled);
}
static class DescriptionViewHolder extends GenericViewHolder {
@BindView(R.id.cell_text)
ProgressLatexView latexView;
DescriptionViewHolder(View itemView) {
super(itemView);
}
@Override
public void setData(@NotNull String text) {
latexView.setAnyText(text);
}
@Override
public void setData(@NotNull Boolean needCheck) {
throw new IllegalStateException("description view can't be without text, check position");
}
@Override
public void makeEnabled(boolean isAllEnabled) {
//do nothing, it is not interactable by user
}
}
static abstract class CompoundButtonViewHolder extends GenericViewHolder {
@BindView(R.id.container)
ViewGroup container;
CompoundButtonViewHolder(View itemView, final CheckedChangeListenerWithPosition checkedChangeListenerWithPosition) {
super(itemView);
getCheckableView().setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.isPressed()) {
checkedChangeListenerWithPosition.onCheckedChanged(buttonView, isChecked, getAdapterPosition());
}
}
});
container.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return getCheckableView().dispatchTouchEvent(event);
}
});
}
@Override
public final void setData(@NotNull String text) {
throw new IllegalStateException("text is not allowed in table view quiz");
}
@Override
public final void setData(@NotNull Boolean needCheckModel) {
getCheckableView().setChecked(needCheckModel);
}
@Override
public void makeEnabled(boolean isEnabled) {
container.setClickable(isEnabled);
getCheckableView().setClickable(isEnabled);
}
abstract CompoundButton getCheckableView();
}
static class CheckboxCellViewHolder extends CompoundButtonViewHolder {
@BindView(R.id.checkbox_cell)
AppCompatCheckBox checkBox;
CheckboxCellViewHolder(View itemView, CheckedChangeListenerWithPosition checkedChangeListenerWithPosition) {
super(itemView, checkedChangeListenerWithPosition);
}
@Override
CompoundButton getCheckableView() {
return checkBox;
}
}
static class RadioButtonCellViewHolder extends CompoundButtonViewHolder {
@BindView(R.id.radio_button_cell)
AppCompatRadioButton radioButton;
RadioButtonCellViewHolder(View itemView, final CheckedChangeListenerWithPosition checkedChangeListenerWithPosition) {
super(itemView, checkedChangeListenerWithPosition);
}
@Override
CompoundButton getCheckableView() {
return radioButton;
}
}
}
|
package org.exist.dom;
/**
* Used to track fulltext matches throughout the query.
*
* {@link org.exist.storage.TextSearchEngine} will add a
* match object to every {@link org.exist.dom.NodeProxy}
* that triggered a fulltext match for every term matched. The
* Match object contains the nodeId of the text node that triggered the
* match, the string value of the matching term and a frequency count,
* indicating the frequency of the matching term string within the corresponding
* single text node.
*
* All path operations copy existing match objects, i.e. the match objects
* are copied to the selected descendant or child nodes. This means that
* every NodeProxy being the direct or indirect result of a fulltext
* selection will have one or more match objects, indicating which text nodes
* among its descendant nodes contained a fulltext match.
*
* @author wolf
*/
public class Match implements Comparable {
private String matchTerm;
private long nodeId;
private int frequency = 1;
protected Match nextMatch = null;
protected Match prevMatch = null;
public Match(String matchTerm, long nodeId) {
this.matchTerm = matchTerm;
this.nodeId = nodeId;
}
public Match(Match match) {
this.matchTerm = match.matchTerm;
this.nodeId = match.nodeId;
this.frequency = match.frequency;
}
public String getMatchingTerm() {
return matchTerm;
}
public long getNodeId() {
return nodeId;
}
public void setFrequency(int freq) {
this.frequency = freq;
}
public int getFrequency() {
return frequency;
}
public Match getNextMatch() {
return nextMatch;
}
public boolean equals(Object other) {
if(!(other instanceof Match))
return false;
return ((Match)other).matchTerm.equals(matchTerm) &&
((Match)other).nodeId == nodeId;
}
/**
* Used to sort matches. Terms are compared by their string
* length to have the longest string first.
*
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(Object o) {
Match other = (Match)o;
return matchTerm.compareTo(other.matchTerm);
}
}
|
package org.joml;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.text.DecimalFormat;
import java.text.NumberFormat;
/**
* Represents a 2D axis-aligned rectangle.
*
* @author Kai Burjack
*/
public class Rectanglei implements Externalizable {
/**
* The x coordinate of the minimum corner.
*/
public int minX;
/**
* The y coordinate of the minimum corner.
*/
public int minY;
/**
* The x coordinate of the maximum corner.
*/
public int maxX;
/**
* The y coordinate of the maximum corner.
*/
public int maxY;
/**
* Create a new {@link Rectanglei} with a minimum and maximum corner of <code>(0, 0)</code>.
*/
public Rectanglei() {
}
/**
* Create a new {@link Rectanglei} as a copy of the given <code>source</code>.
*
* @param source
* the {@link Rectanglei} to copy from
*/
public Rectanglei(Rectanglei source) {
this.minX = source.minX;
this.minY = source.minY;
this.maxX = source.maxX;
this.maxY = source.maxY;
}
/**
* Create a new {@link Rectanglei} with the given <code>min</code> and <code>max</code> corner coordinates.
*
* @param min
* the minimum coordinates
* @param max
* the maximum coordinates
*/
public Rectanglei(Vector2ic min, Vector2ic max) {
this.minX = min.x();
this.minY = min.y();
this.maxX = max.x();
this.maxY = max.y();
}
/**
* Create a new {@link Rectanglei} with the given minimum and maximum corner coordinates.
*
* @param minX
* the x coordinate of the minimum corner
* @param minY
* the y coordinate of the minimum corner
* @param maxX
* the x coordinate of the maximum corner
* @param maxY
* the y coordinate of the maximum corner
*/
public Rectanglei(int minX, int minY, int maxX, int maxY) {
this.minX = minX;
this.minY = minY;
this.maxX = maxX;
this.maxY = maxY;
}
/**
* Return the length of the rectangle in the X dimension.
*
* @return length in the X dimension
*/
public int lengthX() {
return maxX - minX;
}
/**
* Return the length of the rectangle in the Y dimension.
*
* @return length in the Y dimension
*/
public int lengthY() {
return maxY - minY;
}
/**
* Return the area of the rectangle
*
* @return area
*/
public int area() {
return lengthX() * lengthY();
}
/**
* Check if this and the given rectangle intersect.
*
* @param other
* the other rectangle
* @return <code>true</code> iff both rectangles intersect; <code>false</code> otherwise
*/
public boolean intersects(Rectangled other) {
return minX < other.maxX && maxX >= other.minX &&
maxY >= other.minY && minY < other.maxY;
}
/**
* Check if this and the given rectangle intersect.
*
* @param other
* the other rectangle
* @return <code>true</code> iff both rectangles intersect; <code>false</code> otherwise
*/
public boolean intersects(Rectanglef other) {
return minX < other.maxX && maxX >= other.minX &&
maxY >= other.minY && minY < other.maxY;
}
/**
* Check if this and the given rectangle intersect.
*
* @param other
* the other rectangle
* @return <code>true</code> iff both rectangles intersect; <code>false</code> otherwise
*/
public boolean intersects(Rectanglei other) {
return minX < other.maxX && maxX >= other.minX &&
maxY >= other.minY && minY < other.maxY;
}
private Rectanglei validate() {
if (!isValid()) {
minX = Integer.MAX_VALUE;
minY = Integer.MAX_VALUE;
maxX = Integer.MIN_VALUE;
maxY = Integer.MIN_VALUE;
}
return this;
}
/**
* Check whether <code>this</code> rectangle represents a valid rectangle.
*
* @return <code>true</code> iff this rectangle is valid; <code>false</code> otherwise
*/
public boolean isValid() {
return minX < maxX && minY < maxY;
}
/**
* Compute the rectangle of intersection between <code>this</code> and the given rectangle.
* <p>
* If the two rectangles do not intersect, then the minimum coordinates of <code>this</code>
* will have a value of {@link Integer#MAX_VALUE} and the maximum coordinates will have a value of
* {@link Integer#MIN_VALUE}.
*
* @param other
* the other rectangle
* @return this
*/
public Rectanglei intersection(Rectanglei other) {
return intersection(other, this);
}
/**
* Compute the rectangle of intersection between <code>this</code> and the given rectangle and
* store the result in <code>dest</code>.
* <p>
* If the two rectangles do not intersect, then the minimum coordinates of <code>dest</code>
* will have a value of {@link Integer#MAX_VALUE} and the maximum coordinates will have a value of
* {@link Integer#MIN_VALUE}.
*
* @param other
* the other rectangle
* @param dest
* will hold the result
* @return dest
*/
public Rectanglei intersection(Rectanglei other, Rectanglei dest) {
dest.minX = Math.max(minX, other.minX);
dest.minY = Math.max(minY, other.minY);
dest.maxX = Math.min(maxX, other.maxX);
dest.maxY = Math.min(maxY, other.maxY);
return dest.validate();
}
/**
* Return the length of this rectangle in the X and Y dimensions and store the result in <code>dest</code>.
*
* @param dest
* will hold the result
* @return dest
*/
public Vector2i lengths(Vector2i dest) {
return dest.set(lengthX(), lengthY());
}
/**
* Check if this rectangle contains the given <code>rectangle</code>.
*
* @param rectangle
* the rectangle to test
* @return <code>true</code> iff this rectangle contains the rectangle; <code>false</code> otherwise
*/
public boolean contains(Rectangled rectangle) {
return rectangle.minX >= minX && rectangle.maxX <= maxX &&
rectangle.minY >= minY && rectangle.maxY <= maxY;
}
/**
* Check if this rectangle contains the given <code>rectangle</code>.
*
* @param rectangle
* the rectangle to test
* @return <code>true</code> iff this rectangle contains the rectangle; <code>false</code> otherwise
*/
public boolean contains(Rectanglef rectangle) {
return rectangle.minX >= minX && rectangle.maxX <= maxX &&
rectangle.minY >= minY && rectangle.maxY <= maxY;
}
/**
* Check if this rectangle contains the given <code>rectangle</code>.
*
* @param rectangle
* the rectangle to test
* @return <code>true</code> iff this rectangle contains the rectangle; <code>false</code> otherwise
*/
public boolean contains(Rectanglei rectangle) {
return rectangle.minX >= minX && rectangle.maxX <= maxX &&
rectangle.minY >= minY && rectangle.maxY <= maxY;
}
/**
* Check if this rectangle contains the given <code>point</code>.
*
* @param point
* the point to test
* @return <code>true</code> iff this rectangle contains the point; <code>false</code> otherwise
*/
public boolean contains(Vector2ic point) {
return contains(point.x(), point.y());
}
/**
* Check if this rectangle contains the given point <code>(x, y)</code>.
*
* @param x
* the x coordinate of the point to check
* @param y
* the y coordinate of the point to check
* @return <code>true</code> iff this rectangle contains the point; <code>false</code> otherwise
*/
public boolean contains(int x, int y) {
return x >= minX && y >= minY && x < maxX && y < maxY;
}
/**
* Translate <code>this</code> by the given vector <code>xy</code>.
*
* @param xy
* the vector to translate by
* @return this
*/
public Rectanglei translate(Vector2ic xy) {
return translate(xy.x(), xy.y(), this);
}
/**
* Translate <code>this</code> by the given vector <code>xy</code> and store the result in <code>dest</code>.
*
* @param xy
* the vector to translate by
* @param dest
* will hold the result
* @return dest
*/
public Rectanglei translate(Vector2ic xy, Rectanglei dest) {
return translate(xy.x(), xy.y(), dest);
}
/**
* Translate <code>this</code> by the vector <code>(x, y)</code>.
*
* @param x
* the x coordinate to translate by
* @param y
* the y coordinate to translate by
* @return this
*/
public Rectanglei translate(int x, int y) {
return translate(x, y, this);
}
/**
* Translate <code>this</code> by the vector <code>(x, y)</code> and store the result in <code>dest</code>.
*
* @param x
* the x coordinate to translate by
* @param y
* the y coordinate to translate by
* @param dest
* will hold the result
* @return dest
*/
public Rectanglei translate(int x, int y, Rectanglei dest) {
dest.minX = minX + x;
dest.minY = minY + y;
dest.maxX = maxX + x;
dest.maxY = maxY + y;
return dest;
}
/**
* Scale <code>this</code> about the origin.
*
* @param sf
* the scaling factor in the x and y axis.
* @return this
*/
public Rectanglei scale(int sf) {
return scale(sf, sf);
}
/**
* Scale <code>this</code> about the origin and store the result in <code>dest</code>.
*
* @param sf
* the scaling factor in the x and y axis
* @param dest
* will hold the result
* @return dest
*/
public Rectanglei scale(int sf, Rectanglei dest) {
return scale(sf, sf, dest);
}
/**
* Scale <code>this</code> about an anchor.
* <p>
* This is effectively equivalent to <br>
* <pre>
* translate(-ax, -ay);
* scale(sf);
* translate(ax, ay);
* </pre>
*
* @param sf
* the scaling factor in the x and y axis
* @param ax
* the x coordinate of the anchor
* @param ay
* the y coordinate of the anchor
* @return this
*/
public Rectanglei scale(int sf, int ax, int ay) {
return scale(sf, sf, ax, ay);
}
/**
* Scale <code>this</code> about an anchor and store the result in <code>dest</code>.
* <p>
* This is effectively equivalent to <br>
* <pre>
* translate(-ax, -ay);
* scale(sf);
* translate(ax, ay);
* </pre>
*
* @param sf
* the scaling factor in the x and y axis
* @param ax
* the x coordinate of the anchor
* @param ay
* the y coordinate of the anchor
* @param dest
* will hold the result
* @return dest
*/
public Rectanglei scale(int sf, int ax, int ay, Rectanglei dest) {
return scale(sf, sf, ax, ay, dest);
}
/**
* Scale <code>this</code> about an anchor.
* <p>
* This is effectively equivalent to <br>
* <pre>
* translate(anchor.negate());
* scale(sf);
* translate(anchor.negate());
* </pre>
*
* @param sf
* the scaling factor in the x and y axis
* @param anchor
* the location of the anchor
* @return this
*/
public Rectanglei scale(int sf, Vector2ic anchor) {
return scale(sf, anchor.x(), anchor.y());
}
/**
* Scale <code>this</code> about an anchor and store the result in <code>dest</code>.
* <p>
* This is effectively equivalent to <br>
* <pre>
* translate(anchor.negate());
* scale(sf);
* translate(anchor.negate());
* </pre>
*
* @param sf
* the scaling factor in the x and y axis
* @param anchor
* the location of the anchor
* @param dest
* will hold the result
* @return dest
*/
public Rectanglei scale(int sf, Vector2ic anchor, Rectanglei dest) {
return scale(sf, anchor.x(), anchor.y(), dest);
}
/**
* Scale <code>this</code> about the origin.
*
* @param sx
* the scaling factor on the x axis
* @param sy
* the scaling factor on the y axis
* @return this
*/
public Rectanglei scale(int sx, int sy) {
return scale(sx, sy, 0, 0);
}
/**
* Scale <code>this</code> about the origin and store the result in <code>dest</code>.
*
* @param sx
* the scaling factor on the x axis
* @param sy
* the scaling factor on the y axis
* @param dest
* will hold the result
* @return dest
*/
public Rectanglei scale(int sx, int sy, Rectanglei dest) {
return scale(sx, sy, 0, 0, dest);
}
/**
* Scale <code>this</code> about an anchor.
* This is equivalent to <br>
* <pre>
* translate(-ax, -ay);
* scale(sx, sy);
* translate(ax, ay);
* </pre>
*
* @param sx
* the scaling factor on the x axis
* @param sy
* the scaling factor on the y axis
* @param ax
* the x coordinate of the anchor
* @param ay
* the y coordinate of the anchor
* @return this
*/
public Rectanglei scale(int sx, int sy, int ax, int ay) {
minX = (minX - ax) * sx + ax;
minY = (minY - ay) * sy + ay;
maxX = (maxX - ax) * sx + ax;
maxY = (maxY - ay) * sy + ay;
return this;
}
/**
* Scale <code>this</code> about an anchor.
* <p>
* This is equivalent to <br>
* <pre>
* translate(anchor.negate());
* scale(sx, sy);
* translate(anchor.negate());
* </pre>
*
* @param sx
* the scaling factor on the x axis
* @param sy
* the scaling factor on the y axis
* @param anchor
* the location of the anchor
* @return this
*/
public Rectanglei scale(int sx, int sy, Vector2ic anchor) {
return scale(sx, sy, anchor.x(), anchor.y());
}
/**
* Scale <code>this</code> about an anchor and store the result in <code>dest</code>.
* <p>
* This is equivalent to <br>
* <pre>
* translate(-ax, -ay);
* scale(sx, sy);
* translate(ax, ay);
* </pre>
*
* @param sx
* the scaling factor on the x axis
* @param sy
* the scaling factor on the y axis
* @param ax
* the x coordinate of the anchor
* @param ay
* the y coordinate of the anchor
* @param dest
* will hold the result
* @return dest
*/
public Rectanglei scale(int sx, int sy, int ax, int ay, Rectanglei dest) {
dest.minX = (minX - ax) * sx + ax;
dest.minY = (minY - ay) * sy + ay;
dest.maxX = (maxX - ax) * sx + ax;
dest.maxY = (maxY - ay) * sy + ay;
return dest;
}
/**
* Scale <code>this</code> about an anchor and store the result in <code>dest</code>.
* <p>
* This is equivalent to <br>
* <pre>
* translate(anchor.negate());
* scale(sx, sy);
* translate(anchor.negate());
* </pre>
*
* @param sx
* the scaling factor on the x axis
* @param sy
* the scaling factor on the y axis
* @param anchor
* the location of the anchor
* @param dest
* will hold the result
* @return dest
*/
public Rectanglei scale(int sx, int sy, Vector2ic anchor, Rectanglei dest) {
return scale(sx, sy, anchor.x(), anchor.y(), dest);
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + maxX;
result = prime * result + maxY;
result = prime * result + minX;
result = prime * result + minY;
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Rectanglei other = (Rectanglei) obj;
if (maxX != other.maxX)
return false;
if (maxY != other.maxY)
return false;
if (minX != other.minX)
return false;
if (minY != other.minY)
return false;
return true;
}
/**
* Return a string representation of this rectangle.
* <p>
* This method creates a new {@link DecimalFormat} on every invocation with the format string "<code>0.000E0;-</code>".
*
* @return the string representation
*/
public String toString() {
return Runtime.formatNumbers(toString(Options.NUMBER_FORMAT));
}
/**
* Return a string representation of this rectangle by formatting the vector components with the given {@link NumberFormat}.
*
* @param formatter
* the {@link NumberFormat} used to format the vector components with
* @return the string representation
*/
public String toString(NumberFormat formatter) {
return "(" + formatter.format(minX) + " " + formatter.format(minY) + ") < "
+ "(" + formatter.format(maxX) + " " + formatter.format(maxY) + ")";
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(minX);
out.writeInt(minY);
out.writeInt(maxX);
out.writeInt(maxY);
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
minX = in.readInt();
minY = in.readInt();
maxX = in.readInt();
maxY = in.readInt();
}
}
|
package org.jgroups.protocols.google;
import com.google.cloud.storage.*;
import org.jgroups.Address;
import org.jgroups.annotations.Property;
import org.jgroups.conf.ClassConfigurator;
import org.jgroups.protocols.FILE_PING;
import org.jgroups.protocols.PingData;
import org.jgroups.util.Responses;
import org.jgroups.util.Util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;
public class GOOGLE_PING2 extends FILE_PING {
protected static final short GOOGLE_PING_ID=2018;
static {
ClassConfigurator.addProtocol(GOOGLE_PING_ID, GOOGLE_PING2.class);
}
@Property(description="The region (eu, asia, us) where the bucket will be created. If non-null, the storage class " +
"will be multi-regional, else regional")
protected String region;
@Property(description="Creates the bucket if it doesn't exist")
protected boolean create_bucket_if_not_exists=true;
protected Storage store; // client to access GCS
protected Bucket bucket; // the bucket to be used; all objects are in this bucket
@Override
public void init() throws Exception {
super.init();
if(location == null)
throw new IllegalStateException("location must be set");
store=StorageOptions.getDefaultInstance().getService();
// Fetch the existing bucket: this either returns null (bucket doesn't exist), or throws an exception
// (e.g. if the bucket is owned by a different user)
bucket=store.get(location);
if(bucket == null) {
if(!create_bucket_if_not_exists)
throw new IllegalStateException("bucket " + location + " doesn't exist");
BucketInfo info=region == null? BucketInfo.of(location)
: BucketInfo.newBuilder(location).setStorageClass(StorageClass.REGIONAL).setLocation(this.region).build();
bucket=store.create(info);
}
}
@Override
protected void createRootDir() {
; // do *not* create root file system (don't remove !)
}
@Override
protected void readAll(List<Address> members, String clustername, Responses responses) {
if(clustername == null)
return;
try {
clustername=sanitize(clustername);
for(Blob blob: bucket.list(Storage.BlobListOption.prefix(clustername)).iterateAll()) {
String name=blob.getName();
if(name.endsWith(SUFFIX)) {
byte[] contents=blob.getContent();
readResponse(contents, members, responses);
}
}
}
catch(Exception ex) {
log.error(Util.getMessage("FailedReadingAddresses"), ex);
}
}
protected void readResponse(byte[] buf, List<Address> mbrs, Responses responses) {
if(buf != null && buf.length > 0) {
try {
List<PingData> list=read(new ByteArrayInputStream(buf));
if(list != null) {
for(PingData data : list) {
if(mbrs == null || mbrs.contains(data.getAddress()))
responses.addResponse(data, data.isCoord());
if(local_addr != null && !local_addr.equals(data.getAddress()))
addDiscoveryResponseToCaches(data.getAddress(), data.getLogicalName(), data.getPhysicalAddr());
}
}
}
catch(Throwable e) {
log.error(Util.getMessage("FailedUnmarshallingResponse"), e);
}
}
}
@Override
protected void write(List<PingData> list, String clustername) {
String filename=addressToFilename(local_addr);
String key=sanitize(clustername) + "/" + sanitize(filename);
try {
ByteArrayOutputStream out=new ByteArrayOutputStream(4096);
write(list, out);
byte[] data=out.toByteArray();
bucket.create(key, data);
} catch (Exception e) {
log.error(Util.getMessage("ErrorMarshallingObject"), e);
}
}
protected void remove(String clustername, Address addr) {
if(clustername == null || addr == null)
return;
String filename=addressToFilename(addr);// addr instanceof org.jgroups.util.UUID? ((org.jgroups.util.UUID)addr).toStringLong() : addr.toString();
String key=sanitize(clustername) + "/" + sanitize(filename);
try {
BlobId obj=BlobId.of(location, key);
boolean success=store.delete(obj);
if(log.isTraceEnabled())
log.trace("removed %s/%s, success: %b", location, key, success);
}
catch(Exception e) {
log.error(Util.getMessage("FailureRemovingData"), e);
}
}
@Override
protected void removeAll(String clustername) {
if(clustername == null)
return;
try {
for(Blob blob: bucket.list(Storage.BlobListOption.prefix(clustername)).iterateAll()) {
String name=blob.getName();
if(name.endsWith(".list")) {
blob.delete();
}
}
// store.delete(BlobId.of(location, clustername)); // also delete the top folder for the cluster name
}
catch(Exception ex) {
log.error(Util.getMessage("FailedDeletingAllObjects"), ex);
}
}
/** Sanitizes bucket and folder names according to AWS guidelines */
protected static String sanitize(final String name) {
return name.replace('/', '-').replace('\\', '-');
}
}
|
package org.sqlite;
import org.ibex.nestedvm.Runtime;
import java.io.File;
import java.io.PrintWriter;
import java.sql.*;
// FEATURE: strdup is wasteful, SQLite interface will take unterminated char*
/** Communicates with the Java version of SQLite provided by NestedVM. */
final class NestedDB extends DB implements Runtime.CallJavaCB
{
/** database pointer */
int handle = 0;
/** sqlite binary embedded in nestedvm */
private Runtime rt = null;
/** user defined functions referenced by position (stored in used data) */
private Function[] functions = null;
private String[] funcNames = null;
// WRAPPER FUNCTIONS ////////////////////////////////////////////
synchronized void open(String filename) throws SQLException {
if (handle != 0) throw new SQLException("DB already open");
if (rt != null) throw new SQLException("DB closed but runtime exists");
// handle silly windows drive letter mapping
if (filename.length() > 2) {
char drive = Character.toLowerCase(filename.charAt(0));
if (filename.charAt(1) == ':' && drive >= 'a' && drive <= 'z') {
// convert to nestedvm's "/c:/file" format
filename = filename.substring(2);
filename = filename.replace('\\', '/');
filename = "/" + drive + ":" + filename;
}
}
// start the nestedvm runtime
try {
rt = (Runtime)Class.forName("org.sqlite.SQLite").newInstance();
rt.start();
} catch (Exception e) {
throw new CausedSQLException(e);
}
// callback for user defined functions
rt.setCallJavaCB(this);
// open the db and retrieve sqlite3_db* pointer
int passback = rt.xmalloc(4);
int str = rt.strdup(filename);
if (call("sqlite3_open", str, passback) != SQLITE_OK)
throwex();
handle = deref(passback);
rt.free(str);
rt.free(passback);
}
/* callback for Runtime.CallJavaCB above */
public int call(int xType, int context, int args, int value) {
xUDF(xType, context, args, value);
return 0;
}
protected synchronized void _close() throws SQLException {
if (handle == 0) return;
try {
if (call("sqlite3_close", handle) != SQLITE_OK)
throwex();
} finally {
handle = 0;
rt.stop();
rt = null;
}
}
synchronized void interrupt() throws SQLException {
call("sqlite3_interrupt", handle);
}
synchronized void busy_timeout(int ms) throws SQLException {
call("sqlite3_busy_timeout", handle, ms);
}
protected synchronized long prepare(String sql) throws SQLException {
int passback = rt.xmalloc(4);
int str = rt.strdup(sql);
int ret = call("sqlite3_prepare", handle, str, -1, passback, 0);
rt.free(str);
if (ret != SQLITE_OK) {
rt.free(passback);
throwex();
}
int pointer = deref(passback);
rt.free(passback);
return pointer;
}
synchronized String errmsg() throws SQLException {
return cstring(call("sqlite3_errmsg", handle)); }
synchronized String libversion() throws SQLException {
return cstring(call("sqlite3_libversion", handle)); }
synchronized int changes() throws SQLException {
return call("sqlite3_changes", handle); }
protected synchronized int finalize(long stmt) throws SQLException {
return call("sqlite3_finalize", (int)stmt); }
protected synchronized int step(long stmt) throws SQLException {
return call("sqlite3_step", (int)stmt); }
protected synchronized int reset(long stmt) throws SQLException {
return call("sqlite3_reset", (int)stmt); }
synchronized int clear_bindings(long stmt) throws SQLException {
return call("sqlite3_clear_bindings", (int)stmt); }
synchronized int bind_parameter_count(long stmt) throws SQLException {
return call("sqlite3_bind_parameter_count", (int)stmt); }
synchronized int column_count(long stmt) throws SQLException {
return call("sqlite3_column_count", (int)stmt); }
synchronized int column_type(long stmt, int col) throws SQLException {
return call("sqlite3_column_type", (int)stmt, col); }
synchronized String column_name(long stmt, int col) throws SQLException {
return utfstring(call("sqlite3_column_name", (int)stmt, col)); }
synchronized String column_text(long stmt, int col) throws SQLException {
return utfstring(call("sqlite3_column_text", (int)stmt, col)); }
synchronized byte[] column_blob(long stmt, int col) throws SQLException {
int addr = call("sqlite3_column_blob", (int)stmt, col);
if (addr == 0) return null;
byte[] blob = new byte[call("sqlite3_column_bytes", (int)stmt, col)];
copyin(addr, blob, blob.length);
return blob;
}
synchronized double column_double(long stmt, int col) throws SQLException {
try { return Double.parseDouble(column_text(stmt, col)); }
catch (NumberFormatException e) { return Double.NaN; } // TODO
}
synchronized long column_long(long stmt, int col) throws SQLException {
try { return Long.parseLong(column_text(stmt, col)); }
catch (NumberFormatException e) { return 0; } // TODO
}
synchronized int column_int(long stmt, int col) throws SQLException {
return call("sqlite3_column_int", (int)stmt, col); }
synchronized String column_decltype(long stmt, int col)
throws SQLException {
return utfstring(call("sqlite3_column_decltype", (int)stmt, col)); }
synchronized String column_table_name(long stmt, int col)
throws SQLException {
return utfstring(call("sqlite3_column_table_name", (int)stmt, col));
}
synchronized int bind_null(long stmt, int pos) throws SQLException {
return call("sqlite3_bind_null", (int)stmt, pos);
}
synchronized int bind_int(long stmt, int pos, int v) throws SQLException {
return call("sqlite3_bind_int", (int)stmt, pos, v);
}
synchronized int bind_long(long stmt, int pos, long v) throws SQLException {
return bind_text(stmt, pos, Long.toString(v)); // TODO
}
synchronized int bind_double(long stmt, int pos, double v)
throws SQLException {
return bind_text(stmt, pos, Double.toString(v)); // TODO
}
synchronized int bind_text(long stmt, int pos, String v)
throws SQLException {
if (v == null) return bind_null(stmt, pos);
return call("sqlite3_bind_text", (int)stmt, pos, rt.strdup(v),
-1, rt.lookupSymbol("free"));
}
synchronized int bind_blob(long stmt, int pos, byte[] buf)
throws SQLException {
if (buf == null || buf.length < 1) return bind_null(stmt, pos);
int len = buf.length;
int blob = rt.xmalloc(len); // free()ed by sqlite3_bind_blob
copyout(buf, blob, len);
return call("sqlite3_bind_blob", (int)stmt, pos, blob, len,
rt.lookupSymbol("free"));
}
synchronized void result_null (long cxt) throws SQLException {
call("sqlite3_result_null", (int)cxt); }
synchronized void result_text (long cxt, String val) throws SQLException {
call("sqlite3_result_text", (int)cxt, rt.strdup(val), -1,
rt.lookupSymbol("free"));
}
synchronized void result_blob (long cxt, byte[] val) throws SQLException {
if (val == null || val.length == 0) { result_null(cxt); return; }
int blob = rt.xmalloc(val.length);
copyout(val, blob, val.length);
call("sqlite3_result_blob", (int)cxt, blob,
val.length, rt.lookupSymbol("free"));
}
synchronized void result_double(long cxt, double val) throws SQLException {
result_text(cxt, Double.toString(val)); } // TODO
synchronized void result_long(long cxt, long val) throws SQLException {
result_text(cxt, Long.toString(val)); } // TODO
synchronized void result_int(long cxt, int val) throws SQLException {
call("sqlite3_result_int", (int)cxt, val); }
synchronized void result_error(long cxt, String err) throws SQLException {
int str = rt.strdup(err);
call("sqlite3_result_error", (int)cxt, str, -1);
rt.free(str);
}
synchronized int value_bytes(Function f, int arg) throws SQLException {
return call("sqlite3_value_bytes", value(f, arg));
}
synchronized String value_text(Function f, int arg) throws SQLException {
return utfstring(call("sqlite3_value_text", value(f, arg)));
}
synchronized byte[] value_blob(Function f, int arg) throws SQLException {
int addr = call("sqlite3_value_blob", value(f, arg));
if (addr == 0) return null;
byte[] blob = new byte[value_bytes(f, arg)];
copyin(addr, blob, blob.length);
return blob;
}
synchronized double value_double(Function f, int arg) throws SQLException {
return Double.parseDouble(value_text(f, arg)); // TODO
}
synchronized long value_long(Function f, int arg) throws SQLException {
return Long.parseLong(value_text(f, arg)); // TODO
}
synchronized int value_int(Function f, int arg) throws SQLException {
return call("sqlite3_value_int", value(f, arg));
}
synchronized int value_type(Function f, int arg) throws SQLException {
return call("sqlite3_value_type", value(f, arg));
}
private int value(Function f, int arg) throws SQLException {
return deref((int)f.value + (arg*4));
}
synchronized int create_function(String name, Function func)
throws SQLException {
if (functions == null) {
functions = new Function[10];
funcNames = new String[10];
}
// find a position
int pos;
for (pos=0; pos < functions.length; pos++)
if (functions[pos] == null) break;
if (pos == functions.length) { // expand function arrays
Function[] fnew = new Function[functions.length * 2];
String[] nnew = new String[funcNames.length * 2];
System.arraycopy(functions, 0, fnew, 0, functions.length);
System.arraycopy(funcNames, 0, nnew, 0, funcNames.length);
functions = fnew;
funcNames = nnew;
}
// register function
functions[pos] = func;
funcNames[pos] = name;
int str = rt.strdup(name);
int rc = call("create_function_helper", handle, str, pos,
func instanceof Function.Aggregate ? 1 : 0);
rt.free(str);
return rc;
}
synchronized int destroy_function(String name) throws SQLException {
if (name == null) return 0;
// find function position number
int pos;
for (pos = 0; pos < funcNames.length; pos++)
if (name.equals(funcNames[pos])) break;
if (pos == funcNames.length) return 0;
functions[pos] = null;
funcNames[pos] = null;
// deregister function
int str = rt.strdup(name);
int rc = call("create_function_helper", handle, str, -1, 0);
rt.free(str);
return rc;
}
/* unused as we use the user_data pointer to store a single word */
synchronized void free_functions() {}
/** Callback used by xFunc (1), xStep (2) and xFinal (3). */
synchronized void xUDF(int xType, int context, int args, int value) {
Function func = null;
try {
int pos = call("sqlite3_user_data", context);
func = functions[pos];
if (func == null)
throw new SQLException("function state inconsistent");
func.context = context;
func.value = value;
func.args = args;
switch (xType) {
case 1: func.xFunc(); break;
case 2: ((Function.Aggregate)func).xStep(); break;
case 3: ((Function.Aggregate)func).xFinal(); break;
}
} catch (SQLException e) {
try {
String err = e.toString();
if (err == null) err = "unknown error";
int str = rt.strdup(err);
call("sqlite3_result_error", context, str, -1);
rt.free(str);
} catch (SQLException exp) {
exp.printStackTrace();//TODO
}
} finally {
if (func != null) {
func.context = 0;
func.value = 0;
func.args = 0;
}
}
}
/** Calls support function found in upstream/sqlite-metadata.patch */
synchronized boolean[][] column_metadata(long stmt) throws SQLException {
int colCount = call("sqlite3_column_count", (int)stmt);
boolean[][] meta = new boolean[colCount][3];
int pass = rt.xmalloc(12); // struct metadata
for (int i=0; i < colCount; i++) {
call("column_metadata_helper", handle, (int)stmt, i, pass);
meta[i][0] = deref(pass) == 1;
meta[i][1] = deref(pass + 4) == 1;
meta[i][2] = deref(pass + 8) == 1;
}
rt.free(pass);
return meta;
}
// HELPER FUNCTIONS /////////////////////////////////////////////
/** safe to reuse parameter arrays as all functions are syncrhonized */
private final int[]
p0 = new int[] {},
p1 = new int[] { 0 },
p2 = new int[] { 0, 0 },
p3 = new int[] { 0, 0, 0 },
p4 = new int[] { 0, 0, 0, 0 },
p5 = new int[] { 0, 0, 0, 0, 0 };
private int call(String addr, int a0) throws SQLException {
p1[0] = a0; return call(addr, p1); }
private int call(String addr, int a0, int a1) throws SQLException {
p2[0] = a0; p2[1] = a1; return call(addr, p2); }
private int call(String addr, int a0, int a1, int a2) throws SQLException {
p3[0] = a0; p3[1] = a1; p3[2] = a2; return call(addr, p3); }
private int call(String addr, int a0, int a1, int a2, int a3)
throws SQLException {
p4[0] = a0; p4[1] = a1; p4[2] = a2; p4[3] = a3;
return call(addr, p4);
}
private int call(String addr, int a0, int a1, int a2, int a3, int a4)
throws SQLException {
p5[0] = a0; p5[1] = a1; p5[2] = a2; p5[3] = a3; p5[4] = a4;
return call(addr, p5);
}
private int call(String func, int[] args) throws SQLException {
try {
return rt.call(func, args);
} catch (Runtime.CallException e) { throw new CausedSQLException(e); }
}
/** Dereferences a pointer, returning the word it points to. */
private int deref(int pointer) throws SQLException {
try { return rt.memRead(pointer); }
catch (Runtime.ReadFaultException e) { throw new CausedSQLException(e);}
}
private String utfstring(int str) throws SQLException {
try { return rt.utfstring(str); }
catch (Runtime.ReadFaultException e) { throw new CausedSQLException(e);}
}
private String cstring(int str) throws SQLException {
try { return rt.cstring(str); }
catch (Runtime.ReadFaultException e) { throw new CausedSQLException(e);}
}
private void copyin(int addr, byte[] buf, int count) throws SQLException {
try { rt.copyin(addr, buf, count); }
catch (Runtime.ReadFaultException e) { throw new CausedSQLException(e);}
}
private void copyout(byte[] buf, int addr, int count) throws SQLException {
try { rt.copyout(buf, addr, count); }
catch (Runtime.FaultException e) { throw new CausedSQLException(e);}
}
/** Maps any exception onto an SQLException. */
private static final class CausedSQLException extends SQLException {
private final Exception cause;
CausedSQLException(Exception e) {
if (e == null) throw new RuntimeException("null exception cause");
cause = e;
}
public Throwable getCause() { return cause; }
public void printStackTrace() { cause.printStackTrace(); }
public void printStackTrace(PrintWriter s) { cause.printStackTrace(s); }
public Throwable fillInStackTrace() { return cause.fillInStackTrace(); }
public StackTraceElement[] getStackTrace() {
return cause.getStackTrace(); }
public String getMessage() { return cause.getMessage(); }
}
}
|
package org.jvnet.hudson.plugins;
import hudson.CopyOnWrite;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Computer;
import hudson.model.EnvironmentSpecific;
import hudson.model.JDK;
import hudson.model.Node;
import hudson.model.Result;
import hudson.model.TaskListener;
import hudson.remoting.Callable;
import hudson.slaves.NodeSpecific;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Builder;
import hudson.tools.DownloadFromUrlInstaller;
import hudson.tools.ToolDescriptor;
import hudson.tools.ToolInstallation;
import hudson.tools.ToolInstaller;
import hudson.tools.ToolProperty;
import hudson.util.ArgumentListBuilder;
import hudson.util.FormValidation;
import jenkins.model.Jenkins;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* sbt plugin {@link Builder}.
* <p/>
* <p/>
* When the user configures the project and enables this builder,
* {@link DescriptorImpl#newInstance(StaplerRequest)} is invoked and a new
* {@link SbtPluginBuilder} is created. The created instance is persisted to the
* project configuration XML by using XStream, so this allows you to use
* instance fields (like {@link #name}) to remember the configuration.
* <p/>
* <p/>
* When a build is performed, the
* {@link #perform(AbstractBuild, Launcher, BuildListener)} method will be
* invoked.
*
* @author Uzi Landsmann
*/
public class SbtPluginBuilder extends Builder {
public static final Logger LOGGER = Logger.getLogger(SbtPluginBuilder.class
.getName());
private final String name;
private final String jvmFlags;
private final String sbtFlags;
private final String actions;
private String subdirPath;
// Fields in config.jelly must match the parameter names in the
// "DataBoundConstructor"
@DataBoundConstructor
public SbtPluginBuilder(String name, String jvmFlags, String sbtFlags,
String actions, String subdirPath) {
this.name = name;
this.jvmFlags = jvmFlags;
this.sbtFlags = sbtFlags;
this.actions = actions;
this.subdirPath = subdirPath;
}
public String getName() {
return name;
}
public String getJvmFlags() {
return jvmFlags;
}
public String getSbtFlags() {
return sbtFlags;
}
public String getActions() {
return actions;
}
public String getSubdirPath() {
return subdirPath;
}
/**
* Perform the sbt build. Interpret the command arguments and create a
* command line, then run it.
*/
@Override
public boolean perform(AbstractBuild build, Launcher launcher,
BuildListener listener) {
EnvVars env = null;
FilePath workDir = build.getModuleRoot();
try {
ArgumentListBuilder cmdLine = buildCmdLine(build, launcher,
listener);
String[] cmds = cmdLine.toCommandArray();
env = build.getEnvironment(listener);
if (subdirPath != null && subdirPath.length() > 0) {
workDir = new FilePath(workDir, subdirPath);
}
int exitValue = launcher.launch().cmds(cmds).envs(env)
.stdout(listener).pwd(workDir).join();
boolean success = (exitValue == 0);
build.setResult(success ? Result.SUCCESS : Result.FAILURE);
return success;
} catch (IllegalArgumentException e) {
// Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError("command execution failed: "
+ e.getMessage()));
build.setResult(Result.FAILURE);
return false;
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError("command execution failed: "
+ e.getMessage()));
build.setResult(Result.FAILURE);
return false;
} catch (InterruptedException e) {
// Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError("command execution failed: "
+ e.getMessage()));
build.setResult(Result.ABORTED);
return false;
}
}
/**
* Create an {@link ArgumentListBuilder} to run the build, given command
* arguments.
*/
private ArgumentListBuilder buildCmdLine(AbstractBuild build,
Launcher launcher, BuildListener listener)
throws IllegalArgumentException, InterruptedException, IOException {
ArgumentListBuilder args = new ArgumentListBuilder();
// DescriptorImpl descriptor = (DescriptorImpl) getDescriptor();
EnvVars env = build.getEnvironment(listener);
env.overrideAll(build.getBuildVariables());
SbtInstallation sbt = getSbt();
if (sbt == null) {
throw new IllegalArgumentException("sbt-launch.jar not found");
} else {
sbt = sbt.forNode(Computer.currentComputer().getNode(), listener);
sbt = sbt.forEnvironment(env);
String launcherPath = sbt.getSbtLaunchJar(launcher);
if (launcherPath == null) {
throw new IllegalArgumentException("sbt-launch.jar not found");
}
if (!launcher.isUnix()) {
args.add("cmd.exe", "/C");
// add an extra set of quotes after cmd/c to handle paths with spaces in Windows
args.add("\"");
}
// java
String javaExePath;
JDK jdk = build.getProject().getJDK();
Computer computer = Computer.currentComputer();
if (computer != null && jdk != null) { // just in case were not in a build
// use node specific installers, etc
jdk = jdk.forNode(computer.getNode(), listener);
}
if (jdk != null) {
javaExePath = jdk.getHome() + "/bin/java";
} else {
javaExePath = "java";
}
args.add(javaExePath);
splitAndAddArgs(env.expand(jvmFlags), args);
splitAndAddArgs(env.expand(sbtFlags), args);
// additionnal args from .sbtopts file
FilePath sbtopts = build.getProject().getWorkspace().child(".sbtopts");
if (sbtopts.exists()) {
String argsToSplit = sbtopts.readToString();
if (!StringUtils.isBlank(argsToSplit)) {
String[] split = argsToSplit.split("\\s+");
for (String flag : split) {
if (flag.startsWith("-J")) {
args.add(flag.substring(2));
} else {
args.add(flag);
}
}
}
}
args.add("-jar");
args.add(launcherPath);
for (String action : split(actions)) {
args.add(action);
}
if (!launcher.isUnix()) {
args.add("\"");
}
}
return args;
}
private SbtInstallation getSbt() {
for (SbtInstallation sbtInstallation : getDescriptor().getInstallations()) {
if (name != null && name.equals(sbtInstallation.getName())) {
return sbtInstallation;
}
}
return null;
}
/**
* Split arguments and add them to the args list
*
* @param argsToSplit the arguments to split
* @param args java/sbt command arguments
*/
private void splitAndAddArgs(String argsToSplit, ArgumentListBuilder args) {
if (StringUtils.isBlank(argsToSplit)) {
return;
}
String[] split = argsToSplit.split("\\s+");
for (String flag : split) {
args.add(flag);
}
}
private List<String> split(String s) {
List<String> result = new ArrayList<String>();
Matcher matcher = Pattern.compile("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'")
.matcher(s);
while (matcher.find()) {
if (matcher.group(1) != null)
result.add(matcher.group(1));
else if (matcher.group(2) != null)
result.add(matcher.group(2));
else
result.add(matcher.group());
}
return result;
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
* See <tt>SbtPluginBuilder/*.jelly</tt> for the actual HTML fragment for
* the configuration screen.
*/
@Extension
// this marker indicates Hudson that this is an implementation of an
// extension point.
public static final class DescriptorImpl extends
BuildStepDescriptor<Builder> {
// private volatile Jar[] jars = new Jar[0];
@CopyOnWrite
private volatile SbtInstallation[] installations = new SbtInstallation[0];
public DescriptorImpl() {
super(SbtPluginBuilder.class);
load();
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
return true;
}
/**
* This human readable name is used in the configuration screen.
*/
@Override
public String getDisplayName() {
return "Build using sbt";
}
/*public Jar getJar(String name) {
for (Jar jar : jars) {
if (jar.getName().equals(name)) {
return jar;
}
}
return null;
}*/
/*@Override
public boolean configure(StaplerRequest req, JSONObject formData)
throws FormException {
try {
jars = req.bindJSONToList(Jar.class,
req.getSubmittedForm().get("jar")).toArray(new Jar[0]);
save();
return true;
} catch (ServletException e) {
LOGGER.severe(String.format("Couldn't save jars beacause %s",
e.getMessage()));
LOGGER.severe(String.format("Stacktrace %s", e.getStackTrace()
.toString()));
return false;
}
}*/
/*public Jar[] getJars() {
return jars;
}*/
public SbtInstallation.DescriptorImpl getToolDescriptor() {
return ToolInstallation.all().get(SbtInstallation.DescriptorImpl.class);
}
public SbtInstallation[] getInstallations() {
return installations;
}
public void setInstallations(SbtInstallation... sbtInstallations) {
this.installations = sbtInstallations;
save();
}
}
/**
* Representation of an sbt launcher. Several such launchers can be defined
* in Jenkins properties to choose among when running a project.
*/
/*public static final class Jar implements Serializable {
private static final long serialVersionUID = 1L;
*/
/** The human-friendly name of this launcher */
// private String name;
/**
* The path to the launcher
*/
// private String path;
/*
@DataBoundConstructor
public Jar(String name, String path) {
this.name = name;
this.path = path;
}
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 static final class SbtInstallation extends ToolInstallation implements
EnvironmentSpecific<SbtInstallation>, NodeSpecific<SbtInstallation>, Serializable {
private static final long serialVersionUID = -2281774135009218882L;
private String sbtLaunchJar;
@DataBoundConstructor
public SbtInstallation(String name, String home, List<? extends ToolProperty<?>> properties) {
super(name, launderHome(home), properties);
}
private static String launderHome(String home) {
if (home.endsWith("/") || home.endsWith("\\")) {
// Ant doesn't like the trailing slash, especially on Windows
return home.substring(0, home.length() - 1);
} else {
return home;
}
}
public String getSbtLaunchJar(Launcher launcher) throws IOException, InterruptedException {
return launcher.getChannel().call(new Callable<String, IOException>() {
public String call() throws IOException {
File sbtLaunchJarFile = getSbtLaunchJarFile();
if(sbtLaunchJarFile.exists())
return sbtLaunchJarFile.getPath();
return getHome();
}
});
}
private File getSbtLaunchJarFile() {
String home = Util.replaceMacro(getHome(), EnvVars.masterEnvVars);
return new File(home, "bin/sbt-launch.jar");
}
public SbtInstallation forEnvironment(EnvVars environment) {
return new SbtInstallation(getName(), environment.expand(getHome()), getProperties().toList());
}
public SbtInstallation forNode(Node node, TaskListener log) throws IOException, InterruptedException {
return new SbtInstallation(getName(), translateFor(node, log), getProperties().toList());
}
@Extension
public static class DescriptorImpl extends ToolDescriptor<SbtInstallation> {
@Override
public SbtInstallation[] getInstallations() {
return Jenkins.getInstance().getDescriptorByType(SbtPluginBuilder.DescriptorImpl.class)
.getInstallations();
}
@Override
public void setInstallations(SbtInstallation... installations) {
Jenkins.getInstance().getDescriptorByType(SbtPluginBuilder.DescriptorImpl.class)
.setInstallations(installations);
}
@Override
public List<? extends ToolInstaller> getDefaultInstallers() {
return Collections.singletonList(new SbtInstaller(null));
}
@Override
public String getDisplayName() {
return "Sbt";
}
/**
* Checks if the sbt-launch.jar is exist.
*/
public FormValidation doCheckHome(@QueryParameter File value) {
if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
return FormValidation.ok();
}
// allow empty input
if(value.getPath().equals(""))
return FormValidation.ok();
if (!value.exists() || !value.isFile()) {
return FormValidation.error("sbt-launch.jar not found");
}
return FormValidation.ok();
}
}
}
/**
* Automatic Sbt installer from scala-sbt.org
*/
public static class SbtInstaller extends DownloadFromUrlInstaller {
@DataBoundConstructor
public SbtInstaller(String id) {
super(id);
}
@Extension
public static final class DescriptorImpl extends DownloadFromUrlInstaller.DescriptorImpl<SbtInstaller> {
@Override
public String getDisplayName() {
return "Install from scala-sbt.org";
}
@Override
public boolean isApplicable(Class<? extends ToolInstallation> toolType) {
return toolType == SbtInstallation.class;
}
}
}
}
|
package org.wyona.yanel.servlet;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.wyona.security.core.api.Identity;
import org.wyona.yanel.core.Resource;
import org.wyona.yanel.core.attributes.viewable.View;
import org.wyona.yanel.core.map.Map;
class YanelHTMLUI {
private static final String TOOLBAR_KEY = "toolbar";
private String reservedPrefix;
private Map map;
private static Logger log = Logger.getLogger(YanelHTMLUI.class);
YanelHTMLUI(Map map, String reservedPrefix) {
this.reservedPrefix = reservedPrefix;
this.map = map;
}
/**
* Checks if the yanel.toolbar request parameter is set and stores
* the value of the parameter in the session.
* @param request
*/
void switchToolbar(HttpServletRequest request) {
// Check for toolbar ...
String yanelToolbar = request.getParameter("yanel.toolbar");
if(yanelToolbar != null) {
if (yanelToolbar.equals("on")) {
log.info("Turn on toolbar!");
enableToolbar(request);
} else if (yanelToolbar.equals("off")) {
log.info("Turn off toolbar!");
disableToolbar(request);
} else {
log.warn("No such toolbar value: " + yanelToolbar);
}
}
}
/**
* Get toolbar menus
*/
private String getToolbarMenus(Resource resource, HttpServletRequest request) throws ServletException, IOException, Exception {
org.wyona.yanel.servlet.menu.Menu menu = null;
String menuRealmClass = resource.getRealm().getMenuClass();
if (menuRealmClass != null) {
menu = (org.wyona.yanel.servlet.menu.Menu) Class.forName(menuRealmClass).newInstance();
// TODO: Check resource configuration ...
//} else if (RESOURCE) {
} else {
menu = new org.wyona.yanel.servlet.menu.impl.DefaultMenu();
}
final String reservedPrefix = this.reservedPrefix;
final Map map = this.map;
return menu.getAllMenus(resource, request, map, reservedPrefix);
}
/**
* Gets the part of the toolbar which has to be inserted into the html header.
* @param resource
* @param request
* @return
* @throws Exception
*/
private String getToolbarHeader(Resource resource, HttpServletRequest request) throws Exception {
final String reservedPrefix = this.reservedPrefix;
String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(resource.getPath());
StringBuilder sb= new StringBuilder();
sb.append("<!-- START: Dynamically added code by " + this.getClass().getName() + " -->");
sb.append(System.getProperty("line.separator"));
sb.append("<link type=\"text/css\" href=\"" + backToRealm + reservedPrefix + "/toolbar.css\" rel=\"stylesheet\"/>");
sb.append(System.getProperty("line.separator"));
sb.append("<style type=\"text/css\" media=\"screen\">");
sb.append(System.getProperty("line.separator"));
sb.append("#yaneltoolbar_menu li li.haschild{ background: lightgrey url(" + backToRealm + reservedPrefix + "/yanel-img/submenu.gif) no-repeat 98% 50%;}");
sb.append(System.getProperty("line.separator"));
sb.append("#yaneltoolbar_menu li li.haschild:hover{ background: lightsteelblue url(" + backToRealm + reservedPrefix + "/yanel-img/submenu.gif) no-repeat 98% 50%;}");
sb.append("</style>");
sb.append(System.getProperty("line.separator"));
// If browser is Mozilla (gecko engine rv:1.7)
if (request.getHeader("User-Agent").indexOf("rv:1.7") >= 0) {
sb.append("<link type=\"text/css\" href=\"" + backToRealm + reservedPrefix + "/toolbarMozilla.css\" rel=\"stylesheet\"/>");
sb.append(System.getProperty("line.separator"));
}
// If browser is IE
if (request.getHeader("User-Agent").indexOf("compatible; MSIE") >= 0 && request.getHeader("User-Agent").indexOf("Windows") >= 0 ) {
sb.append("<link type=\"text/css\" href=\"" + backToRealm + reservedPrefix + "/toolbarIE.css\" rel=\"stylesheet\"/>");
sb.append(System.getProperty("line.separator"));
sb.append("<style type=\"text/css\" media=\"screen\">");
sb.append(" body{behavior:url(" + backToRealm + reservedPrefix + "/csshover.htc);font-size:100%;}");
sb.append("</style>");
}
// If browser is IE6
if (request.getHeader("User-Agent").indexOf("compatible; MSIE 6") >= 0 && request.getHeader("User-Agent").indexOf("Windows") >= 0 ) {
sb.append("<link type=\"text/css\" href=\"" + backToRealm + reservedPrefix + "/toolbarIE6.css\" rel=\"stylesheet\"/>");
sb.append(System.getProperty("line.separator"));
}
sb.append("<!-- END: Dynamically added code by " + this.getClass().getName() + " -->");
return sb.toString();
}
/**
* Gets the part of the toolbar which has to be inserted into the html body
* right after the opening body tag.
* @param resource
* @return
* @throws Exception
*/
private String getToolbarBodyStart(Resource resource, HttpServletRequest request) throws Exception {
final String reservedPrefix = this.reservedPrefix;
final Map map = this.map;
String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(resource.getPath());
StringBuffer buf = new StringBuffer();
buf.append("<div id=\"yaneltoolbar_headerwrap\">");
buf.append("<div id=\"yaneltoolbar_menu\">");
buf.append(getToolbarMenus(resource, request));
buf.append("</div>");
buf.append("<span id=\"yaneltoolbar_info\">");
//buf.append("Version: " + yanel.getVersion() + "-r" + yanel.getRevision() + "  ");
buf.append("Realm: <b>" + resource.getRealm().getName() + "</b>  ");
Identity identity = YanelServlet.getIdentity(request, map);
if (identity != null && !identity.isWorld()) {
buf.append("User: <b>" + identity.getUsername() + "</b>");
} else {
buf.append("User: <b>Not signed in!</b>");
}
buf.append("</span>");
buf.append("<span id=\"yaneltoolbar_logo\">");
buf.append("<img src=\"" + backToRealm + reservedPrefix + "/yanel_toolbar_logo.png\"/>");
buf.append("</span>");
buf.append("</div>");
buf.append("<div id=\"yaneltoolbar_middlewrap\">");
return buf.toString();
}
/**
* Gets the part of the toolbar which has to be inserted into the html body
* right before the closing body tag.
* @param resource
* @return
* @throws Exception
*/
private String getToolbarBodyEnd(Resource resource, HttpServletRequest request) throws Exception {
return "</div>";
}
/**
* Merges the toolbar and the page content. This will parse the html stream and add
* the toolbar.
* @param response
* @param resource
* @param view
* @throws Exception
*/
void mergeToolbarWithContent(HttpServletRequest request, HttpServletResponse response,
Resource resource, View view) throws Exception {
final int INSIDE_TAG = 0;
final int OUTSIDE_TAG = 1;
String encoding = view.getEncoding();
if (encoding == null) {
encoding = "UTF-8";
}
InputStreamReader reader = new InputStreamReader(view.getInputStream(), encoding);
OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream(), encoding);
int c;
int state = OUTSIDE_TAG;
StringBuffer tagBuf = null;
int headcount = 0;
int bodycount = 0;
while ((c = reader.read()) != -1) {
switch (state) {
case OUTSIDE_TAG:
if (c == '<') {
tagBuf = new StringBuffer("<");
state = INSIDE_TAG;
} else {
writer.write(c);
}
break;
case INSIDE_TAG:
if (c == '>') {
state = OUTSIDE_TAG;
tagBuf.append((char)c);
String tag = tagBuf.toString();
if (tag.startsWith("<head")) {
if (headcount == 0) {
writer.write(tag, 0, tag.length());
String toolbarString = getToolbarHeader(resource, request);
writer.write(toolbarString, 0, toolbarString.length());
} else {
writer.write(tag, 0, tag.length());
}
headcount++;
} else if (tag.startsWith("<body")) {
if (bodycount == 0) {
writer.write(tag, 0, tag.length());
String toolbarString = getToolbarBodyStart(resource, request);
writer.write(toolbarString, 0, toolbarString.length());
} else {
writer.write(tag, 0, tag.length());
}
bodycount++;
} else if (tag.equals("</body>")) {
bodycount
if (bodycount == 0) {
String toolbarString = getToolbarBodyEnd(resource, request);
writer.write(toolbarString, 0, toolbarString.length());
writer.write(tag, 0, tag.length());
} else {
writer.write(tag, 0, tag.length());
}
} else {
writer.write(tag, 0, tag.length());
}
} else {
tagBuf.append((char)c);
}
break;
}
}
writer.flush();
writer.close();
reader.close();
}
void enableToolbar(HttpServletRequest request) {
request.getSession(true).setAttribute(TOOLBAR_KEY, "on");
}
void disableToolbar(HttpServletRequest request) {
request.getSession(true).setAttribute(TOOLBAR_KEY, "off");
}
boolean isToolbarEnabled(HttpServletRequest request) {
String toolbarStatus = (String) request.getSession(true).getAttribute(TOOLBAR_KEY);
if (toolbarStatus != null && toolbarStatus.equals("on")) {
String yanelToolbar = request.getParameter("yanel.toolbar");
if(yanelToolbar != null && request.getParameter("yanel.toolbar").equals("suppress")) {
return false;
} else {
return true;
}
}
return false;
}
}
|
package org.mklab.taskit.server.dao;
import java.util.List;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import org.mklab.taskit.shared.model.Report;
/**
* @author teshima
* @version $Revision$, Jan 26, 2011
*/
public class ReportDaoImpl implements ReportDao {
private EntityManager entityManager;
/**
* {@link ReportDaoImpl}
*
* @param entityManager
*/
public ReportDaoImpl(EntityManager entityManager) {
if (entityManager == null) throw new NullPointerException();
this.entityManager = entityManager;
}
/**
* @see org.mklab.taskit.server.dao.ReportDao#getReportFromDate(java.lang.String)
*/
@Override
public List<Report> getReportFromDate(String date) {
final Query query = this.entityManager.createQuery("SELECT r FROM Report r WHERE r.date = :date"); //$NON-NLS-1$
query.setParameter("date", date); //$NON-NLS-1$
@SuppressWarnings("unchecked")
final List<Report> reportList = query.getResultList();
if (reportList.size() == 0) return null;
if (reportList.size() > 1) throw new IllegalStateException();
return reportList;
}
/**
* @see org.mklab.taskit.server.dao.ReportDao#getReportFromID(int)
*/
@Override
public Report getReportFromID(int id) {
return this.entityManager.find(Report.class, Integer.valueOf(id));
}
/**
* @see org.mklab.taskit.server.dao.ReportDao#registerReport(org.mklab.taskit.shared.model.Report)
*/
@Override
public void registerReport(Report report) throws ReportRegistrationException {
EntityTransaction t = this.entityManager.getTransaction();
t.begin();
try {
this.entityManager.persist(report);
t.commit();
} catch (EntityExistsException e) {
if (t.isActive()) {
t.rollback();
}
throw new ReportRegistrationException("report already exists!"); //$NON-NLS-1$
} catch (Throwable e) {
try {
if (t.isActive()) {
t.rollback();
}
throw new ReportRegistrationException("failed to register a report"); //$NON-NLS-1$
} catch (Throwable e1) {
throw new ReportRegistrationException("failed to register a report, and rollback failed."); //$NON-NLS-1$
}
}
}
/**
* @see org.mklab.taskit.server.dao.ReportDao#getReportsFromLectureId(int)
*/
@SuppressWarnings({"boxing", "unchecked"})
@Override
public List<Report> getReportsFromLectureId(int lectureId) {
Query query = this.entityManager.createQuery("SELECT r FROM REPORT r WHERE r.lectureId = :lectureId"); //$NON-NLS-1$
query.setParameter("lectureId", lectureId); //$NON-NLS-1$
List<Report> selectedReports = query.getResultList();
return selectedReports;
}
}
|
package org.osiam.ng.scim.mvc.user;
import org.osiam.ng.scim.dao.SCIMUserProvisioning;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriTemplate;
import scim.schema.v2.User;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URI;
@Controller
@RequestMapping(value = "/User")
public class UserController {
@Inject
private SCIMUserProvisioning scimUserProvisioning;
public void setScimUserProvisioning(SCIMUserProvisioning scimUserProvisioning) {
this.scimUserProvisioning = scimUserProvisioning;
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public User getUser(@PathVariable final String id) {
return scimUserProvisioning.getById(id);
}
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public User createUser(@RequestBody User user,
HttpServletRequest request, HttpServletResponse response) {
User createdUser = scimUserProvisioning.createUser(user);
String requestUrl = request.getRequestURL().toString();
URI uri = new UriTemplate("{requestUrl}{externalId}").expand(requestUrl, createdUser.getExternalId());
response.setHeader("Location", uri.toASCIIString());
return createdUser;
}
@RequestMapping(value = "/{id}",method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public User updateUser(@PathVariable final String id,
@RequestBody User user,
HttpServletRequest request, HttpServletResponse response) {
User createdUser = scimUserProvisioning.replaceUser(id, user);
String requestUrl = request.getRequestURL().toString();
URI uri = new UriTemplate("{requestUrl}").expand(requestUrl);
response.setHeader("Location", uri.toASCIIString());
return createdUser;
}
}
|
package org.owasp.esapi.reference;
import java.util.HashMap;
import org.apache.log4j.Level;
import javax.servlet.http.HttpSession;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.LogFactory;
import org.owasp.esapi.Logger;
import org.owasp.esapi.User;
public class Log4JLogFactory implements LogFactory {
private String applicationName;
@SuppressWarnings("unchecked")
private HashMap loggersMap = new HashMap();
/**
* Null argument constructor for this implementation of the LogFactory interface
* needed for dynamic configuration.
*/
public Log4JLogFactory() {}
/**
* Constructor for this implementation of the LogFactory interface.
*
* @param applicationName The name of this application this logger is being constructed for.
*/
public Log4JLogFactory(String applicationName) {
this.applicationName = applicationName;
}
/**
* {@inheritDoc}
*/
public void setApplicationName(String newApplicationName) {
applicationName = newApplicationName;
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
public Logger getLogger(Class clazz) {
// If a logger for this class already exists, we return the same one, otherwise we create a new one.
Logger classLogger = (Logger) loggersMap.get(clazz);
if (classLogger == null) {
classLogger = new Log4JLogger(applicationName, clazz.getName());
loggersMap.put(clazz, classLogger);
}
return classLogger;
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
public Logger getLogger(String moduleName) {
// If a logger for this module already exists, we return the same one, otherwise we create a new one.
Logger moduleLogger = (Logger) loggersMap.get(moduleName);
if (moduleLogger == null) {
moduleLogger = new Log4JLogger(applicationName, moduleName);
loggersMap.put(moduleName, moduleLogger);
}
return moduleLogger;
}
private static class Log4JLogger implements org.owasp.esapi.Logger {
/** The jlogger object used by this class to log everything. */
private org.apache.log4j.Logger jlogger = null;
/** The application name using this log. */
private String applicationName = null;
/** The module name using this log. */
private String moduleName = null;
/**
* Public constructor should only ever be called via the appropriate LogFactory
*
* @param applicationName the application name
* @param moduleName the module name
*/
private Log4JLogger(String applicationName, String moduleName) {
this.applicationName = applicationName;
this.moduleName = moduleName;
this.jlogger = org.apache.log4j.Logger.getLogger(applicationName + ":" + moduleName);
}
/**
* {@inheritDoc}
* Note: In this implementation, this change is not persistent,
* meaning that if the application is restarted, the log level will revert to the level defined in the
* ESAPI SecurityConfiguration properties file.
*/
public void setLevel(int level)
{
try {
jlogger.setLevel(convertESAPILeveltoLoggerLevel( level ));
}
catch (IllegalArgumentException e) {
this.error(Logger.SECURITY_FAILURE, "", e);
}
}
private static Level convertESAPILeveltoLoggerLevel(int level)
{
switch (level) {
case Logger.OFF: return Level.OFF;
case Logger.FATAL: return Level.FATAL;
case Logger.ERROR: return Level.ERROR;
case Logger.WARNING: return Level.WARN;
case Logger.INFO: return Level.INFO;
case Logger.DEBUG: return Level.DEBUG; //fine
case Logger.TRACE: return Level.TRACE; //finest
case Logger.ALL: return Level.ALL;
default: {
throw new IllegalArgumentException("Invalid logging level. Value was: " + level);
}
}
}
/**
* {@inheritDoc}
*/
public void trace(EventType type, String message, Throwable throwable) {
log(Level.TRACE, type, message, throwable);
}
/**
* {@inheritDoc}
*/
public void trace(EventType type, String message) {
log(Level.TRACE, type, message, null);
}
/**
* {@inheritDoc}
*/
public void debug(EventType type, String message, Throwable throwable) {
log(Level.DEBUG, type, message, throwable);
}
/**
* {@inheritDoc}
*/
public void debug(EventType type, String message) {
log(Level.DEBUG, type, message, null);
}
/**
* {@inheritDoc}
*/
public void info(EventType type, String message) {
log(Level.INFO, type, message, null);
}
/**
* {@inheritDoc}
*/
public void info(EventType type, String message, Throwable throwable) {
log(Level.INFO, type, message, throwable);
}
/**
* {@inheritDoc}
*/
public void warning(EventType type, String message, Throwable throwable) {
log(Level.WARN, type, message, throwable);
}
/**
* {@inheritDoc}
*/
public void warning(EventType type, String message) {
log(Level.WARN, type, message, null);
}
/**
* {@inheritDoc}
*/
public void error(EventType type, String message, Throwable throwable) {
log(Level.ERROR, type, message, throwable);
}
/**
* {@inheritDoc}
*/
public void error(EventType type, String message) {
log(Level.ERROR, type, message, null);
}
/**
* {@inheritDoc}
*/
public void fatal(EventType type, String message, Throwable throwable) {
log(Level.FATAL, type, message, throwable);
}
/**
* {@inheritDoc}
*/
public void fatal(EventType type, String message) {
log(Level.FATAL, type, message, null);
}
/**
* Log the message after optionally encoding any special characters that might be dangerous when viewed
* by an HTML based log viewer. Also encode any carriage returns and line feeds to prevent log
* injection attacks. This logs all the supplied parameters plus the user ID, user's source IP, a logging
* specific session ID, and the current date/time.
*
* It will only log the message if the current logging level is enabled, otherwise it will
* discard the message.
*
* @param level the severity level of the security event
* @param type the type of the event (SECURITY, FUNCTIONALITY, etc.)
* @param success whether this was a failed or successful event
* @param message the message
* @param throwable the throwable
*/
private void log(Level level, EventType type, String message, Throwable throwable) {
// Before we waste time preparing this event for the log, we check to see if it needs to be logged
if (!jlogger.isEnabledFor( level )) return;
User user = ESAPI.authenticator().getCurrentUser();
// create a random session number for the user to represent the user's 'session', if it doesn't exist already
String userSessionIDforLogging = "unknown";
try {
HttpSession session = ESAPI.httpUtilities().getCurrentRequest().getSession( false );
userSessionIDforLogging = (String)session.getAttribute("ESAPI_SESSION");
// if there is no session ID for the user yet, we create one and store it in the user's session
if ( userSessionIDforLogging == null ) {
userSessionIDforLogging = ""+ ESAPI.randomizer().getRandomInteger(0, 1000000);
session.setAttribute("ESAPI_SESSION", userSessionIDforLogging);
}
} catch( NullPointerException e ) {
// continue
}
// ensure there's something to log
if ( message == null ) {
message = "";
}
// ensure no CRLF injection into logs for forging records
String clean = message.replace( '\n', '_' ).replace( '\r', '_' );
if ( ((DefaultSecurityConfiguration)ESAPI.securityConfiguration()).getLogEncodingRequired() ) {
clean = ESAPI.encoder().encodeForHTML(message);
if (!message.equals(clean)) {
clean += " (Encoded)";
}
}
// create the message to log
String msg = "";
if ( user != null && type != null) {
msg = type + " " + user.getAccountName() + "@"+ user.getLastHostAddress() +":" + userSessionIDforLogging + " " + clean;
}
if(throwable == null) {
jlogger.log(level, applicationName + " " + moduleName + " " + msg);
} else {
jlogger.log(level, applicationName + " " + moduleName + " " + msg, throwable);
}
}
/**
* {@inheritDoc}
*/
public boolean isDebugEnabled() {
return jlogger.isEnabledFor(Level.DEBUG);
}
/**
* {@inheritDoc}
*/
public boolean isErrorEnabled() {
return jlogger.isEnabledFor(Level.ERROR);
}
/**
* {@inheritDoc}
*/
public boolean isFatalEnabled() {
return jlogger.isEnabledFor(Level.FATAL);
}
/**
* {@inheritDoc}
*/
public boolean isInfoEnabled() {
return jlogger.isEnabledFor(Level.INFO);
}
/**
* {@inheritDoc}
*/
public boolean isTraceEnabled() {
return jlogger.isEnabledFor(Level.TRACE);
}
/**
* {@inheritDoc}
*/
public boolean isWarningEnabled() {
return jlogger.isEnabledFor(Level.WARN);
}
}
}
|
package org.scijava.widget;
import java.util.ArrayList;
import java.util.List;
import org.scijava.AbstractContextual;
import org.scijava.convert.ConvertService;
import org.scijava.log.LogService;
import org.scijava.module.Module;
import org.scijava.module.ModuleCanceledException;
import org.scijava.module.ModuleException;
import org.scijava.module.ModuleItem;
import org.scijava.object.ObjectService;
import org.scijava.plugin.Parameter;
/**
* Abstract superclass for {@link InputHarvester}s.
* <p>
* An input harvester obtains a module's unresolved input parameter values from
* the user. Parameters are collected using an {@link InputPanel} dialog box.
* </p>
*
* @author Curtis Rueden
* @param <P> The type of UI component housing the input panel itself.
* @param <W> The type of UI component housing each input widget.
*/
public abstract class AbstractInputHarvester<P, W> extends AbstractContextual
implements InputHarvester<P, W>
{
@Parameter
private LogService log;
@Parameter
private WidgetService widgetService;
@Parameter
private ObjectService objectService;
@Parameter
private ConvertService convertService;
// -- InputHarvester methods --
@Override
public void harvest(final Module module) throws ModuleException {
final InputPanel<P, W> inputPanel = createInputPanel();
buildPanel(inputPanel, module);
if (!inputPanel.hasWidgets()) return; // no inputs left to harvest
final boolean ok = harvestInputs(inputPanel, module);
if (!ok) throw new ModuleCanceledException();
processResults(inputPanel, module);
}
@Override
public void
buildPanel(final InputPanel<P, W> inputPanel, final Module module)
throws ModuleException
{
final Iterable<ModuleItem<?>> inputs = module.getInfo().inputs();
final ArrayList<WidgetModel> models = new ArrayList<WidgetModel>();
for (final ModuleItem<?> item : inputs) {
final WidgetModel model = addInput(inputPanel, module, item);
if (model != null) models.add(model);
}
// mark all models as initialized
for (final WidgetModel model : models)
model.setInitialized(true);
// compute initial preview
module.preview();
}
@Override
public void processResults(final InputPanel<P, W> inputPanel,
final Module module) throws ModuleException
{
final Iterable<ModuleItem<?>> inputs = module.getInfo().inputs();
for (final ModuleItem<?> item : inputs) {
final String name = item.getName();
module.setResolved(name, true);
}
}
// -- Helper methods --
private <T> WidgetModel addInput(final InputPanel<P, W> inputPanel,
final Module module, final ModuleItem<T> item) throws ModuleException
{
final String name = item.getName();
final boolean resolved = module.isResolved(name);
if (resolved) return null; // skip resolved inputs
final Class<T> type = item.getType();
final WidgetModel model =
widgetService.createModel(inputPanel, module, item, getObjects(type));
final Class<W> widgetType = inputPanel.getWidgetComponentType();
final InputWidget<?, ?> widget = widgetService.create(model);
if (widget == null) {
log.debug("No widget found for input: " + model.getItem().getName());
}
if (widget != null && widget.getComponentType() == widgetType) {
@SuppressWarnings("unchecked")
final InputWidget<?, W> typedWidget = (InputWidget<?, W>) widget;
inputPanel.addWidget(typedWidget);
return model;
}
if (item.isRequired()) {
throw new ModuleException("A " + type.getSimpleName() +
" is required but none exist.");
}
// item is not required; we can skip it
return null;
}
/** Asks the object service and convert service for valid choices */
@SuppressWarnings("unchecked")
private List<?> getObjects(final Class<?> type) {
@SuppressWarnings("rawtypes")
List compatibleInputs =
new ArrayList(convertService.getCompatibleInputs(type));
compatibleInputs.addAll(objectService.getObjects(type));
return compatibleInputs;
}
}
|
package org.smoothbuild.lang.parse.ast;
import static java.util.stream.Collectors.toSet;
import static org.smoothbuild.lang.parse.LocationHelpers.locationOf;
import static org.smoothbuild.util.Lists.map;
import static org.smoothbuild.util.Lists.sane;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.smoothbuild.antlr.lang.SmoothBaseVisitor;
import org.smoothbuild.antlr.lang.SmoothParser.AccessorContext;
import org.smoothbuild.antlr.lang.SmoothParser.ArgContext;
import org.smoothbuild.antlr.lang.SmoothParser.ArgListContext;
import org.smoothbuild.antlr.lang.SmoothParser.ArrayTypeContext;
import org.smoothbuild.antlr.lang.SmoothParser.CallContext;
import org.smoothbuild.antlr.lang.SmoothParser.ExprContext;
import org.smoothbuild.antlr.lang.SmoothParser.FieldContext;
import org.smoothbuild.antlr.lang.SmoothParser.FieldListContext;
import org.smoothbuild.antlr.lang.SmoothParser.FuncContext;
import org.smoothbuild.antlr.lang.SmoothParser.ModuleContext;
import org.smoothbuild.antlr.lang.SmoothParser.NameContext;
import org.smoothbuild.antlr.lang.SmoothParser.NonPipeExprContext;
import org.smoothbuild.antlr.lang.SmoothParser.ParamContext;
import org.smoothbuild.antlr.lang.SmoothParser.ParamListContext;
import org.smoothbuild.antlr.lang.SmoothParser.StructContext;
import org.smoothbuild.antlr.lang.SmoothParser.TypeContext;
import org.smoothbuild.antlr.lang.SmoothParser.TypeIdentifierContext;
import org.smoothbuild.lang.base.Location;
import org.smoothbuild.lang.base.ModulePath;
public class AstCreator {
public static Ast fromParseTree(ModulePath path, ModuleContext module) {
List<FuncNode> nodes = new ArrayList<>();
List<StructNode> structs = new ArrayList<>();
new SmoothBaseVisitor<Void>() {
private Set<String> visibleParams = new HashSet<>();
@Override
public Void visitStruct(StructContext struct) {
String name = struct.TYPE_IDENTIFIER().getText();
Location location = locationOf(path, struct.TYPE_IDENTIFIER().getSymbol());
List<ItemNode> fields = createFields(struct.fieldList());
structs.add(new StructNode(name, fields, location));
return null;
}
private List<ItemNode> createFields(FieldListContext fieldList) {
var result = new ArrayList<ItemNode>();
if (fieldList != null) {
List<FieldContext> saneList = sane(fieldList.field());
for (int i = 0; i < saneList.size(); i++) {
result.add(createField(i, saneList.get(i)));
}
}
return result;
}
private ItemNode createField(int index, FieldContext field) {
TypeNode type = createType(field.type());
NameContext nameContext = field.name();
String name = nameContext.getText();
Location location = locationOf(path, nameContext);
return new ItemNode(index, type, name, null, location);
}
@Override
public Void visitFunc(FuncContext func) {
TypeNode type = func.type() == null ? null : createType(func.type());
NameContext nameContext = func.name();
String name = nameContext.getText();
List<ItemNode> params = createParams(func.paramList());
visibleParams = paramNames(params);
ExprNode pipe = func.expr() == null ? null : createExpr(func.expr());
visitChildren(func);
visibleParams = new HashSet<>();
nodes.add(new FuncNode(type, name, params, pipe, locationOf(path, nameContext)));
return null;
}
private Set<String> paramNames(List<ItemNode> params) {
return params
.stream()
.map(NamedNode::name)
.collect(toSet());
}
private List<ItemNode> createParams(ParamListContext paramList) {
ArrayList<ItemNode> result = new ArrayList<>();
if (paramList != null) {
List<ParamContext> paramContexts = sane(paramList.param());
for (int i = 0; i < paramContexts.size(); i++) {
result.add(createParam(i, paramContexts.get(i)));
}
}
return result;
}
private ItemNode createParam(int index, ParamContext param) {
TypeNode type = createType(param.type());
String name = param.name().getText();
Location location = locationOf(path, param);
ExprNode defaultValue = param.expr() != null
? createExpr(param.expr())
: null;
return new ItemNode(index, type, name, defaultValue, location);
}
private ExprNode createExpr(ExprContext pipe) {
NonPipeExprContext initialExpression = pipe.nonPipeExpr();
ExprNode result = createNonPipeExpr(initialExpression);
List<CallContext> calls = pipe.call();
for (int i = 0; i < calls.size(); i++) {
CallContext call = calls.get(i);
// Location of nameless piped argument is set to the location of pipe character '|'.
Location location = locationOf(path, pipe.p.get(i));
List<ArgNode> args = new ArrayList<>();
args.add(new ArgNode(null, result, location));
args.addAll(createArgList(call.argList()));
String name = call.name().getText();
result = new CallNode(name, args, locationOf(path, call.name()));
}
return result;
}
private ExprNode createNonPipeExpr(NonPipeExprContext expr) {
if (expr.accessor() != null) {
ExprNode structExpr = createNonPipeExpr(expr.nonPipeExpr());
AccessorContext accessor = expr.accessor();
String name = accessor.name().getText();
return new AccessorNode(structExpr, name, locationOf(path, accessor));
}
if (expr.array() != null) {
List<ExprNode> elements = map(expr.array().expr(), this::createExpr);
return new ArrayNode(elements, locationOf(path, expr));
}
if (expr.call() != null) {
CallContext call = expr.call();
String name = call.name().getText();
Location location = locationOf(path, call.name());
if (visibleParams.contains(name)) {
boolean hasParentheses = call.p != null;
return new RefNode(name, hasParentheses, location);
} else {
List<ArgNode> args = createArgList(call.argList());
return new CallNode(name, args, location);
}
}
if (expr.STRING() != null) {
String quotedString = expr.STRING().getText();
return new StringNode(quotedString.substring(1, quotedString.length() - 1),
locationOf(path, expr));
}
if (expr.BLOB() != null) {
return new BlobNode(
expr.BLOB().getText().substring(2), locationOf(path, expr));
}
throw new RuntimeException("Illegal parse tree: " + NonPipeExprContext.class.getSimpleName()
+ " without children.");
}
private List<ArgNode> createArgList(ArgListContext argList) {
List<ArgNode> result = new ArrayList<>();
if (argList != null) {
List<ArgContext> args = argList.arg();
for (ArgContext arg : args) {
ExprContext pipe = arg.expr();
NameContext nameContext = arg.name();
String name = nameContext == null ? null : nameContext.getText();
ExprNode exprNode = createExpr(pipe);
result.add(new ArgNode(name, exprNode, locationOf(path, arg)));
}
}
return result;
}
private TypeNode createType(TypeContext type) {
if (type instanceof TypeIdentifierContext typeIdentifier) {
return createType(typeIdentifier);
}
if (type instanceof ArrayTypeContext arrayType) {
return createArrayType(arrayType);
}
throw new RuntimeException("Illegal parse tree: " + TypeContext.class.getSimpleName()
+ " without children.");
}
private TypeNode createType(TypeIdentifierContext type) {
return new TypeNode(type.getText(), locationOf(path, type.TYPE_IDENTIFIER().getSymbol()));
}
private TypeNode createArrayType(ArrayTypeContext arrayType) {
TypeNode elementType = createType(arrayType.type());
return new ArrayTypeNode(elementType, locationOf(path, arrayType));
}
}.visit(module);
return new Ast(structs, nodes);
}
}
|
package org.spongepowered.api.entity.vehicle;
import org.spongepowered.api.entity.Entity;
/**
* Represents a Boat entity.
*/
public interface Boat extends Entity {
/**
* Gets whether this boat is currently in
* water.
*
* @return If the boat is in water
*/
boolean isInWater();
/**
* Gets the maximum speed that this boat is
* allowed to travel at.
*
* Default value is 0.4
*
* @return The maximum speed
*/
double getMaxSpeed();
/**
* Sets the maximum speed that this boat is
* allowed to travel at.
*
* Default value is 0.4
*
* @param maxSpeed The new max speed
*/
void setMaxSpeed(double maxSpeed);
/**
* Gets whether or not the boat is able to
* move freely on land.
*
* @return If the boat can move on land
*/
boolean canMoveOnLand();
/**
* Gets whether or not the boat is able to
* move freely on land.
*
* @param moveOnLand If the boat can move on land
*/
void setMoveOnLand(boolean moveOnLand);
/**
* Gets the rate at which occupied boats decelerate.
*
* @return The occupied deceleration rate.
*/
double getOccupiedDeceleration();
/**
* Sets the rate at which occupied boats decelerate.
*
* @param occupiedDeceleration The new occupied deceleration rate
*/
void setOccupiedDeceleration(double occupiedDeceleration);
/**
* Gets the rate at which unoccupied boats decelerate.
*
* @return The unoccupied deceleration rate
*/
double getUnoccupiedDeceleration();
/**
* Sets the rate at which unoccupied boats decelerate.
*
* @param unoccupiedDeceleration The new unoccupied deceleration rate
*/
void setUnoccupiedDeceleration(double unoccupiedDeceleration);
}
|
package pl.tkowalcz.twitter.mock;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.List;
import com.google.common.collect.ImmutableList;
import pl.tkowalcz.twitter.TwitterUser;
import rx.Observable;
import rx.schedulers.Schedulers;
public class MockRetroTwitter {
private final List<TwitterUser> users;
public MockRetroTwitter() {
ImmutableList.Builder<TwitterUser> builder = ImmutableList.builder();
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("src/main/resources/users.bin"));
for (int i = 0; i < 10; i++) {
builder.add((TwitterUser) ois.readObject());
}
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
users = builder.build();
}
public Observable<List<TwitterUser>> searchUsers(String prefix) {
return Observable
.from(users)
.skip(1)
.toList()
.subscribeOn(Schedulers.newThread());
}
}
|
/*
* @PickerField.java 1.0 Feb 21, 2013 Sistema Integral de Gestion Hospitalaria
*/
package py.una.med.base.dynamic.forms;
import javax.el.ValueExpression;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlInputText;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
import py.una.med.base.exception.KarakuRuntimeException;
import py.una.med.base.util.KarakuListHelperProvider;
import py.una.med.base.util.LabelProvider;
import py.una.med.base.util.LabelProvider.StringLabelProvider;
/**
*
* @author Arturo Volpe Torres
* @since 1.0
* @version 1.0 Feb 21, 2013
*
*/
public class PickerField<T> extends LabelField {
public interface KeyListener {
boolean onBlur(Field source, AjaxBehaviorEvent event,
Object submittedValue);
}
public interface ValueChangeListener<T> {
boolean onChange(Field source, T value);
}
/**
* Tipo de este componente
*/
public static final String TYPE = "py.una.med.base.dynamic.forms.PickerField";
private boolean hasCodeInput;
private String popupID;
private KeyListener keyListener;
private ValueExpression valueExpression;
private ValueExpression codeExpression;
private String urlColumns;
private KarakuListHelperProvider<T> listHelper;
private LabelProvider<T> valueLabelProvider;
private HtmlInputText codeInput;
private boolean buttonDisabled;
private boolean popupShow;
private T temp;
private boolean nullable;
private boolean selected;
private ValueChangeListener<T> valueChangeListener;
private String popupTitle;
private String dataTableID;
/**
* Crea un picker field, con ID autogenerado
*/
public PickerField() {
super();
this.popupID = getId() + "popup";
dataTableID = popupID + "datatable";
}
/*
* (non-Javadoc)
*
* @see py.una.med.base.forms.dynamic.Field#getType()
*/
@Override
public String getType() {
return TYPE;
}
/**
* Listener que escucha las peticiones del field codigo y llama al
* correspondiente {@link KeyListener} cuando un evento ocurre, si el
* correspondiente {@link KeyListener} no maneja el evento, se setea a null
* el objeto seleccionado
*
* @param event
*/
public void keyUpListener(final AjaxBehaviorEvent event) {
Object submitted = ((HtmlInputText) event.getSource())
.getSubmittedValue();
FacesContext fc = FacesContext.getCurrentInstance();
if (keyListener != null) {
boolean bool = keyListener.onBlur(this, event, submitted);
// Tratar cuadno se selecciona un valor nulo
if (!bool) {
getValueExpression().setValue(fc.getELContext(), null);
createFacesMessage(FacesMessage.SEVERITY_WARN, "",
"COMPONENT_PICKER_INPUT_NOT_FOUND");
}
}
}
/**
* Retorna el list helper, el cual se encarga de los filtros y de mostrar
* informacion
*
* @return ListHelper
*/
public KarakuListHelperProvider<T> getListHelper() {
return listHelper;
}
/**
* Setea el list helper que sera utilizado por el sistema
*
* @param listHelper
* listHelper para setear
*/
public void setListHelper(final KarakuListHelperProvider<T> listHelper) {
if (listHelper == null) {
throw new IllegalArgumentException("listHelper can't be null");
}
this.listHelper = listHelper;
}
/**
* Verifica si el componente tiene visible la opcion de insertar el codigo a
* mano
*
* @return hasCodeInput
*/
public boolean isHasCodeInput() {
return hasCodeInput;
}
/**
* Configura el componente para que cuando sea mostrado tenga un output
*
* @param hasCodeInput
* hasCodeInput para setear
*/
public void setHasCodeInput(final boolean hasCodeInput) {
this.hasCodeInput = hasCodeInput;
}
/**
* Retorna el {@link KeyListener} que esta actualmente activo, se encarga de
* escuchar todas las peticiones que se realizan sobre el input
*
* @return keyListener
*/
public KeyListener getKeyListener() {
return keyListener;
}
public void setKeyListener(final KeyListener keyListener) {
if (keyListener == null) {
throw new IllegalArgumentException("keyListener can be null");
}
setHasCodeInput(true);
this.keyListener = keyListener;
}
/**
* Retorna la expresion que se utiliza para mostrar el codigo en el
* textfield de codigo, aqui se almacenaran automaticamente todos los
* cambios que se realizen sobre este campo, y si esta configurado, el campo
* activara {@link PickerField#keyUpListener(AjaxBehaviorEvent)} que llamara
* al {@link KeyListener} configurado en
* {@link PickerField#getKeyListener()}
*
* @return idExpression
*/
public ValueExpression getCodeExpression() {
return codeExpression;
}
/**
* Asigna la expresion que se utiliza para mostrar el codigo
*
* @param idExpression
* idExpression para setear
*/
public void setCodeExpression(final ValueExpression idExpression) {
codeExpression = idExpression;
}
/**
* Retorna el codigo a ser mostrado por el componente
*
* @return "" si no esta configurado para mostrar el codigo, en otro caso
* retorna la evaluacion de {@link PickerField#getCodeExpression()}
*/
public String getCode() {
if (!hasCodeInput) {
return "";
}
FacesContext fc = FacesContext.getCurrentInstance();
if (codeExpression == null) {
throw new IllegalArgumentException("Code Expression not set, "
+ "set one with PickerField#setCodeExpression(expression))");
}
Object value = codeExpression.getValue(fc.getELContext());
if (value == null) {
return "";
}
return codeExpression.getValue(fc.getELContext()).toString();
}
public void setCode(final String code) {
// el codigo no importa, se utiliza solamente para respetar la
// convencion.
}
/**
* @return valueExpression
*/
public ValueExpression getValueExpression() {
return valueExpression;
}
/**
* @param valueExpression
* valueExpression para setear
*/
public void setValueExpression(final ValueExpression valueExpression) {
this.valueExpression = valueExpression;
}
/**
* @return popupID
*/
public String getPopupID() {
return popupID;
}
/**
* @param popupID
* popupID para setear
*/
public void setPopupID(final String popupID) {
this.popupID = popupID;
}
/**
* Retorna la url donde se encuentran las columnas mostradas por el popup de
* seleccion
*
* @return urlColumns
*/
public String getUrlColumns() {
return urlColumns;
}
/**
* Configura el componente para mostrar las filas que se encuetnran en la
* url pasada como parametro
*
* @param urlColumns
* urlColumns para setear
*/
public void setUrlColumns(final String urlColumns) {
this.urlColumns = urlColumns;
}
/**
* Formatea la opcion actualmente seleccionada para ser mostrada al usuario
*
* @return opcion correctamente formateada
*/
public String getFormmatedSelectedOption() {
T option = getValue();
return getFormmatedOption(option);
}
/**
* Formatea una opcion pasada, esto invoca al
* {@link PickerField#getValueLabelProvider()} para formatear segun
* configuracion del usuario, si no se configura el {@link LabelProvider},
* entonces utiliza {@link StringLabelProvider}
*
* @param option
* @return
*/
public String getFormmatedOption(final T option) {
if (getValueLabelProvider() == null) {
if (option == null) {
return "";
} else {
return option.toString();
}
}
return getValueLabelProvider().getAsString(option);
}
/**
* @return valueLabelProvider
*/
public LabelProvider<T> getValueLabelProvider() {
return valueLabelProvider;
}
/**
* @param valueLabelProvider
* valueLabelProvider para setear
*/
public void setValueLabelProvider(final LabelProvider<T> valueLabelProvider) {
this.valueLabelProvider = valueLabelProvider;
}
/**
* @return codeInput
*/
public HtmlInputText getCodeInput() {
if (codeInput == null) {
codeInput = SIGHComponentFactory.getHtmlInputText();
}
return codeInput;
}
/**
* @return popupShow
*/
public boolean isPopupShow() {
return popupShow;
}
public void emptyMethod() {
}
/**
* @param popupShow
* popupShow para setear
*/
public void setPopupShow(final boolean popupShow) {
this.popupShow = popupShow;
}
/**
* @param codeInput
* codeInput para setear
*/
public void setCodeInput(final HtmlInputText codeInput) {
this.codeInput = codeInput;
}
public String getPopUpClientID() {
UIComponent find = findComponent(getPopupID());
if (find == null) {
throw new KarakuRuntimeException("Popup with id: " + getId()
+ " not found.");
} else {
return find.getClientId();
}
}
public void setValue(final T value) {
temp = value;
selected = true;
}
public void initialize() {
temp = null;
selected = false;
}
/**
* Retorna el valor actualmente seleccionado en el Picker, si se selecciono
* un valor retorna el valor temporal (antes de persistir) y si ya se
* selecciono y se acepto, retorna el valor asociado en
* {@link #getValueExpression()}
*
* @return T objeto actualmente seleccionado.
*/
@SuppressWarnings("unchecked")
public T getValue() {
// Si se selecciono un valor
if (selected) {
return temp;
} else {
FacesContext fc = FacesContext.getCurrentInstance();
return (T) getValueExpression().getValue(fc.getELContext());
}
}
@Override
public boolean enable() {
getCodeInput().setDisabled(false);
setButtonDisabled(false);
return true;
}
@Override
public boolean disable() {
getCodeInput().setDisabled(true);
setButtonDisabled(true);
return true;
}
public boolean isButtonDisabled() {
return buttonDisabled;
}
public void setButtonDisabled(final boolean buttonDisabled) {
this.buttonDisabled = buttonDisabled;
}
public String getIdMessage() {
return getId() + "messages";
}
public boolean isNullable() {
return nullable;
}
public void setNullable(boolean nullable) {
this.nullable = nullable;
}
void postUpdate() {
T objectToSave = getValue();
getValueExpression().setValue(
FacesContext.getCurrentInstance().getELContext(), objectToSave);
temp = null;
selected = false;
}
/**
* Se encarga de llamar al metodo
* {@link ValueChangeListener#onChange(Field, Object)} cuando existe un
* cambio en el valor asociado al {@link PickerField}
**/
public void changeValueListener(T value) {
setValue(value);
if (valueChangeListener == null) {
return;
}
valueChangeListener.onChange(this, getValue());
}
/**
* Setea el {@link ValueChangeListener} cuando existe un cambio en el valor
* asociado al {@link PickerField}
**/
public void setValueChangeListener(ValueChangeListener<T> listener) {
this.valueChangeListener = listener;
}
/**
* Asigna un titulo al popup donde se selecciona la entidad, por defecto es
* igual a {@link #getLabel()}
*
* @param popupTitle
* key del archivo de internacionalizacion.
*/
public void setPopupTitle(String popupTitle) {
this.popupTitle = getMessage(popupTitle);
}
/**
* Retorna el titulo del popUp, por defecto es igual a {@link #getLabel()}
*
* @return Cadena ya internacionalizada
*/
public String getPopupTitle() {
return popupTitle == null ? getLabel() : popupTitle;
}
public String getDataTableID() {
return dataTableID;
}
public void setDataTableID(String id) {
dataTableID = id;
}
}
|
package seedu.tache.logic.parser;
import static seedu.tache.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.tache.logic.parser.CliSyntax.DELIMITER_PARAMETER;
import static seedu.tache.logic.parser.CliSyntax.RECURRENCE_IDENTIFIER_PREFIX;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.Stack;
import seedu.tache.commons.exceptions.IllegalValueException;
import seedu.tache.logic.commands.AddCommand;
import seedu.tache.logic.commands.Command;
import seedu.tache.logic.commands.IncorrectCommand;
import seedu.tache.logic.parser.AddCommandParser.PossibleDateTime.DateTimeType;
import seedu.tache.model.recurstate.RecurState.RecurInterval;
//@@author A0150120H
/**
* Parses input arguments and creates a new AddCommand object
*/
public class AddCommandParser {
public static final String START_DATE_IDENTIFIER = "from";
/**
* Parses the given {@code String} of arguments in the context of the AddCommand
* and returns an AddCommand object for execution.
*/
public Command parse(String args) {
Set<String> tagSet = new HashSet<String>();
String[] taskTag = args.split(AddCommand.TAG_SEPARATOR);
if (taskTag.length == 0) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
} else if (taskTag.length > 1) {
for (String tag: taskTag[1].trim().split(" ")) {
tagSet.add(tag);
}
}
String taskWithoutTags = taskTag[0];
Stack<PossibleDateTime> possibleDateTimes = parseDateTimeRecurrenceIdentifiers(taskWithoutTags);
DateTimeProperties filteredDateTimes = filterPossibleDateTime(possibleDateTimes);
PossibleDateTime startDateTime = filteredDateTimes.start;
PossibleDateTime endDateTime = filteredDateTimes.end;
PossibleDateTime recurInterval = filteredDateTimes.recurrence;
if (endDateTime == null && startDateTime != null) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
} else if (endDateTime == null && startDateTime == null) {
try {
return new AddCommand(taskWithoutTags, Optional.empty(), Optional.empty(), tagSet, Optional.empty());
} catch (IllegalValueException ex) {
return new IncorrectCommand(ex.getMessage());
}
} else if (startDateTime == null && recurInterval != null) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
} else {
String taskName = taskWithoutTags;
Optional<String> endDateTimeStr = Optional.of(endDateTime.data);
taskName = ParserUtil.removeLast(taskName, endDateTime.data);
Optional<String> startDateTimeStr = Optional.empty();
if (startDateTime != null) {
startDateTimeStr = Optional.of(startDateTime.data);
taskName = ParserUtil.removeLast(taskName, startDateTime.data);
}
Optional<RecurInterval> parsedRecurInterval = Optional.empty();
if (recurInterval != null) {
parsedRecurInterval = Optional.of(recurInterval.recurInterval);
taskName = ParserUtil.removeLast(taskName, recurInterval.data);
}
try {
return new AddCommand(taskName, startDateTimeStr, endDateTimeStr, tagSet, parsedRecurInterval);
} catch (IllegalValueException ex) {
return new IncorrectCommand(ex.getMessage());
}
}
}
public Command parseStructured(String args) {
String[] taskFields = args.split(DELIMITER_PARAMETER);
Set<String> tagSet = new HashSet<String>();
if (taskFields.length == 0) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
} else {
String name = taskFields[0];
Optional<String> startDateTime = Optional.empty();
Optional<String> endDateTime = Optional.empty();
for (int i = 1; i < taskFields.length; i++) {
String currentChunk = taskFields[i];
if (ParserUtil.hasDate(currentChunk) || ParserUtil.hasTime(currentChunk)) {
if (!endDateTime.isPresent()) {
endDateTime = Optional.of(taskFields[i]);
} else if (!startDateTime.isPresent()) {
startDateTime = endDateTime;
endDateTime = Optional.of(taskFields[i]);
} else {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
AddCommand.MESSAGE_USAGE));
}
} else {
tagSet.add(taskFields[i]);
}
}
try {
return new AddCommand(name, startDateTime, endDateTime, tagSet, Optional.empty());
} catch (IllegalValueException e) {
return new IncorrectCommand(e.getMessage());
}
}
}
/**
* Looks for all possible date/time strings based on identifiers
* @param input String to parse
* @return Stack of PossibleDateTime objects, each representing a possible date/time string
*/
private static Stack<PossibleDateTime> parseDateTimeRecurrenceIdentifiers(String input) {
String[] inputs = input.split(" ");
int currentIndex = 0;
Stack<PossibleDateTime> result = new Stack<PossibleDateTime>();
PossibleDateTime current = new PossibleDateTime(new String(), PossibleDateTime.INVALID_INDEX,
DateTimeType.UNKNOWN);
for (int i = 0; i < inputs.length; i++) {
String word = inputs[i];
if (ParserUtil.isStartDateIdentifier(word)) {
result.push(current);
current = new PossibleDateTime(word, currentIndex, DateTimeType.START);
} else if (ParserUtil.isEndDateIdentifier(word)) {
result.push(current);
current = new PossibleDateTime(word, currentIndex, DateTimeType.END);
} else if (ParserUtil.isRecurrencePrefix(word)) {
result.push(current);
current = new PossibleDateTime(word, currentIndex, DateTimeType.RECURRENCE_PREFIX);
} else if (ParserUtil.isRecurrenceDaily(word)) {
result.push(current);
result.push(new PossibleDateTime(word, currentIndex, DateTimeType.RECURRENCE, RecurInterval.DAY));
current = new PossibleDateTime(new String(), PossibleDateTime.INVALID_INDEX, DateTimeType.UNKNOWN);
} else if (ParserUtil.isRecurrenceWeekly(word)) {
result.push(current);
result.push(new PossibleDateTime(word, currentIndex, DateTimeType.RECURRENCE, RecurInterval.WEEK));
current = new PossibleDateTime(new String(), PossibleDateTime.INVALID_INDEX, DateTimeType.UNKNOWN);
} else if (ParserUtil.isRecurrenceMonthly(word)) {
result.push(current);
result.push(new PossibleDateTime(word, currentIndex, DateTimeType.RECURRENCE, RecurInterval.MONTH));
current = new PossibleDateTime(new String(), PossibleDateTime.INVALID_INDEX, DateTimeType.UNKNOWN);
} else if (ParserUtil.isRecurrenceYearly(word)) {
result.push(current);
result.push(new PossibleDateTime(word, currentIndex, DateTimeType.RECURRENCE, RecurInterval.YEAR));
current = new PossibleDateTime(new String(), PossibleDateTime.INVALID_INDEX, DateTimeType.UNKNOWN);
} else {
current.appendDateTime(word);
}
currentIndex += word.length() + 1;
}
result.push(current);
return result;
}
/**
* Class to describe a date/time String that was found
*
*/
static class PossibleDateTime {
static enum DateTimeType { START, END, UNKNOWN, RECURRENCE, RECURRENCE_PREFIX };
int startIndex;
String data;
DateTimeType type;
RecurInterval recurInterval;
static final int INVALID_INDEX = -1;
PossibleDateTime(String data, int index, DateTimeType type) {
this.startIndex = index;
this.type = type;
this.data = data;
}
PossibleDateTime(String data, int index, DateTimeType type, RecurInterval recurInterval) {
this(data, index, type);
this.recurInterval = recurInterval;
}
void appendDateTime(String data) {
this.data += " " + data;
}
}
static class DateTimeProperties {
PossibleDateTime start;
PossibleDateTime end;
PossibleDateTime recurrence;
DateTimeProperties(PossibleDateTime start, PossibleDateTime end, PossibleDateTime recurrence) {
this.start = start;
this.end = end;
this.recurrence = recurrence;
}
}
private static DateTimeProperties filterPossibleDateTime(Stack<PossibleDateTime> dateTimeStack) {
PossibleDateTime recurInterval = null;
PossibleDateTime startDateTime = null;
PossibleDateTime endDateTime = null;
while (!dateTimeStack.isEmpty()) {
PossibleDateTime current = dateTimeStack.pop();
if (current.type == DateTimeType.RECURRENCE && recurInterval == null) {
recurInterval = current;
} else if (current.type == DateTimeType.RECURRENCE_PREFIX && recurInterval == null) {
try {
current.recurInterval = ParserUtil.parseStringToRecurInterval(
current.data.replaceFirst(RECURRENCE_IDENTIFIER_PREFIX, ""));
recurInterval = current;
} catch (IllegalValueException ex) {
continue;
}
} else if (!ParserUtil.canParse(current.data)) {
continue;
} else if (current.type == DateTimeType.END && endDateTime == null) {
endDateTime = current;
} else if (current.type == DateTimeType.START && startDateTime == null) {
startDateTime = current;
}
}
return new DateTimeProperties(startDateTime, endDateTime, recurInterval);
}
}
|
/**
* The Totemic API.
* This should provide some functionality for extending Totemic.
*/
@net.minecraftforge.fml.common.API(apiVersion = "2.1.1", owner = "totemic", provides = "totemic|API")
package totemic_commons.pokefenn.api;
|
package xyz.openmodloader.client;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.resources.IResourcePack;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.text.ITextComponent;
import xyz.openmodloader.SidedHandler;
import xyz.openmodloader.OpenModLoader;
import xyz.openmodloader.client.gui.GuiSnackbar;
import xyz.openmodloader.event.impl.MessageEvent;
import xyz.openmodloader.event.impl.UpdateEvent;
import xyz.openmodloader.launcher.strippable.Side;
import xyz.openmodloader.launcher.strippable.Strippable;
import xyz.openmodloader.modloader.ModContainer;
import xyz.openmodloader.modloader.ModLoader;
import xyz.openmodloader.util.ReflectionHelper;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
@Strippable(side = Side.CLIENT)
public class OMLClientHandler implements SidedHandler {
@Override
public void onInitialize() {
List<IResourcePack> modResourcePacks = new ArrayList<>();
for (ModContainer mod : ModLoader.MODS) {
File file = mod.getModFile();
if (file.isDirectory()) {
modResourcePacks.add(new OMLFolderResourcePack(mod));
} else {
modResourcePacks.add(new OMLFileResourcePack(mod));
}
}
try {
List<IResourcePack> defaultResourcePacks = ReflectionHelper.getValue(Minecraft.class, Minecraft.getMinecraft(), "defaultResourcePacks", "aD");
defaultResourcePacks.addAll(modResourcePacks);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
OpenModLoader.INSTANCE.getEventBus().register(UpdateEvent.ClientUpdate.class, event -> {
if (GuiSnackbar.CURRENT_SNACKBAR != null) {
GuiSnackbar.CURRENT_SNACKBAR.updateSnackbar();
} else if (!GuiSnackbar.SNACKBAR_LIST.isEmpty()) {
GuiSnackbar.CURRENT_SNACKBAR = GuiSnackbar.SNACKBAR_LIST.get(0);
GuiSnackbar.SNACKBAR_LIST.remove(GuiSnackbar.CURRENT_SNACKBAR);
}
});
OpenModLoader.INSTANCE.getEventBus().register(UpdateEvent.RenderUpdate.class, event -> {
if (GuiSnackbar.CURRENT_SNACKBAR != null) {
GuiSnackbar.CURRENT_SNACKBAR.drawSnackbar();
}
});
}
@Override
public Side getSide() {
return Side.CLIENT;
}
@Override
public void openSnackbar(ITextComponent component) {
component = MessageEvent.Snackbar.handle(component, Side.CLIENT);
if (component == null) {
return;
}
GuiSnackbar.SNACKBAR_LIST.add(new GuiSnackbar(component));
}
@Override
public EntityPlayerSP getClientPlayer() {
return Minecraft.getMinecraft().thePlayer;
}
@Override
public void handleOnMainThread(Runnable runnable) {
Minecraft.getMinecraft().addScheduledTask(runnable);
}
@Override
public MinecraftServer getServer() {
return Minecraft.getMinecraft().getIntegratedServer();
}
public static List<String> getMainMenuStrings() {
List<String> list = new ArrayList<>();
list.add(ModLoader.MODS.size() + " mod" + ((ModLoader.MODS.size() == 1 ? "" : "s") + " enabled"));
list.add("Version " + OpenModLoader.INSTANCE.getVersion());
list.add("OpenModLoader");
return list;
}
}
|
package algorithms.imageProcessing;
import algorithms.misc.Misc;
import algorithms.misc.MiscMath;
import algorithms.util.PairInt;
import gnu.trove.map.TObjectIntMap;
import gnu.trove.map.hash.TObjectIntHashMap;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
/**
*
* @author nichole
*/
public class DFSContiguousGapFinder {
/**
* an array to hold each group as an item. each item contains a key which is an index
* to arrays indexer.x, indexer.y and this.pointToGroupIndex
*/
protected List<Set<PairInt> > groupMembership = new ArrayList<Set<PairInt> >();
protected Logger log = null;
/*
* map w/ key =pairint coord,
value = group it belongs to.
*/
protected TObjectIntMap<PairInt> pointToGroupMap = new
TObjectIntHashMap<PairInt>();
protected int minimumNumberInCluster = 3;
protected boolean debug = false;
protected final Set<PairInt> points;
private final int minX;
private final int maxX;
private final int minY;
private final int maxY;
/**
* uses the 4 neighbor region if true, else the 8-neighbor region
*/
protected boolean use4Neighbors = true;
public DFSContiguousGapFinder(final Set<PairInt> thePoints) {
this.points = thePoints;
this.log = Logger.getLogger(this.getClass().getName());
int[] minMaxXY = MiscMath.findMinMaxXY(points);
this.minX = minMaxXY[0];
this.maxX = minMaxXY[1];
this.minY = minMaxXY[2];
this.maxY = minMaxXY[3];
}
public void setMinimumNumberInCluster(int n) {
this.minimumNumberInCluster = n;
}
public void setDebug(boolean setDebugToTrue) {
this.debug = setDebugToTrue;
}
public void setToUse8Neighbors() {
use4Neighbors = false;
}
public void findGaps() {
findGapClusters();
prune();
}
protected void findGapClusters() {
int[] dxs;
int[] dys;
if (use4Neighbors) {
dxs = Misc.dx4;
dys = Misc.dy4;
} else {
dxs = Misc.dx8;
dys = Misc.dy8;
}
for (int i = minX; i <= maxX; ++i) {
for (int j = minY; j <= maxY; ++j) {
PairInt p = new PairInt(i, j);
if (points.contains(p)) {
continue;
}
for (int k = 0; k < dxs.length; ++k) {
int x2 = i + dxs[k];
int y2 = j + dys[k];
if (x2 < minX || y2 < minY || x2 > maxX ||
y2 > maxY) {
continue;
}
PairInt p2 = new PairInt(x2, y2);
if (!points.contains(p2)) {
processPair(p, p2);
}
}
}
}
}
protected void processPair(PairInt u, PairInt v) {
int groupId = -1;
if (pointToGroupMap.containsKey(u)) {
groupId = pointToGroupMap.get(u);
}
boolean containsV = pointToGroupMap.containsKey(v);
if ((groupId > -1) && !containsV) {
groupMembership.get(groupId).add(v);
pointToGroupMap.put(v, groupId);
} else if ((groupId == -1) && containsV) {
// usually, u will have been added before v is visited, so this
// block is rarely used
groupId = pointToGroupMap.get(v);
groupMembership.get(groupId).add(u);
pointToGroupMap.put(u, groupId);
} else if ((groupId == -1) && !containsV) {
groupId = groupMembership.size();
pointToGroupMap.put(u, groupId);
pointToGroupMap.put(v, groupId);
Set<PairInt> set = new HashSet<PairInt>();
set.add(u);
set.add(v);
groupMembership.add(set);
}
}
public List<Set<PairInt> > getGapGroupMembershipList() {
return groupMembership;
}
public int getNumberOfGapGroups() {
return groupMembership.size();
}
public TObjectIntMap<PairInt> getPointToGroupIndexes() {
return pointToGroupMap;
}
/**
* remove groups smaller than minimumNumberInCluster
*/
protected void prune() {
log.finest("number of groups before prune=" + groupMembership.size());
log.fine("PRUNE: nGroups before prune =" + groupMembership.size());
// iterate backwards so can move items up without conflict with iterator
for (int i = (groupMembership.size() - 1); i > -1; i
Set<PairInt> group = groupMembership.get(i);
int count = group.size();
if (count < minimumNumberInCluster) {
// remove this group and move up all groups w/ index > i by one index
for (int j = (i + 1); j < groupMembership.size(); j++) {
int newGroupId = j - 1;
// update members in pointToGroupIndex
Set<PairInt> latest = groupMembership.get(j);
for (PairInt p : latest) {
pointToGroupMap.put(p, newGroupId);
}
}
Set<PairInt> removed = groupMembership.remove(i);
}
}
log.fine("number of groups after prune=" + groupMembership.size());
}
public int getNumberofGroupMembers(int groupId) {
if (groupMembership.isEmpty()) {
return 0;
}
if (groupId > (groupMembership.size() - 1) || (groupId < 0)) {
throw new IllegalArgumentException("groupId=" + groupId
+ " is outside of range of nGroups=" + groupMembership.size());
}
return groupMembership.get(groupId).size();
}
public void getXY(final int groupId, final Set<PairInt> output) {
if (groupMembership.isEmpty()) {
return;
}
if (groupId > (groupMembership.size() - 1) || (groupId < 0)) {
throw new IllegalArgumentException("groupId=" + groupId
+ " is outside of range of nGroups=" + groupMembership.size());
}
Set<PairInt> indexes = groupMembership.get(groupId);
output.addAll(indexes);
}
public Set<PairInt> getXY(final int groupId) {
if (groupMembership.isEmpty()) {
return null;
}
if (groupId > (groupMembership.size() - 1) || (groupId < 0)) {
throw new IllegalArgumentException("groupId=" + groupId
+ " is outside of range of nGroups=" + groupMembership.size());
}
return groupMembership.get(groupId);
}
/**
* @return the minX
*/
public int getMinX() {
return minX;
}
/**
* @return the maxX
*/
public int getMaxX() {
return maxX;
}
/**
* @return the minY
*/
public int getMinY() {
return minY;
}
/**
* @return the maxY
*/
public int getMaxY() {
return maxY;
}
}
|
package uk.ac.ebi.gxa.db;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*;
/**
* The actual executor part extracted from {@link com.carbonfive.db.jdbc.ScriptRunner#doExecute}
*/
class SqlStatementExecutor {
private final static Logger log = LoggerFactory.getLogger(SqlStatementExecutor.class);
private Connection conn;
SqlStatementExecutor(Connection conn) {
this.conn = conn;
}
public void executeStatement(String command) throws SQLException {
Statement statement = null;
ResultSet rs = null;
try {
statement = conn.createStatement();
log.info(command);
boolean hasResults = statement.execute(command);
rs = statement.getResultSet();
if (hasResults && rs != null) {
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
for (int i = 1; i <= cols; i++) {
String name = md.getColumnName(i);
log.debug(name + "\t");
}
while (rs.next()) {
for (int i = 1; i <= cols; i++) {
String value = rs.getString(i);
log.debug(value + "\t");
}
}
}
} finally {
cleanup(statement, rs);
}
Thread.yield();
}
private void cleanup(Statement statement, ResultSet rs) {
if (rs != null)
try {
rs.close();
} catch (SQLException e) {
log.error("Cannot close result set", e);
}
if (statement != null)
try {
statement.close();
} catch (Exception e) {
// Ignore to workaround a bug in Jakarta DBCP
}
}
}
|
package org.codehaus.groovy.classgen;
import groovy.lang.Closure;
import groovy.lang.GString;
import groovy.lang.GroovyRuntimeException;
import groovy.lang.MissingClassException;
import groovy.lang.Reference;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.security.AccessControlException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import org.codehaus.groovy.ast.ASTNode;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.CodeVisitorSupport;
import org.codehaus.groovy.ast.CompileUnit;
import org.codehaus.groovy.ast.ConstructorNode;
import org.codehaus.groovy.ast.FieldNode;
import org.codehaus.groovy.ast.GroovyClassVisitor;
import org.codehaus.groovy.ast.GroovyCodeVisitor;
import org.codehaus.groovy.ast.InnerClassNode;
import org.codehaus.groovy.ast.MethodNode;
import org.codehaus.groovy.ast.Parameter;
import org.codehaus.groovy.ast.PropertyNode;
import org.codehaus.groovy.ast.Type;
import org.codehaus.groovy.ast.VariableScope;
import org.codehaus.groovy.ast.expr.ArgumentListExpression;
import org.codehaus.groovy.ast.expr.ArrayExpression;
import org.codehaus.groovy.ast.expr.BinaryExpression;
import org.codehaus.groovy.ast.expr.BooleanExpression;
import org.codehaus.groovy.ast.expr.CastExpression;
import org.codehaus.groovy.ast.expr.ClassExpression;
import org.codehaus.groovy.ast.expr.ClosureExpression;
import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.ast.expr.ConstructorCallExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.ExpressionTransformer;
import org.codehaus.groovy.ast.expr.FieldExpression;
import org.codehaus.groovy.ast.expr.GStringExpression;
import org.codehaus.groovy.ast.expr.ListExpression;
import org.codehaus.groovy.ast.expr.MapEntryExpression;
import org.codehaus.groovy.ast.expr.MapExpression;
import org.codehaus.groovy.ast.expr.MethodCallExpression;
import org.codehaus.groovy.ast.expr.NegationExpression;
import org.codehaus.groovy.ast.expr.NotExpression;
import org.codehaus.groovy.ast.expr.PostfixExpression;
import org.codehaus.groovy.ast.expr.PrefixExpression;
import org.codehaus.groovy.ast.expr.PropertyExpression;
import org.codehaus.groovy.ast.expr.RangeExpression;
import org.codehaus.groovy.ast.expr.RegexExpression;
import org.codehaus.groovy.ast.expr.StaticMethodCallExpression;
import org.codehaus.groovy.ast.expr.TernaryExpression;
import org.codehaus.groovy.ast.expr.TupleExpression;
import org.codehaus.groovy.ast.expr.VariableExpression;
import org.codehaus.groovy.ast.stmt.AssertStatement;
import org.codehaus.groovy.ast.stmt.BlockStatement;
import org.codehaus.groovy.ast.stmt.BreakStatement;
import org.codehaus.groovy.ast.stmt.CaseStatement;
import org.codehaus.groovy.ast.stmt.CatchStatement;
import org.codehaus.groovy.ast.stmt.ContinueStatement;
import org.codehaus.groovy.ast.stmt.DoWhileStatement;
import org.codehaus.groovy.ast.stmt.ExpressionStatement;
import org.codehaus.groovy.ast.stmt.ForStatement;
import org.codehaus.groovy.ast.stmt.IfStatement;
import org.codehaus.groovy.ast.stmt.ReturnStatement;
import org.codehaus.groovy.ast.stmt.Statement;
import org.codehaus.groovy.ast.stmt.SwitchStatement;
import org.codehaus.groovy.ast.stmt.SynchronizedStatement;
import org.codehaus.groovy.ast.stmt.ThrowStatement;
import org.codehaus.groovy.ast.stmt.TryCatchStatement;
import org.codehaus.groovy.ast.stmt.WhileStatement;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.codehaus.groovy.syntax.Token;
import org.codehaus.groovy.syntax.Types;
import org.codehaus.groovy.syntax.parser.RuntimeParserException;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.CodeVisitor;
import org.objectweb.asm.Constants;
import org.objectweb.asm.Label;
/**
* Generates Java class versions of Groovy classes using ASM
*
* @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
* @version $Revision$
*/
public class AsmClassGenerator extends ClassGenerator {
private Logger log = Logger.getLogger(getClass().getName());
private ClassVisitor cw;
private CodeVisitor cv;
private GeneratorContext context;
private String sourceFile;
// current class details
private ClassNode classNode;
private ClassNode outermostClass;
private String internalClassName;
private String internalBaseClassName;
/** maps the variable names to the JVM indices */
private Map variableStack = new HashMap();
/** have we output a return statement yet */
private boolean outputReturn;
/** are we on the left or right of an expression */
private boolean leftHandExpression;
// cached values
MethodCaller invokeMethodMethod = MethodCaller.newStatic(InvokerHelper.class, "invokeMethod");
MethodCaller invokeMethodSafeMethod = MethodCaller.newStatic(InvokerHelper.class, "invokeMethodSafe");
MethodCaller invokeStaticMethodMethod = MethodCaller.newStatic(InvokerHelper.class, "invokeStaticMethod");
MethodCaller invokeConstructorMethod = MethodCaller.newStatic(InvokerHelper.class, "invokeConstructor");
MethodCaller invokeConstructorOfMethod = MethodCaller.newStatic(InvokerHelper.class, "invokeConstructorOf");
MethodCaller invokeNoArgumentsConstructorOf = MethodCaller.newStatic(InvokerHelper.class, "invokeNoArgumentsConstructorOf");
MethodCaller invokeClosureMethod = MethodCaller.newStatic(InvokerHelper.class, "invokeClosure");
MethodCaller invokeSuperMethodMethod = MethodCaller.newStatic(InvokerHelper.class, "invokeSuperMethod");
MethodCaller invokeNoArgumentsMethod = MethodCaller.newStatic(InvokerHelper.class, "invokeNoArgumentsMethod");
MethodCaller invokeStaticNoArgumentsMethod =
MethodCaller.newStatic(InvokerHelper.class, "invokeStaticNoArgumentsMethod");
MethodCaller asIntMethod = MethodCaller.newStatic(InvokerHelper.class, "asInt");
MethodCaller asTypeMethod = MethodCaller.newStatic(InvokerHelper.class, "asType");
MethodCaller getPropertyMethod = MethodCaller.newStatic(InvokerHelper.class, "getProperty");
MethodCaller getPropertySafeMethod = MethodCaller.newStatic(InvokerHelper.class, "getPropertySafe");
MethodCaller setPropertyMethod = MethodCaller.newStatic(InvokerHelper.class, "setProperty");
MethodCaller setPropertyMethod2 = MethodCaller.newStatic(InvokerHelper.class, "setProperty2");
MethodCaller setPropertySafeMethod2 = MethodCaller.newStatic(InvokerHelper.class, "setPropertySafe2");
MethodCaller getGroovyObjectPropertyMethod = MethodCaller.newStatic(InvokerHelper.class, "getGroovyObjectProperty");
MethodCaller setGroovyObjectPropertyMethod = MethodCaller.newStatic(InvokerHelper.class, "setGroovyObjectProperty");
MethodCaller asIteratorMethod = MethodCaller.newStatic(InvokerHelper.class, "asIterator");
MethodCaller asBool = MethodCaller.newStatic(InvokerHelper.class, "asBool");
MethodCaller notBoolean = MethodCaller.newStatic(InvokerHelper.class, "notBoolean");
MethodCaller notObject = MethodCaller.newStatic(InvokerHelper.class, "notObject");
MethodCaller regexPattern = MethodCaller.newStatic(InvokerHelper.class, "regexPattern");
MethodCaller negation = MethodCaller.newStatic(InvokerHelper.class, "negate");
MethodCaller compareIdenticalMethod = MethodCaller.newStatic(InvokerHelper.class, "compareIdentical");
MethodCaller compareEqualMethod = MethodCaller.newStatic(InvokerHelper.class, "compareEqual");
MethodCaller compareNotEqualMethod = MethodCaller.newStatic(InvokerHelper.class, "compareNotEqual");
MethodCaller compareToMethod = MethodCaller.newStatic(InvokerHelper.class, "compareTo");
MethodCaller findRegexMethod = MethodCaller.newStatic(InvokerHelper.class, "findRegex");
MethodCaller matchRegexMethod = MethodCaller.newStatic(InvokerHelper.class, "matchRegex");
MethodCaller compareLessThanMethod = MethodCaller.newStatic(InvokerHelper.class, "compareLessThan");
MethodCaller compareLessThanEqualMethod = MethodCaller.newStatic(InvokerHelper.class, "compareLessThanEqual");
MethodCaller compareGreaterThanMethod = MethodCaller.newStatic(InvokerHelper.class, "compareGreaterThan");
MethodCaller compareGreaterThanEqualMethod = MethodCaller.newStatic(InvokerHelper.class, "compareGreaterThanEqual");
MethodCaller isCaseMethod = MethodCaller.newStatic(InvokerHelper.class, "isCase");
MethodCaller createListMethod = MethodCaller.newStatic(InvokerHelper.class, "createList");
MethodCaller createTupleMethod = MethodCaller.newStatic(InvokerHelper.class, "createTuple");
MethodCaller createMapMethod = MethodCaller.newStatic(InvokerHelper.class, "createMap");
MethodCaller createRangeMethod = MethodCaller.newStatic(InvokerHelper.class, "createRange");
MethodCaller assertFailedMethod = MethodCaller.newStatic(InvokerHelper.class, "assertFailed");
MethodCaller iteratorNextMethod = MethodCaller.newInterface(Iterator.class, "next");
MethodCaller iteratorHasNextMethod = MethodCaller.newInterface(Iterator.class, "hasNext");
// current stack index
private int lastVariableIndex;
private static int tempVariableNameCounter;
// exception blocks list
private List exceptionBlocks = new ArrayList();
private boolean definingParameters;
private Set syntheticStaticFields = new HashSet();
private Set mutableVars = new HashSet();
private boolean passingClosureParams;
private ConstructorNode constructorNode;
private MethodNode methodNode;
//private PropertyNode propertyNode;
private BlockScope scope;
private BytecodeHelper helper = new BytecodeHelper(null);
private VariableScope variableScope;
public AsmClassGenerator(
GeneratorContext context,
ClassVisitor classVisitor,
ClassLoader classLoader,
String sourceFile) {
super(classLoader);
this.context = context;
this.cw = classVisitor;
this.sourceFile = sourceFile;
}
// GroovyClassVisitor interface
public void visitClass(ClassNode classNode) {
try {
syntheticStaticFields.clear();
this.classNode = classNode;
this.outermostClass = null;
this.internalClassName = BytecodeHelper.getClassInternalName(classNode.getName());
//System.out.println("Generating class: " + classNode.getName());
// lets check that the classes are all valid
classNode.setSuperClass(checkValidType(classNode.getSuperClass(), classNode, "Must be a valid base class"));
String[] interfaces = classNode.getInterfaces();
for (int i = 0; i < interfaces.length; i++ ) {
interfaces[i] = checkValidType(interfaces[i], classNode, "Must be a valid interface name");
}
this.internalBaseClassName = BytecodeHelper.getClassInternalName(classNode.getSuperClass());
cw.visit(
classNode.getModifiers(),
internalClassName,
internalBaseClassName,
BytecodeHelper.getClassInternalNames(classNode.getInterfaces()),
sourceFile);
// set the optional enclosing method attribute of the current inner class
// br comment out once Groovy uses the latest CVS HEAD of ASM
// MethodNode enclosingMethod = classNode.getEnclosingMethod();
// String ownerName = BytecodeHelper.getClassInternalName(enclosingMethod.getDeclaringClass().getName());
// String descriptor = BytecodeHelper.getMethodDescriptor(enclosingMethod.getReturnType(), enclosingMethod.getParameters());
// EnclosingMethodAttribute attr = new EnclosingMethodAttribute(ownerName,enclosingMethod.getName(),descriptor);
// cw.visitAttribute(attr);
classNode.visitContents(this);
createSyntheticStaticFields();
for (Iterator iter = innerClasses.iterator(); iter.hasNext();) {
ClassNode innerClass = (ClassNode) iter.next();
String innerClassName = innerClass.getName();
String innerClassInternalName = BytecodeHelper.getClassInternalName(innerClassName);
String outerClassName = internalClassName; // default for inner classes
MethodNode enclosingMethod = innerClass.getEnclosingMethod();
if (enclosingMethod != null) {
// local inner classes do not specify the outer class name
outerClassName = null;
}
cw.visitInnerClass(
innerClassInternalName,
outerClassName,
innerClassName,
innerClass.getModifiers());
}
// br TODO an inner class should have an entry of itself
cw.visitEnd();
}
catch (GroovyRuntimeException e) {
e.setModule(classNode.getModule());
throw e;
}
}
public void visitConstructor(ConstructorNode node) {
// creates a MethodWriter for the (implicit) constructor
//String methodType = Type.getMethodDescriptor(VOID_TYPE, )
this.constructorNode = node;
this.methodNode = null;
this.variableScope = null;
visitParameters(node, node.getParameters());
String methodType = BytecodeHelper.getMethodDescriptor("void", node.getParameters());
cv = cw.visitMethod(node.getModifiers(), "<init>", methodType, null, null);
helper = new BytecodeHelper(cv);
findMutableVariables();
resetVariableStack(node.getParameters());
Statement code = node.getCode();
if (code == null || !firstStatementIsSuperInit(code)) {
// invokes the super class constructor
cv.visitVarInsn(ALOAD, 0);
cv.visitMethodInsn(INVOKESPECIAL, internalBaseClassName, "<init>", "()V");
}
if (code != null) {
code.visit(this);
}
cv.visitInsn(RETURN);
cv.visitMaxs(0, 0);
}
public void visitMethod(MethodNode node) {
//System.out.println("Visiting method: " + node.getName() + " with
// return type: " + node.getReturnType());
this.constructorNode = null;
this.methodNode = node;
this.variableScope = null;
visitParameters(node, node.getParameters());
node.setReturnType(checkValidType(node.getReturnType(), node, "Must be a valid return type"));
String methodType = BytecodeHelper.getMethodDescriptor(node.getReturnType(), node.getParameters());
cv = cw.visitMethod(node.getModifiers(), node.getName(), methodType, null, null);
Label labelStart = new Label();
cv.visitLabel(labelStart);
helper = new BytecodeHelper(cv);
findMutableVariables();
resetVariableStack(node.getParameters());
outputReturn = false;
node.getCode().visit(this);
if (!outputReturn) {
cv.visitInsn(RETURN);
}
// lets do all the exception blocks
for (Iterator iter = exceptionBlocks.iterator(); iter.hasNext();) {
Runnable runnable = (Runnable) iter.next();
runnable.run();
}
exceptionBlocks.clear();
Label labelEnd = new Label();
cv.visitLabel(labelEnd);
// br experiment with local var table so debugers can retrieve variable names
// Set vars = this.variableStack.keySet();
// for (Iterator iterator = vars.iterator(); iterator.hasNext();) {
// String varName = (String) iterator.next();
// Variable v = (Variable)variableStack.get(varName);
// String type = v.getTypeName();
// type = BytecodeHelper.getTypeDescription(type);
// cv.visitLocalVariable(varName, type, labelStart, labelEnd, v.getIndex()); // the start and end should be fine-pined
cv.visitMaxs(0, 0);
}
protected void visitParameters(ASTNode node, Parameter[] parameters) {
for (int i = 0, size = parameters.length; i < size; i++ ) {
visitParameter(node, parameters[i]);
}
}
protected void visitParameter(ASTNode node, Parameter parameter) {
if (! parameter.isDynamicType()) {
parameter.setType(checkValidType(parameter.getType(), node, "Must be a valid parameter class"));
}
}
public void visitField(FieldNode fieldNode) {
onLineNumber(fieldNode);
// lets check that the classes are all valid
fieldNode.setType(checkValidType(fieldNode.getType(), fieldNode, "Must be a valid field class for field: " + fieldNode.getName()));
//System.out.println("Visiting field: " + fieldNode.getName() + " on
// class: " + classNode.getName());
Object fieldValue = null;
Expression expression = fieldNode.getInitialValueExpression();
if (expression instanceof ConstantExpression) {
ConstantExpression constantExp = (ConstantExpression) expression;
Object value = constantExp.getValue();
if (isPrimitiveFieldType(fieldNode.getType())) {
// lets convert any primitive types
Class type = null;
try {
type = loadClass(fieldNode.getType());
fieldValue = InvokerHelper.asType(value, type);
}
catch (Exception e) {
log.warning("Caught unexpected: " + e);
}
}
}
cw.visitField(
fieldNode.getModifiers(),
fieldNode.getName(),
BytecodeHelper.getTypeDescription(fieldNode.getType()),
fieldValue,
null);
}
/**
* Creates a getter, setter and field
*/
public void visitProperty(PropertyNode statement) {
onLineNumber(statement);
//this.propertyNode = statement;
this.methodNode = null;
}
// GroovyCodeVisitor interface
// Statements
public void visitForLoop(ForStatement loop) {
onLineNumber(loop);
// Declare the loop counter.
Type variableType = checkValidType(loop.getVariableType(), loop, "for loop variable");
Variable variable = defineVariable(loop.getVariable(), variableType, true);
if( isInScriptBody() ) {
variable.setProperty( true );
}
// Then initialize the iterator and generate the loop control
loop.getCollectionExpression().visit(this);
asIteratorMethod.call(cv);
final int iteratorIdx = defineVariable(createVariableName("iterator"), "java.util.Iterator", false).getIndex();
cv.visitVarInsn(ASTORE, iteratorIdx);
pushBlockScope();
Label continueLabel = scope.getContinueLabel();
cv.visitJumpInsn(GOTO, continueLabel);
Label label2 = new Label();
cv.visitLabel(label2);
BytecodeExpression expression = new BytecodeExpression() {
public void visit(GroovyCodeVisitor visitor) {
cv.visitVarInsn(ALOAD, iteratorIdx);
iteratorNextMethod.call(cv);
}
};
evaluateEqual( BinaryExpression.newAssignmentExpression(loop.getVariable(), expression) );
// Generate the loop body
loop.getLoopBlock().visit(this);
// Generate the loop tail
cv.visitLabel(continueLabel);
cv.visitVarInsn(ALOAD, iteratorIdx);
iteratorHasNextMethod.call(cv);
cv.visitJumpInsn(IFNE, label2);
cv.visitLabel(scope.getBreakLabel());
popScope();
}
public void visitWhileLoop(WhileStatement loop) {
onLineNumber(loop);
/*
* // quick hack if (!methodNode.isStatic()) { cv.visitVarInsn(ALOAD,
* 0); }
*/
pushBlockScope();
Label continueLabel = scope.getContinueLabel();
cv.visitJumpInsn(GOTO, continueLabel);
Label l1 = new Label();
cv.visitLabel(l1);
loop.getLoopBlock().visit(this);
cv.visitLabel(continueLabel);
//cv.visitVarInsn(ALOAD, 0);
loop.getBooleanExpression().visit(this);
cv.visitJumpInsn(IFNE, l1);
cv.visitLabel(scope.getBreakLabel());
popScope();
}
public void visitDoWhileLoop(DoWhileStatement loop) {
onLineNumber(loop);
pushBlockScope();
Label breakLabel = scope.getBreakLabel();
Label continueLabel = scope.getContinueLabel();
cv.visitLabel(continueLabel);
Label l1 = new Label();
loop.getLoopBlock().visit(this);
cv.visitLabel(l1);
loop.getBooleanExpression().visit(this);
cv.visitJumpInsn(IFNE, continueLabel);
cv.visitLabel(breakLabel);
popScope();
}
public void visitIfElse(IfStatement ifElse) {
onLineNumber(ifElse);
ifElse.getBooleanExpression().visit(this);
Label l0 = new Label();
cv.visitJumpInsn(IFEQ, l0);
ifElse.getIfBlock().visit(this);
Label l1 = new Label();
cv.visitJumpInsn(GOTO, l1);
cv.visitLabel(l0);
ifElse.getElseBlock().visit(this);
cv.visitLabel(l1);
}
public void visitTernaryExpression(TernaryExpression expression) {
onLineNumber(expression);
expression.getBooleanExpression().visit(this);
Label l0 = new Label();
cv.visitJumpInsn(IFEQ, l0);
expression.getTrueExpression().visit(this);
Label l1 = new Label();
cv.visitJumpInsn(GOTO, l1);
cv.visitLabel(l0);
expression.getFalseExpression().visit(this);
cv.visitLabel(l1);
}
public void visitAssertStatement(AssertStatement statement) {
onLineNumber(statement);
//System.out.println("Assert: " + statement.getLineNumber() + " for: "
// + statement.getText());
BooleanExpression booleanExpression = statement.getBooleanExpression();
booleanExpression.visit(this);
Label l0 = new Label();
cv.visitJumpInsn(IFEQ, l0);
// do nothing
Label l1 = new Label();
cv.visitJumpInsn(GOTO, l1);
cv.visitLabel(l0);
// push expression string onto stack
String expressionText = booleanExpression.getText();
List list = new ArrayList();
addVariableNames(booleanExpression, list);
if (list.isEmpty()) {
cv.visitLdcInsn(expressionText);
}
else {
boolean first = true;
// lets create a new expression
cv.visitTypeInsn(NEW, "java/lang/StringBuffer");
cv.visitInsn(DUP);
cv.visitLdcInsn(expressionText + ". Values: ");
cv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuffer", "<init>", "(Ljava/lang/String;)V");
int tempIndex = defineVariable(createVariableName("assert"), "java.lang.Object", false).getIndex();
cv.visitVarInsn(ASTORE, tempIndex);
for (Iterator iter = list.iterator(); iter.hasNext();) {
String name = (String) iter.next();
String text = name + " = ";
if (first) {
first = false;
}
else {
text = ", " + text;
}
cv.visitVarInsn(ALOAD, tempIndex);
cv.visitLdcInsn(text);
cv.visitMethodInsn(
INVOKEVIRTUAL,
"java/lang/StringBuffer",
"append",
"(Ljava/lang/String;)Ljava/lang/StringBuffer;");
cv.visitInsn(POP);
cv.visitVarInsn(ALOAD, tempIndex);
new VariableExpression(name).visit(this);
cv.visitMethodInsn(
INVOKEVIRTUAL,
"java/lang/StringBuffer",
"append",
"(Ljava/lang/Object;)Ljava/lang/StringBuffer;");
cv.visitInsn(POP);
}
cv.visitVarInsn(ALOAD, tempIndex);
}
// now the optional exception expression
statement.getMessageExpression().visit(this);
assertFailedMethod.call(cv);
cv.visitLabel(l1);
}
private void addVariableNames(Expression expression, List list) {
if (expression instanceof BooleanExpression) {
BooleanExpression boolExp = (BooleanExpression) expression;
addVariableNames(boolExp.getExpression(), list);
}
else if (expression instanceof BinaryExpression) {
BinaryExpression binExp = (BinaryExpression) expression;
addVariableNames(binExp.getLeftExpression(), list);
addVariableNames(binExp.getRightExpression(), list);
}
else if (expression instanceof VariableExpression) {
VariableExpression varExp = (VariableExpression) expression;
list.add(varExp.getVariable());
}
}
public void visitTryCatchFinally(TryCatchStatement statement) {
onLineNumber(statement);
CatchStatement catchStatement = statement.getCatchStatement(0);
Statement tryStatement = statement.getTryStatement();
if (tryStatement.isEmpty() || catchStatement == null) {
final Label l0 = new Label();
cv.visitLabel(l0);
tryStatement.visit(this);
int index1 = defineVariable(this.createVariableName("exception"), "java.lang.Object").getIndex();
int index2 = defineVariable(this.createVariableName("exception"), "java.lang.Object").getIndex();
final Label l1 = new Label();
cv.visitJumpInsn(JSR, l1);
final Label l2 = new Label();
cv.visitLabel(l2);
final Label l3 = new Label();
cv.visitJumpInsn(GOTO, l3);
final Label l4 = new Label();
cv.visitLabel(l4);
cv.visitVarInsn(ASTORE, index1);
cv.visitJumpInsn(JSR, l1);
final Label l5 = new Label();
cv.visitLabel(l5);
cv.visitVarInsn(ALOAD, index1);
cv.visitInsn(ATHROW);
cv.visitLabel(l1);
cv.visitVarInsn(ASTORE, index2);
statement.getFinallyStatement().visit(this);
cv.visitVarInsn(RET, index2);
cv.visitLabel(l3);
exceptionBlocks.add(new Runnable() {
public void run() {
cv.visitTryCatchBlock(l0, l2, l4, null);
cv.visitTryCatchBlock(l4, l5, l4, null);
}
});
}
else {
String exceptionVar = catchStatement.getVariable();
String exceptionType =
checkValidType(catchStatement.getExceptionType(), catchStatement, "in catch statement");
int exceptionIndex = defineVariable(exceptionVar, exceptionType, false).getIndex();
int index2 = defineVariable(this.createVariableName("exception"), "java.lang.Object").getIndex();
int index3 = defineVariable(this.createVariableName("exception"), "java.lang.Object").getIndex();
final Label l0 = new Label();
cv.visitLabel(l0);
tryStatement.visit(this);
final Label l1 = new Label();
cv.visitLabel(l1);
Label l2 = new Label();
cv.visitJumpInsn(JSR, l2);
final Label l3 = new Label();
cv.visitLabel(l3);
Label l4 = new Label();
cv.visitJumpInsn(GOTO, l4);
final Label l5 = new Label();
cv.visitLabel(l5);
cv.visitVarInsn(ASTORE, exceptionIndex);
if (catchStatement != null) {
catchStatement.visit(this);
}
cv.visitJumpInsn(JSR, l2);
final Label l6 = new Label();
cv.visitLabel(l6);
cv.visitJumpInsn(GOTO, l4);
final Label l7 = new Label();
cv.visitLabel(l7);
cv.visitVarInsn(ASTORE, index2);
cv.visitJumpInsn(JSR, l2);
final Label l8 = new Label();
cv.visitLabel(l8);
cv.visitVarInsn(ALOAD, index2);
cv.visitInsn(ATHROW);
cv.visitLabel(l2);
cv.visitVarInsn(ASTORE, index3);
statement.getFinallyStatement().visit(this);
cv.visitVarInsn(RET, index3);
cv.visitLabel(l4);
// rest of code goes here...
//final String exceptionTypeInternalName = (catchStatement !=
// null) ?
// getTypeDescription(exceptionType) : null;
final String exceptionTypeInternalName =
(catchStatement != null) ? BytecodeHelper.getClassInternalName(exceptionType) : null;
exceptionBlocks.add(new Runnable() {
public void run() {
cv.visitTryCatchBlock(l0, l1, l5, exceptionTypeInternalName);
cv.visitTryCatchBlock(l0, l3, l7, null);
cv.visitTryCatchBlock(l5, l6, l7, null);
cv.visitTryCatchBlock(l7, l8, l7, null);
}
});
}
}
public void visitSwitch(SwitchStatement statement) {
onLineNumber(statement);
statement.getExpression().visit(this);
// switch does not have a continue label. use its parent's for continue
pushBlockScope(false, true);
scope.setContinueLabel(scope.getParent().getContinueLabel());
int switchVariableIndex = defineVariable(createVariableName("switch"), "java.lang.Object").getIndex();
cv.visitVarInsn(ASTORE, switchVariableIndex);
List caseStatements = statement.getCaseStatements();
int caseCount = caseStatements.size();
Label[] labels = new Label[caseCount + 1];
for (int i = 0; i < caseCount; i++) {
labels[i] = new Label();
}
int i = 0;
for (Iterator iter = caseStatements.iterator(); iter.hasNext(); i++) {
CaseStatement caseStatement = (CaseStatement) iter.next();
visitCaseStatement(caseStatement, switchVariableIndex, labels[i], labels[i + 1]);
}
statement.getDefaultStatement().visit(this);
cv.visitLabel(scope.getBreakLabel());
popScope();
}
public void visitCaseStatement(CaseStatement statement) {
}
public void visitCaseStatement(
CaseStatement statement,
int switchVariableIndex,
Label thisLabel,
Label nextLabel) {
onLineNumber(statement);
cv.visitVarInsn(ALOAD, switchVariableIndex);
statement.getExpression().visit(this);
isCaseMethod.call(cv);
Label l0 = new Label();
cv.visitJumpInsn(IFEQ, l0);
cv.visitLabel(thisLabel);
statement.getCode().visit(this);
// now if we don't finish with a break we need to jump past
// the next comparison
if (nextLabel != null) {
cv.visitJumpInsn(GOTO, nextLabel);
}
cv.visitLabel(l0);
}
public void visitBreakStatement(BreakStatement statement) {
onLineNumber(statement);
cv.visitJumpInsn(GOTO, scope.getBreakLabel());
}
public void visitContinueStatement(ContinueStatement statement) {
onLineNumber(statement);
cv.visitJumpInsn(GOTO, scope.getContinueLabel());
}
public void visitSynchronizedStatement(SynchronizedStatement statement) {
onLineNumber(statement);
statement.getExpression().visit(this);
int index = defineVariable(createVariableName("synchronized"), "java.lang.Integer").getIndex();
cv.visitVarInsn(ASTORE, index);
cv.visitInsn(MONITORENTER);
final Label l0 = new Label();
cv.visitLabel(l0);
statement.getCode().visit(this);
cv.visitVarInsn(ALOAD, index);
cv.visitInsn(MONITOREXIT);
final Label l1 = new Label();
cv.visitJumpInsn(GOTO, l1);
final Label l2 = new Label();
cv.visitLabel(l2);
cv.visitVarInsn(ALOAD, index);
cv.visitInsn(MONITOREXIT);
cv.visitInsn(ATHROW);
cv.visitLabel(l1);
exceptionBlocks.add(new Runnable() {
public void run() {
cv.visitTryCatchBlock(l0, l2, l2, null);
}
});
}
public void visitThrowStatement(ThrowStatement statement) {
statement.getExpression().visit(this);
// we should infer the type of the exception from the expression
cv.visitTypeInsn(CHECKCAST, "java/lang/Throwable");
cv.visitInsn(ATHROW);
}
public void visitReturnStatement(ReturnStatement statement) {
onLineNumber(statement);
String returnType = methodNode.getReturnType();
if (returnType.equals("void")) {
if (!(statement == ReturnStatement.RETURN_NULL_OR_VOID)) {
throw new RuntimeParserException(
"Cannot use return statement with an expression on a method that returns void",
statement);
}
cv.visitInsn(RETURN);
outputReturn = true;
return;
}
Expression expression = statement.getExpression();
evaluateExpression(expression);
//return is based on class type
//TODO: make work with arrays
// we may need to cast
helper.unbox(returnType);
if (returnType.equals("double")) {
cv.visitInsn(DRETURN);
}
else if (returnType.equals("float")) {
cv.visitInsn(FRETURN);
}
else if (returnType.equals("long")) {
cv.visitInsn(LRETURN);
}
else if (returnType.equals("boolean")) {
cv.visitInsn(IRETURN);
}
else if (
returnType.equals("char")
|| returnType.equals("byte")
|| returnType.equals("int")
|| returnType.equals("short")) { //byte,short,boolean,int are
// all IRETURN
cv.visitInsn(IRETURN);
}
else {
doConvertAndCast(returnType, expression);
cv.visitInsn(ARETURN);
/*
if (c == Boolean.class) {
Label l0 = new Label();
cv.visitJumpInsn(IFEQ, l0);
cv.visitFieldInsn(GETSTATIC, "java/lang/Boolean", "TRUE", "Ljava/lang/Boolean;");
cv.visitInsn(ARETURN);
cv.visitLabel(l0);
cv.visitFieldInsn(GETSTATIC, "java/lang/Boolean", "FALSE", "Ljava/lang/Boolean;");
cv.visitInsn(ARETURN);
}
else {
if (isValidTypeForCast(returnType) && !returnType.equals(c.getName())) {
doConvertAndCast(returnType, expression);
}
cv.visitInsn(ARETURN);
}
*/
}
outputReturn = true;
}
/**
* Casts to the given type unless it can be determined that the cast is unnecessary
*/
protected void doConvertAndCast(String type, Expression expression) {
String expType = getExpressionType(expression);
if (isValidTypeForCast(type) && (expType == null || !type.equals(expType))) {
doConvertAndCast(type);
}
}
/**
* @param expression
*/
protected void evaluateExpression(Expression expression) {
visitAndAutobox(expression);
//expression.visit(this);
Expression assignExpr = createReturnLHSExpression(expression);
if (assignExpr != null) {
leftHandExpression = false;
assignExpr.visit(this);
}
}
public void visitExpressionStatement(ExpressionStatement statement) {
onLineNumber(statement);
Expression expression = statement.getExpression();
visitAndAutobox(expression);
if (isPopRequired(expression)) {
cv.visitInsn(POP);
}
}
// Expressions
public void visitBinaryExpression(BinaryExpression expression) {
switch (expression.getOperation().getType()) {
case Types.EQUAL :
evaluateEqual(expression);
break;
case Types.COMPARE_IDENTICAL :
evaluateBinaryExpression(compareIdenticalMethod, expression);
break;
case Types.COMPARE_EQUAL :
evaluateBinaryExpression(compareEqualMethod, expression);
break;
case Types.COMPARE_NOT_EQUAL :
evaluateBinaryExpression(compareNotEqualMethod, expression);
break;
case Types.COMPARE_TO :
evaluateCompareTo(expression);
break;
case Types.COMPARE_GREATER_THAN :
evaluateBinaryExpression(compareGreaterThanMethod, expression);
break;
case Types.COMPARE_GREATER_THAN_EQUAL :
evaluateBinaryExpression(compareGreaterThanEqualMethod, expression);
break;
case Types.COMPARE_LESS_THAN :
evaluateBinaryExpression(compareLessThanMethod, expression);
break;
case Types.COMPARE_LESS_THAN_EQUAL :
evaluateBinaryExpression(compareLessThanEqualMethod, expression);
break;
case Types.LOGICAL_AND :
evaluateLogicalAndExpression(expression);
break;
case Types.LOGICAL_OR :
evaluateLogicalOrExpression(expression);
break;
case Types.PLUS :
evaluateBinaryExpression("plus", expression);
break;
case Types.PLUS_EQUAL :
evaluateBinaryExpressionWithAsignment("plus", expression);
break;
case Types.MINUS :
evaluateBinaryExpression("minus", expression);
break;
case Types.MINUS_EQUAL :
evaluateBinaryExpressionWithAsignment("minus", expression);
break;
case Types.MULTIPLY :
evaluateBinaryExpression("multiply", expression);
break;
case Types.MULTIPLY_EQUAL :
evaluateBinaryExpressionWithAsignment("multiply", expression);
break;
case Types.DIVIDE :
//SPG don't use divide since BigInteger implements directly
//and we want to dispatch through DefaultGroovyMethods to get a BigDecimal result
evaluateBinaryExpression("div", expression);
break;
case Types.DIVIDE_EQUAL :
//SPG don't use divide since BigInteger implements directly
//and we want to dispatch through DefaultGroovyMethods to get a BigDecimal result
evaluateBinaryExpressionWithAsignment("div", expression);
break;
case Types.MOD :
evaluateBinaryExpression("mod", expression);
break;
case Types.MOD_EQUAL :
evaluateBinaryExpressionWithAsignment("mod", expression);
break;
case Types.LEFT_SHIFT :
evaluateBinaryExpression("leftShift", expression);
break;
case Types.RIGHT_SHIFT :
evaluateBinaryExpression("rightShift", expression);
break;
case Types.RIGHT_SHIFT_UNSIGNED :
evaluateBinaryExpression("rightShiftUnsigned", expression);
break;
case Types.KEYWORD_INSTANCEOF :
evaluateInstanceof(expression);
break;
case Types.FIND_REGEX :
evaluateBinaryExpression(findRegexMethod, expression);
break;
case Types.MATCH_REGEX :
evaluateBinaryExpression(matchRegexMethod, expression);
break;
case Types.LEFT_SQUARE_BRACKET :
if (leftHandExpression) {
throw new RuntimeException("Should not be called");
//evaluateBinaryExpression("putAt", expression);
}
else {
evaluateBinaryExpression("getAt", expression);
}
break;
default :
throw new ClassGeneratorException("Operation: " + expression.getOperation() + " not supported");
}
}
public void visitPostfixExpression(PostfixExpression expression) {
switch (expression.getOperation().getType()) {
case Types.PLUS_PLUS :
evaluatePostfixMethod("next", expression.getExpression());
break;
case Types.MINUS_MINUS :
evaluatePostfixMethod("previous", expression.getExpression());
break;
}
}
public void visitPrefixExpression(PrefixExpression expression) {
switch (expression.getOperation().getType()) {
case Types.PLUS_PLUS :
evaluatePrefixMethod("next", expression.getExpression());
break;
case Types.MINUS_MINUS :
evaluatePrefixMethod("previous", expression.getExpression());
break;
}
}
public void visitClosureExpression(ClosureExpression expression) {
ClassNode innerClass = createClosureClass(expression);
addInnerClass(innerClass);
String innerClassinternalName = BytecodeHelper.getClassInternalName(innerClass.getName());
ClassNode owner = innerClass.getOuterClass();
String ownerTypeName = owner.getName();
if (classNode.isStaticClass() || isStaticMethod()) {
ownerTypeName = "java.lang.Class";
}
passingClosureParams = true;
List constructors = innerClass.getDeclaredConstructors();
ConstructorNode node = (ConstructorNode) constructors.get(0);
Parameter[] localVariableParams = node.getParameters();
// Define in the context any variables that will be
// created inside the closure. Note that the first two
// parameters are always _outerInstance and _delegate,
// so we don't worry about them.
for (int i = 2; i < localVariableParams.length; i++) {
Parameter param = localVariableParams[i];
String name = param.getName();
if (variableStack.get(name) == null && classNode.getField(name) == null) {
defineVariable(name, "java.lang.Object");
}
}
cv.visitTypeInsn(NEW, innerClassinternalName);
cv.visitInsn(DUP);
if (isStaticMethod() || classNode.isStaticClass()) {
visitClassExpression(new ClassExpression(ownerTypeName));
}
else {
loadThisOrOwner();
}
if (innerClass.getSuperClass().equals("groovy.lang.Closure")) {
if (isStaticMethod()) {
/**
* todo could maybe stash this expression in a JVM variable
* from previous statement above
*/
visitClassExpression(new ClassExpression(ownerTypeName));
}
else {
loadThisOrOwner();
}
}
//String prototype = "(L" + BytecodeHelper.getClassInternalName(ownerTypeName) + ";Ljava/lang/Object;";
// now lets load the various parameters we're passing
for (int i = 2; i < localVariableParams.length; i++) {
Parameter param = localVariableParams[i];
String name = param.getName();
if (variableStack.get(name) == null) {
visitFieldExpression(new FieldExpression(classNode.getField(name)));
}
else {
visitVariableExpression(new VariableExpression(name));
}
//prototype = prototype + "L" + BytecodeHelper.getClassInternalName(param.getType()) + ";";
}
passingClosureParams = false;
// we may need to pass in some other constructors
//cv.visitMethodInsn(INVOKESPECIAL, innerClassinternalName, "<init>", prototype + ")V");
cv.visitMethodInsn(
INVOKESPECIAL,
innerClassinternalName,
"<init>",
BytecodeHelper.getMethodDescriptor("void", localVariableParams));
}
/**
* Loads either this object or if we're inside a closure then load the top level owner
*/
protected void loadThisOrOwner() {
if (isInnerClass()) {
visitFieldExpression(new FieldExpression(classNode.getField("owner")));
}
else {
cv.visitVarInsn(ALOAD, 0);
}
}
public void visitRegexExpression(RegexExpression expression) {
expression.getRegex().visit(this);
regexPattern.call(cv);
}
public void visitConstantExpression(ConstantExpression expression) {
Object value = expression.getValue();
if (value == null) {
cv.visitInsn(ACONST_NULL);
}
else if (value instanceof String) {
cv.visitLdcInsn(value);
}
else if (value instanceof Number) {
/** todo it would be more efficient to generate class constants */
Number n = (Number) value;
String className = BytecodeHelper.getClassInternalName(value.getClass().getName());
cv.visitTypeInsn(NEW, className);
cv.visitInsn(DUP);
String methodType;
if (n instanceof Double) {
cv.visitLdcInsn(n);
methodType = "(D)V";
}
else if (n instanceof Float) {
cv.visitLdcInsn(n);
methodType = "(F)V";
}
else if (value instanceof Long) {
cv.visitLdcInsn(n);
methodType = "(J)V";
}
else if (value instanceof BigDecimal) {
cv.visitLdcInsn(n.toString());
methodType = "(Ljava/lang/String;)V";
}
else if (value instanceof BigInteger) {
cv.visitLdcInsn(n.toString());
methodType = "(Ljava/lang/String;)V";
}
else if (value instanceof Integer){
cv.visitLdcInsn(n);
methodType = "(I)V";
}
else
{
throw new ClassGeneratorException(
"Cannot generate bytecode for constant: " + value
+ " of type: " + value.getClass().getName()
+". Numeric constant type not supported.");
}
cv.visitMethodInsn(INVOKESPECIAL, className, "<init>", methodType);
}
else if (value instanceof Boolean) {
Boolean bool = (Boolean) value;
String text = (bool.booleanValue()) ? "TRUE" : "FALSE";
cv.visitFieldInsn(GETSTATIC, "java/lang/Boolean", text, "Ljava/lang/Boolean;");
}
else if (value instanceof Class) {
Class vc = (Class) value;
if (!vc.getName().equals("java.lang.Void")) {
throw new ClassGeneratorException(
"Cannot generate bytecode for constant: " + value + " of type: " + value.getClass().getName());
}
}
else {
throw new ClassGeneratorException(
"Cannot generate bytecode for constant: " + value + " of type: " + value.getClass().getName());
}
}
public void visitNegationExpression(NegationExpression expression) {
Expression subExpression = expression.getExpression();
subExpression.visit(this);
negation.call(cv);
}
public void visitCastExpression(CastExpression expression) {
String type = expression.getType();
type = checkValidType(type, expression, "in cast");
visitAndAutobox(expression.getExpression());
doConvertAndCast(type, expression.getExpression());
}
public void visitNotExpression(NotExpression expression) {
Expression subExpression = expression.getExpression();
subExpression.visit(this);
// This is not the best way to do this. Javac does it by reversing the
// underlying expressions but that proved
// fairly complicated for not much gain. Instead we'll just use a
// utility function for now.
if (comparisonExpression(expression.getExpression())) {
notBoolean.call(cv);
}
else {
notObject.call(cv);
}
}
public void visitBooleanExpression(BooleanExpression expression) {
expression.getExpression().visit(this);
if (!comparisonExpression(expression.getExpression())) {
asBool.call(cv);
}
}
public void visitMethodCallExpression(MethodCallExpression call) {
this.leftHandExpression = false;
Expression arguments = call.getArguments();
/*
* if (arguments instanceof TupleExpression) { TupleExpression
* tupleExpression = (TupleExpression) arguments; int size =
* tupleExpression.getExpressions().size(); if (size == 0) { arguments =
* ConstantExpression.EMPTY_ARRAY; } }
*/
boolean superMethodCall = MethodCallExpression.isSuperMethodCall(call);
String method = call.getMethod();
if (superMethodCall && method.equals("<init>")) {
/** todo handle method types! */
cv.visitVarInsn(ALOAD, 0);
if (isInClosureConstructor()) { // br use the second param to init the super class (Closure)
cv.visitVarInsn(ALOAD, 2);
cv.visitMethodInsn(INVOKESPECIAL, internalBaseClassName, "<init>", "(Ljava/lang/Object;)V");
}
else {
cv.visitVarInsn(ALOAD, 1);
cv.visitMethodInsn(INVOKESPECIAL, internalBaseClassName, "<init>", "(Ljava/lang/Object;)V");
}
}
else {
// are we a local variable
if (isThisExpression(call.getObjectExpression()) && isFieldOrVariable(call.getMethod())) {
/*
* if (arguments instanceof TupleExpression) { TupleExpression
* tupleExpression = (TupleExpression) arguments; int size =
* tupleExpression.getExpressions().size(); if (size == 1) {
* arguments = (Expression)
* tupleExpression.getExpressions().get(0); } }
*/
// lets invoke the closure method
visitVariableExpression(new VariableExpression(method));
arguments.visit(this);
invokeClosureMethod.call(cv);
}
else {
if (superMethodCall) {
if (method.equals("super") || method.equals("<init>")) {
ConstructorNode superConstructorNode = findSuperConstructor(call);
cv.visitVarInsn(ALOAD, 0);
loadArguments(superConstructorNode.getParameters(), arguments);
String descriptor = BytecodeHelper.getMethodDescriptor("void", superConstructorNode.getParameters());
cv.visitMethodInsn(INVOKESPECIAL, BytecodeHelper.getClassInternalName(classNode.getSuperClass()), "<init>", descriptor);
}
else {
MethodNode superMethodNode = findSuperMethod(call);
cv.visitVarInsn(ALOAD, 0);
loadArguments(superMethodNode.getParameters(), arguments);
String descriptor = BytecodeHelper.getMethodDescriptor(superMethodNode.getReturnType(), superMethodNode.getParameters());
cv.visitMethodInsn(INVOKESPECIAL, BytecodeHelper.getClassInternalName(superMethodNode.getDeclaringClass().getName()), method, descriptor);
}
}
else {
if (emptyArguments(arguments) && !call.isSafe()) {
call.getObjectExpression().visit(this);
cv.visitLdcInsn(method);
invokeNoArgumentsMethod.call(cv);
}
else {
if (argumentsUseStack(arguments)) {
int paramIdx =
defineVariable(createVariableName("temp"), "java.lang.Object", false).getIndex();
arguments.visit(this);
cv.visitVarInsn(ASTORE, paramIdx);
call.getObjectExpression().visit(this);
cv.visitLdcInsn(method);
cv.visitVarInsn(ALOAD, paramIdx);
}
else {
call.getObjectExpression().visit(this);
cv.visitLdcInsn(method);
arguments.visit(this);
}
if (call.isSafe()) {
invokeMethodSafeMethod.call(cv);
}
else {
invokeMethodMethod.call(cv);
}
}
}
}
}
}
/**
* Loads and coerces the argument values for the given method call
*/
protected void loadArguments(Parameter[] parameters, Expression expression) {
TupleExpression argListExp = (TupleExpression) expression;
List arguments = argListExp.getExpressions();
for (int i = 0, size = arguments.size(); i < size; i++) {
Expression argExp = argListExp.getExpression(i);
Parameter param = parameters[i];
visitAndAutobox(argExp);
String type = param.getType();
if (BytecodeHelper.isPrimitiveType(type)) {
helper.unbox(type);
}
doConvertAndCast(type, argExp);
}
}
/**
* Attempts to find the method of the given name in a super class
*/
protected MethodNode findSuperMethod(MethodCallExpression call) {
String methodName = call.getMethod();
TupleExpression argExpr = (TupleExpression) call.getArguments();
int argCount = argExpr.getExpressions().size();
ClassNode superClassNode = classNode.getSuperClassNode();
if (superClassNode != null) {
List methods = superClassNode.getMethods(methodName);
for (Iterator iter = methods.iterator(); iter.hasNext(); ) {
MethodNode method = (MethodNode) iter.next();
if (method.getParameters().length == argCount) {
return method;
}
}
}
throw new GroovyRuntimeException("No such method: " + methodName + " for class: " + classNode.getName(), call);
}
/**
* Attempts to find the constructor in a super class
*/
protected ConstructorNode findSuperConstructor(MethodCallExpression call) {
TupleExpression argExpr = (TupleExpression) call.getArguments();
int argCount = argExpr.getExpressions().size();
ClassNode superClassNode = classNode.getSuperClassNode();
if (superClassNode != null) {
List constructors = superClassNode.getDeclaredConstructors();
for (Iterator iter = constructors.iterator(); iter.hasNext(); ) {
ConstructorNode constructor = (ConstructorNode) iter.next();
if (constructor.getParameters().length == argCount) {
return constructor;
}
}
}
throw new GroovyRuntimeException("No such constructor for class: " + classNode.getName(), call);
}
protected boolean emptyArguments(Expression arguments) {
if (arguments instanceof TupleExpression) {
TupleExpression tupleExpression = (TupleExpression) arguments;
int size = tupleExpression.getExpressions().size();
return size == 0;
}
return false;
}
public void visitStaticMethodCallExpression(StaticMethodCallExpression call) {
this.leftHandExpression = false;
Expression arguments = call.getArguments();
if (emptyArguments(arguments)) {
cv.visitLdcInsn(call.getType());
cv.visitLdcInsn(call.getMethod());
invokeStaticNoArgumentsMethod.call(cv);
}
else {
if (arguments instanceof TupleExpression) {
TupleExpression tupleExpression = (TupleExpression) arguments;
int size = tupleExpression.getExpressions().size();
if (size == 1) {
arguments = (Expression) tupleExpression.getExpressions().get(0);
}
}
cv.visitLdcInsn(call.getType());
cv.visitLdcInsn(call.getMethod());
arguments.visit(this);
invokeStaticMethodMethod.call(cv);
}
}
public void visitConstructorCallExpression(ConstructorCallExpression call) {
this.leftHandExpression = false;
Expression arguments = call.getArguments();
if (arguments instanceof TupleExpression) {
TupleExpression tupleExpression = (TupleExpression) arguments;
int size = tupleExpression.getExpressions().size();
if (size == 0) {
arguments = null;
}
else if (size == 1) {
arguments = (Expression) tupleExpression.getExpressions().get(0);
}
}
// lets check that the type exists
String type = checkValidType(call.getType(), call, "in constructor call");
//System.out.println("Constructing: " + type);
visitClassExpression(new ClassExpression(type));
if (arguments !=null) {
arguments.visit(this);
invokeConstructorOfMethod.call(cv);
} else {
invokeNoArgumentsConstructorOf.call(cv);
}
/*
* cv.visitLdcInsn(type);
*
* arguments.visit(this);
*
* invokeConstructorMethod.call(cv);
*/
}
public void visitPropertyExpression(PropertyExpression expression) {
// lets check if we're a fully qualified class name
String className = checkForQualifiedClass(expression);
if (className != null) {
visitClassExpression(new ClassExpression(className));
return;
}
Expression objectExpression = expression.getObjectExpression();
if (expression.getProperty().equals("class")) {
if ((objectExpression instanceof ClassExpression)) {
visitClassExpression((ClassExpression) objectExpression);
return;
}
else if (objectExpression instanceof VariableExpression) {
VariableExpression varExp = (VariableExpression) objectExpression;
className = varExp.getVariable();
try {
className = resolveClassName(className);
visitClassExpression(new ClassExpression(className));
return;
}
catch (Exception e) {
// ignore
}
}
}
if (isThisExpression(objectExpression)) {
// lets use the field expression if its available
String name = expression.getProperty();
FieldNode field = classNode.getField(name);
if (field != null) {
visitFieldExpression(new FieldExpression(field));
return;
}
}
boolean left = leftHandExpression;
// we need to clear the LHS flag to avoid "this." evaluating as ASTORE
// rather than ALOAD
leftHandExpression = false;
objectExpression.visit(this);
cv.visitLdcInsn(expression.getProperty());
if (isGroovyObject(objectExpression) && ! expression.isSafe()) {
if (left) {
setGroovyObjectPropertyMethod.call(cv);
}
else {
getGroovyObjectPropertyMethod.call(cv);
}
}
else {
if (expression.isSafe()) {
if (left) {
setPropertySafeMethod2.call(cv);
}
else {
getPropertySafeMethod.call(cv);
}
}
else {
if (left) {
setPropertyMethod2.call(cv);
}
else {
getPropertyMethod.call(cv);
}
}
}
}
protected boolean isGroovyObject(Expression objectExpression) {
return isThisExpression(objectExpression);
}
/**
* Checks if the given property expression represents a fully qualified class name
* @return the class name or null if the property is not a valid class name
*/
protected String checkForQualifiedClass(PropertyExpression expression) {
String text = expression.getText();
try {
return resolveClassName(text);
}
catch (Exception e) {
if (text.endsWith(".class")) {
text = text.substring(0, text.length() - 6);
try {
return resolveClassName(text);
}
catch (Exception e2) {
}
}
return null;
}
}
public void visitFieldExpression(FieldExpression expression) {
FieldNode field = expression.getField();
boolean isStatic = field.isStatic();
boolean holder = field.isHolder() && !isInClosureConstructor();
if (!isStatic && !leftHandExpression) {
cv.visitVarInsn(ALOAD, 0);
}
String type = field.getType();
int tempIndex = defineVariable(createVariableName("field"), "java.lang.Object", false).getIndex();
if (leftHandExpression && !holder) {
if (isInClosureConstructor()) {
helper.doCast(type);
}
else {
// this may be superflous
doConvertAndCast(type);
}
}
String ownerName =
(field.getOwner().equals(classNode.getName()))
? internalClassName
: org.objectweb.asm.Type.getInternalName(loadClass(field.getOwner()));
int opcode = isStatic ? GETSTATIC : GETFIELD;
if (holder) {
if (leftHandExpression) {
cv.visitVarInsn(ASTORE, tempIndex);
if (!isStatic)
cv.visitVarInsn(ALOAD, 0);
cv.visitFieldInsn(opcode, ownerName, expression.getFieldName(), BytecodeHelper.getTypeDescription(type));
//cv.visitInsn(SWAP); // swap the value and the this pointer . swap is used to save a temp
cv.visitVarInsn(ALOAD, tempIndex);
cv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Reference", "set", "(Ljava/lang/Object;)V");
}
else {
cv.visitFieldInsn(opcode, ownerName, expression.getFieldName(), BytecodeHelper.getTypeDescription(type));
cv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Reference", "get", "()Ljava/lang/Object;");
}
}
else {
if (leftHandExpression) {
if (!isStatic) {
opcode = PUTFIELD;
helper.store(field.getType(), tempIndex);
cv.visitVarInsn(ALOAD, 0); // static does not need this pointer
//cv.visitInsn(SWAP); // swap the value and the this pointer . swap is not type safe
// cv.visitVarInsn(ALOAD, tempIndex);
helper.load(field.getType(), tempIndex);
} else {
opcode = PUTSTATIC;
}
cv.visitFieldInsn(opcode, ownerName, expression.getFieldName(), BytecodeHelper.getTypeDescription(type));
}else {
cv.visitFieldInsn(opcode, ownerName, expression.getFieldName(), BytecodeHelper.getTypeDescription(type));
if (BytecodeHelper.isPrimitiveType(type)) {
helper.box(type);
}
}
}
}
protected void visitOuterFieldExpression(FieldExpression expression, ClassNode outerClassNode, int steps, boolean first ) {
int valueIdx = defineVariable(createVariableName("temp"), "java.lang.Object", false).getIndex();
if (leftHandExpression && first) {
cv.visitVarInsn(ASTORE, valueIdx);
}
FieldNode field = expression.getField();
boolean isStatic = field.isStatic();
if (steps > 1 || !isStatic) {
cv.visitVarInsn(ALOAD, 0);
cv.visitFieldInsn(
GETFIELD,
internalClassName,
"owner",
BytecodeHelper.getTypeDescription(outerClassNode.getName()));
}
if( steps == 1 ) {
int opcode = (leftHandExpression) ? ((isStatic) ? PUTSTATIC : PUTFIELD) : ((isStatic) ? GETSTATIC : GETFIELD);
String ownerName = BytecodeHelper.getClassInternalName(outerClassNode.getName());
if (leftHandExpression) {
cv.visitVarInsn(ALOAD, valueIdx);
boolean holder = field.isHolder() && !isInClosureConstructor();
if ( !holder) {
doConvertAndCast(field.getType());
}
}
cv.visitFieldInsn(opcode, ownerName, expression.getFieldName(), BytecodeHelper.getTypeDescription(field.getType()));
}
else {
visitOuterFieldExpression( expression, outerClassNode.getOuterClass(), steps - 1, false );
}
}
/**
* Visits a bare (unqualified) variable expression.
*/
public void visitVariableExpression(VariableExpression expression) {
String variableName = expression.getVariable();
// SPECIAL CASES
// "this" for static methods is the Class instance
if (isStaticMethod() && variableName.equals("this")) {
visitClassExpression(new ClassExpression(classNode.getName()));
return; // <<< FLOW CONTROL <<<<<<<<<
}
// "super" also requires special handling
if (variableName.equals("super")) {
visitClassExpression(new ClassExpression(classNode.getSuperClass()));
return; // <<< FLOW CONTROL <<<<<<<<<
}
// class names return a Class instance, too
if (!variableName.equals("this")) {
String className = resolveClassName(variableName);
if (className != null) {
if (leftHandExpression) {
throw new RuntimeParserException(
"Cannot use a class expression on the left hand side of an assignment",
expression);
}
visitClassExpression(new ClassExpression(className));
return; // <<< FLOW CONTROL <<<<<<<<<
}
}
// GENERAL VARIABLE LOOKUP
// We are handling only unqualified variables here. Therefore,
// we do not care about accessors, because local access doesn't
// go through them. Therefore, precedence is as follows:
// 1) local variables, nearest block first
// 2) class fields
// 3) repeat search from 2) in next outer class
boolean handled = false;
Variable variable = (Variable)variableStack.get( variableName );
if( variable != null ) {
if( variable.isProperty() ) {
processPropertyVariable( variableName, variable );
}
else {
processStackVariable( variableName, variable );
}
handled = true;
}
// Loop through outer classes for fields
else {
int steps = 0;
ClassNode current = classNode;
FieldNode field = null;
do {
if( (field = current.getField(variableName)) != null ) {
break;
}
steps++;
} while( (current = current.getOuterClass()) != null );
if( field != null ) {
processFieldAccess( variableName, field, steps );
handled = true;
}
}
// Finally, if unhandled, create a variable for it.
// Except there a stack variable should be created,
// we define the variable as a property accessor and
// let other parts of the classgen report the error
// if the property doesn't exist.
if( !handled ) {
String variableType = expression.getType();
variable = defineVariable( variableName, variableType );
if( isInScriptBody() || !leftHandExpression ) {
variable.setProperty( true );
processPropertyVariable( variableName, variable );
}
else {
processStackVariable( variableName, variable );
}
}
}
protected void processStackVariable( String name, Variable variable ) {
String type = variable.getTypeName();
int index = variable.getIndex();
boolean holder = variable.isHolder() && !passingClosureParams;
if( leftHandExpression ) {
if (holder) {
int tempIndex = defineVariable(createVariableName("reference"), type, false).getIndex();
cv.visitVarInsn(ASTORE, tempIndex);
cv.visitVarInsn(ALOAD, index);
//cv.visitInsn(SWAP); // assuming the value is already on the stack
cv.visitVarInsn(ALOAD, tempIndex);
cv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Reference", "set", "(Ljava/lang/Object;)V");
}
else {
helper.store("objref", index); // br seems right hand values on the stack are always object refs, primitives boxed
//cv.visitVarInsn(ASTORE, index);
}
}
else {
if (holder) {
cv.visitVarInsn(ALOAD, index);
cv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Reference", "get", "()Ljava/lang/Object;");
}
else {
cv.visitVarInsn(ALOAD, index);
}
}
}
protected void processPropertyVariable( String name, Variable variable ) {
if (variable.isHolder() && passingClosureParams && isInScriptBody() ) {
// lets create a ScriptReference to pass into the closure
cv.visitTypeInsn(NEW, "org/codehaus/groovy/runtime/ScriptReference");
cv.visitInsn(DUP);
loadThisOrOwner();
cv.visitLdcInsn(name);
cv.visitMethodInsn(
INVOKESPECIAL,
"org/codehaus/groovy/runtime/ScriptReference",
"<init>",
"(Lgroovy/lang/Script;Ljava/lang/String;)V");
}
else {
visitPropertyExpression(new PropertyExpression(VariableExpression.THIS_EXPRESSION, name));
}
}
protected void processFieldAccess( String name, FieldNode field, int steps ) {
FieldExpression expression = new FieldExpression(field);
if( steps == 0 ) {
visitFieldExpression( expression );
}
else {
visitOuterFieldExpression( expression, classNode.getOuterClass(), steps, true );
}
}
/**
* @return true if we are in a script body, where all variables declared are no longer
* local variables but are properties
*/
protected boolean isInScriptBody() {
if (classNode.isScriptBody()) {
return true;
}
else {
return classNode.isScript() && methodNode != null && methodNode.getName().equals("run");
}
}
/**
* @return true if this expression will have left a value on the stack
* that must be popped
*/
protected boolean isPopRequired(Expression expression) {
if (expression instanceof MethodCallExpression) {
return !MethodCallExpression.isSuperMethodCall((MethodCallExpression) expression);
}
if (expression instanceof BinaryExpression) {
BinaryExpression binExp = (BinaryExpression) expression;
switch (binExp.getOperation().getType()) {
case Types.EQUAL :
case Types.PLUS_EQUAL :
case Types.MINUS_EQUAL :
case Types.MULTIPLY_EQUAL :
case Types.DIVIDE_EQUAL :
case Types.MOD_EQUAL :
return false;
}
}
return true;
}
protected boolean firstStatementIsSuperInit(Statement code) {
ExpressionStatement expStmt = null;
if (code instanceof ExpressionStatement) {
expStmt = (ExpressionStatement) code;
}
else if (code instanceof BlockStatement) {
BlockStatement block = (BlockStatement) code;
if (!block.getStatements().isEmpty()) {
Object expr = block.getStatements().get(0);
if (expr instanceof ExpressionStatement) {
expStmt = (ExpressionStatement) expr;
}
}
}
if (expStmt != null) {
Expression expr = expStmt.getExpression();
if (expr instanceof MethodCallExpression) {
MethodCallExpression call = (MethodCallExpression) expr;
if (MethodCallExpression.isSuperMethodCall(call)) {
// not sure which one is constantly used as the super class ctor call. To cover both for now
return call.getMethod().equals("<init>") || call.getMethod().equals("super");
}
}
}
return false;
}
protected void createSyntheticStaticFields() {
for (Iterator iter = syntheticStaticFields.iterator(); iter.hasNext();) {
String staticFieldName = (String) iter.next();
// generate a field node
cw.visitField(ACC_STATIC + ACC_SYNTHETIC, staticFieldName, "Ljava/lang/Class;", null, null);
}
if (!syntheticStaticFields.isEmpty()) {
cv =
cw.visitMethod(
ACC_STATIC + ACC_SYNTHETIC,
"class$",
"(Ljava/lang/String;)Ljava/lang/Class;",
null,
null);
helper = new BytecodeHelper(cv);
Label l0 = new Label();
cv.visitLabel(l0);
cv.visitVarInsn(ALOAD, 0);
cv.visitMethodInsn(INVOKESTATIC, "java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;");
Label l1 = new Label();
cv.visitLabel(l1);
cv.visitInsn(ARETURN);
Label l2 = new Label();
cv.visitLabel(l2);
cv.visitVarInsn(ASTORE, 1);
cv.visitTypeInsn(NEW, "java/lang/NoClassDefFoundError");
cv.visitInsn(DUP);
cv.visitVarInsn(ALOAD, 1);
cv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/ClassNotFoundException", "getMessage", "()Ljava/lang/String;");
cv.visitMethodInsn(INVOKESPECIAL, "java/lang/NoClassDefFoundError", "<init>", "(Ljava/lang/String;)V");
cv.visitInsn(ATHROW);
cv.visitTryCatchBlock(l0, l2, l2, "java/lang/ClassNotFoundException"); // br using l2 as the 2nd param seems create the right table entry
cv.visitMaxs(3, 2);
cw.visitEnd();
}
}
public void visitClassExpression(ClassExpression expression) {
String type = expression.getText();
//type = checkValidType(type, expression, "Must be a valid type name for a constructor call");
if (BytecodeHelper.isPrimitiveType(type)) {
String objectType = BytecodeHelper.getObjectTypeForPrimitive(type);
cv.visitFieldInsn(GETSTATIC, BytecodeHelper.getClassInternalName(objectType), "TYPE", "Ljava/lang/Class;");
}
else {
final String staticFieldName =
(type.equals(classNode.getName())) ? "class$0" : "class$" + type.replace('.', '$');
syntheticStaticFields.add(staticFieldName);
cv.visitFieldInsn(GETSTATIC, internalClassName, staticFieldName, "Ljava/lang/Class;");
Label l0 = new Label();
cv.visitJumpInsn(IFNONNULL, l0);
cv.visitLdcInsn(type);
cv.visitMethodInsn(INVOKESTATIC, internalClassName, "class$", "(Ljava/lang/String;)Ljava/lang/Class;");
cv.visitInsn(DUP);
cv.visitFieldInsn(PUTSTATIC, internalClassName, staticFieldName, "Ljava/lang/Class;");
Label l1 = new Label();
cv.visitJumpInsn(GOTO, l1);
cv.visitLabel(l0);
cv.visitFieldInsn(GETSTATIC, internalClassName, staticFieldName, "Ljava/lang/Class;");
cv.visitLabel(l1);
}
}
public void visitRangeExpression(RangeExpression expression) {
leftHandExpression = false;
expression.getFrom().visit(this);
leftHandExpression = false;
expression.getTo().visit(this);
helper.pushConstant(expression.isInclusive());
createRangeMethod.call(cv);
}
public void visitMapEntryExpression(MapEntryExpression expression) {
}
public void visitMapExpression(MapExpression expression) {
List entries = expression.getMapEntryExpressions();
int size = entries.size();
helper.pushConstant(size * 2);
cv.visitTypeInsn(ANEWARRAY, "java/lang/Object");
int i = 0;
for (Iterator iter = entries.iterator(); iter.hasNext();) {
MapEntryExpression entry = (MapEntryExpression) iter.next();
cv.visitInsn(DUP);
helper.pushConstant(i++);
visitAndAutobox(entry.getKeyExpression());
cv.visitInsn(AASTORE);
cv.visitInsn(DUP);
helper.pushConstant(i++);
visitAndAutobox(entry.getValueExpression());
cv.visitInsn(AASTORE);
}
createMapMethod.call(cv);
}
public void visitTupleExpression(TupleExpression expression) {
int size = expression.getExpressions().size();
helper.pushConstant(size);
cv.visitTypeInsn(ANEWARRAY, "java/lang/Object");
for (int i = 0; i < size; i++) {
cv.visitInsn(DUP);
helper.pushConstant(i);
visitAndAutobox(expression.getExpression(i));
cv.visitInsn(AASTORE);
}
//createTupleMethod.call(cv);
}
public void visitArrayExpression(ArrayExpression expression) {
String type = expression.getType();
String typeName = BytecodeHelper.getClassInternalName(type);
Expression sizeExpression = expression.getSizeExpression();
if (sizeExpression != null) {
// lets convert to an int
visitAndAutobox(sizeExpression);
asIntMethod.call(cv);
cv.visitTypeInsn(ANEWARRAY, typeName);
}
else {
int size = expression.getExpressions().size();
helper.pushConstant(size);
cv.visitTypeInsn(ANEWARRAY, typeName);
for (int i = 0; i < size; i++) {
cv.visitInsn(DUP);
helper.pushConstant(i);
Expression elementExpression = expression.getExpression(i);
if (elementExpression == null) {
ConstantExpression.NULL.visit(this);
}
else {
if(!type.equals(elementExpression.getClass().getName())) {
visitCastExpression(new CastExpression(type, elementExpression));
}
else {
visitAndAutobox(elementExpression);
}
}
cv.visitInsn(AASTORE);
}
}
}
public void visitListExpression(ListExpression expression) {
int size = expression.getExpressions().size();
helper.pushConstant(size);
cv.visitTypeInsn(ANEWARRAY, "java/lang/Object");
for (int i = 0; i < size; i++) {
cv.visitInsn(DUP);
helper.pushConstant(i);
visitAndAutobox(expression.getExpression(i));
cv.visitInsn(AASTORE);
}
createListMethod.call(cv);
}
public void visitGStringExpression(GStringExpression expression) {
int size = expression.getValues().size();
helper.pushConstant(size);
cv.visitTypeInsn(ANEWARRAY, "java/lang/Object");
for (int i = 0; i < size; i++) {
cv.visitInsn(DUP);
helper.pushConstant(i);
visitAndAutobox(expression.getValue(i));
cv.visitInsn(AASTORE);
}
int paramIdx = defineVariable(createVariableName("iterator"), "java.lang.Object", false).getIndex();
cv.visitVarInsn(ASTORE, paramIdx);
ClassNode innerClass = createGStringClass(expression);
addInnerClass(innerClass);
String innerClassinternalName = BytecodeHelper.getClassInternalName(innerClass.getName());
cv.visitTypeInsn(NEW, innerClassinternalName);
cv.visitInsn(DUP);
cv.visitVarInsn(ALOAD, paramIdx);
cv.visitMethodInsn(INVOKESPECIAL, innerClassinternalName, "<init>", "([Ljava/lang/Object;)V");
}
// Implementation methods
protected boolean addInnerClass(ClassNode innerClass) {
innerClass.setModule(classNode.getModule());
return innerClasses.add(innerClass);
}
protected ClassNode createClosureClass(ClosureExpression expression) {
ClassNode owner = getOutermostClass();
boolean parentIsInnerClass = owner instanceof InnerClassNode;
String outerClassName = owner.getName();
String name = outerClassName + "$"
+ context.getNextClosureInnerName(owner, classNode, methodNode); // br added a more infomative name
boolean staticMethodOrInStaticClass = isStaticMethod() || classNode.isStaticClass();
if (staticMethodOrInStaticClass) {
outerClassName = "java.lang.Class";
}
Parameter[] parameters = expression.getParameters();
if (parameters == null || parameters.length == 0) {
// lets create a default 'it' parameter
parameters = new Parameter[] { new Parameter("it")};
}
Parameter[] localVariableParams = getClosureSharedVariables(expression);
InnerClassNode answer = new InnerClassNode(owner, name, ACC_SUPER, "groovy.lang.Closure"); // clsures are local inners and not public
answer.setEnclosingMethod(this.methodNode);
if (staticMethodOrInStaticClass) {
answer.setStaticClass(true);
}
if (isInScriptBody()) {
answer.setScriptBody(true);
}
MethodNode method =
answer.addMethod("doCall", ACC_PUBLIC, "java.lang.Object", parameters, expression.getCode());
method.setLineNumber(expression.getLineNumber());
method.setColumnNumber(expression.getColumnNumber());
VariableScope varScope = expression.getVariableScope();
if (varScope == null) {
throw new RuntimeException(
"Must have a VariableScope by now! for expression: " + expression + " class: " + name);
}
else {
method.setVariableScope(varScope);
}
if (parameters.length > 1
|| (parameters.length == 1
&& parameters[0].getType() != null
&& !parameters[0].getType().equals("java.lang.Object"))) {
// lets add a typesafe call method
answer.addMethod(
"call",
ACC_PUBLIC,
"java.lang.Object",
parameters,
new ReturnStatement(
new MethodCallExpression(
VariableExpression.THIS_EXPRESSION,
"doCall",
new ArgumentListExpression(parameters))));
}
FieldNode ownerField = answer.addField("owner", ACC_PRIVATE, outerClassName, null);
// lets make the constructor
BlockStatement block = new BlockStatement();
block.addStatement(
new ExpressionStatement(
new MethodCallExpression(
new VariableExpression("super"),
"<init>",
new VariableExpression("_outerInstance"))));
block.addStatement(
new ExpressionStatement(
new BinaryExpression(
new FieldExpression(ownerField),
Token.newSymbol(Types.EQUAL, -1, -1),
new VariableExpression("_outerInstance"))));
// lets assign all the parameter fields from the outer context
for (int i = 0; i < localVariableParams.length; i++) {
Parameter param = localVariableParams[i];
String paramName = param.getName();
boolean holder = mutableVars.contains(paramName);
Expression initialValue = null;
String type = param.getType();
FieldNode paramField = null;
if (holder) {
initialValue = new VariableExpression(paramName);
type = Reference.class.getName();
param.makeReference();
paramField = answer.addField(paramName, ACC_PRIVATE, type, initialValue);
paramField.setHolder(true);
String realType = param.getRealType();
String methodName = Verifier.capitalize(paramName);
// lets add a getter & setter
Expression fieldExp = new FieldExpression(paramField);
answer.addMethod(
"get" + methodName,
ACC_PUBLIC,
realType,
Parameter.EMPTY_ARRAY,
new ReturnStatement(fieldExp));
/*
answer.addMethod(
"set" + methodName,
ACC_PUBLIC,
"void",
new Parameter[] { new Parameter(realType, "__value") },
new ExpressionStatement(
new BinaryExpression(expression, Token.newSymbol(Types.EQUAL, 0, 0), new VariableExpression("__value"))));
*/
}
else {
PropertyNode propertyNode = answer.addProperty(paramName, ACC_PUBLIC, type, initialValue, null, null);
paramField = propertyNode.getField();
block.addStatement(
new ExpressionStatement(
new BinaryExpression(
new FieldExpression(paramField),
Token.newSymbol(Types.EQUAL, -1, -1),
new VariableExpression(paramName))));
}
}
Parameter[] params = new Parameter[2 + localVariableParams.length];
params[0] = new Parameter(outerClassName, "_outerInstance");
params[1] = new Parameter("java.lang.Object", "_delegate");
System.arraycopy(localVariableParams, 0, params, 2, localVariableParams.length);
answer.addConstructor(ACC_PUBLIC, params, block);
return answer;
}
protected ClassNode getOutermostClass() {
if (outermostClass == null) {
outermostClass = classNode;
while (outermostClass instanceof InnerClassNode) {
outermostClass = outermostClass.getOuterClass();
}
}
return outermostClass;
}
protected ClassNode createGStringClass(GStringExpression expression) {
ClassNode owner = classNode;
if (owner instanceof InnerClassNode) {
owner = owner.getOuterClass();
}
String outerClassName = owner.getName();
String name = outerClassName + "$" + context.getNextInnerClassIdx();
InnerClassNode answer = new InnerClassNode(owner, name, ACC_SUPER, GString.class.getName());
answer.setEnclosingMethod(this.methodNode);
FieldNode stringsField =
answer.addField(
"strings",
ACC_PRIVATE /*| ACC_STATIC*/,
"java.lang.String[]",
new ArrayExpression("java.lang.String", expression.getStrings()));
answer.addMethod(
"getStrings",
ACC_PUBLIC,
"java.lang.String[]",
Parameter.EMPTY_ARRAY,
new ReturnStatement(new FieldExpression(stringsField)));
// lets make the constructor
BlockStatement block = new BlockStatement();
block.addStatement(
new ExpressionStatement(
new MethodCallExpression(new VariableExpression("super"), "<init>", new VariableExpression("values"))));
Parameter[] contructorParams = new Parameter[] { new Parameter("java.lang.Object[]", "values")};
answer.addConstructor(ACC_PUBLIC, contructorParams, block);
return answer;
}
protected void doConvertAndCast(String type) {
if (!type.equals("java.lang.Object")) {
/** todo should probably support array coercions */
if (!type.endsWith("[]") && isValidTypeForCast(type)) {
visitClassExpression(new ClassExpression(type));
asTypeMethod.call(cv);
}
helper.doCast(type);
}
}
protected void evaluateLogicalOrExpression(BinaryExpression expression) {
visitBooleanExpression(new BooleanExpression(expression.getLeftExpression()));
Label l0 = new Label();
Label l2 = new Label();
cv.visitJumpInsn(IFEQ, l0);
cv.visitLabel(l2);
visitConstantExpression(ConstantExpression.TRUE);
Label l1 = new Label();
cv.visitJumpInsn(GOTO, l1);
cv.visitLabel(l0);
visitBooleanExpression(new BooleanExpression(expression.getRightExpression()));
cv.visitJumpInsn(IFNE, l2);
visitConstantExpression(ConstantExpression.FALSE);
cv.visitLabel(l1);
}
protected void evaluateLogicalAndExpression(BinaryExpression expression) {
visitBooleanExpression(new BooleanExpression(expression.getLeftExpression()));
Label l0 = new Label();
cv.visitJumpInsn(IFEQ, l0);
visitBooleanExpression(new BooleanExpression(expression.getRightExpression()));
cv.visitJumpInsn(IFEQ, l0);
visitConstantExpression(ConstantExpression.TRUE);
Label l1 = new Label();
cv.visitJumpInsn(GOTO, l1);
cv.visitLabel(l0);
visitConstantExpression(ConstantExpression.FALSE);
cv.visitLabel(l1);
}
protected void evaluateBinaryExpression(String method, BinaryExpression expression) {
Expression leftExpression = expression.getLeftExpression();
leftHandExpression = false;
leftExpression.visit(this);
cv.visitLdcInsn(method);
leftHandExpression = false;
new ArgumentListExpression(new Expression[] { expression.getRightExpression()}).visit(this);
// expression.getRightExpression().visit(this);
invokeMethodMethod.call(cv);
}
protected void evaluateCompareTo(BinaryExpression expression) {
Expression leftExpression = expression.getLeftExpression();
leftHandExpression = false;
leftExpression.visit(this);
expression.getRightExpression().visit(this);
compareToMethod.call(cv);
}
protected void evaluateBinaryExpressionWithAsignment(String method, BinaryExpression expression) {
Expression leftExpression = expression.getLeftExpression();
if (leftExpression instanceof BinaryExpression) {
BinaryExpression leftBinExpr = (BinaryExpression) leftExpression;
if (leftBinExpr.getOperation().getType() == Types.LEFT_SQUARE_BRACKET) {
// lets replace this assignment to a subscript operator with a
// method call
// e.g. x[5] += 10
// -> (x, [], 5), =, x[5] + 10
// -> methodCall(x, "putAt", [5, methodCall(x[5], "plus", 10)])
MethodCallExpression methodCall =
new MethodCallExpression(
expression.getLeftExpression(),
method,
new ArgumentListExpression(new Expression[] { expression.getRightExpression()}));
Expression safeIndexExpr = createReusableExpression(leftBinExpr.getRightExpression());
visitMethodCallExpression(
new MethodCallExpression(
leftBinExpr.getLeftExpression(),
"putAt",
new ArgumentListExpression(new Expression[] { safeIndexExpr, methodCall })));
cv.visitInsn(POP);
return;
}
}
evaluateBinaryExpression(method, expression);
leftHandExpression = true;
evaluateExpression(leftExpression);
leftHandExpression = false;
}
protected void evaluateBinaryExpression(MethodCaller compareMethod, BinaryExpression expression) {
Expression leftExpression = expression.getLeftExpression();
/*
if (isNonStaticField(leftExpression)) {
cv.visitVarInsn(ALOAD, 0);
}
*/
leftHandExpression = false;
evaluateExpression(leftExpression);
leftHandExpression = false;
evaluateExpression(expression.getRightExpression());
// now lets invoke the method
compareMethod.call(cv);
}
protected void evaluateEqual(BinaryExpression expression) {
Expression leftExpression = expression.getLeftExpression();
if (leftExpression instanceof BinaryExpression) {
BinaryExpression leftBinExpr = (BinaryExpression) leftExpression;
if (leftBinExpr.getOperation().getType() == Types.LEFT_SQUARE_BRACKET) {
// lets replace this assignment to a subscript operator with a
// method call
// e.g. x[5] = 10
// -> (x, [], 5), =, 10
// -> methodCall(x, "putAt", [5, 10])
visitMethodCallExpression(
new MethodCallExpression(
leftBinExpr.getLeftExpression(),
"putAt",
new ArgumentListExpression(
new Expression[] { leftBinExpr.getRightExpression(), expression.getRightExpression()})));
cv.visitInsn(POP);
return;
}
}
// br we'll load this pointer later right where we really need it
// lets evaluate the RHS then hopefully the LHS will be a field
leftHandExpression = false;
Expression rightExpression = expression.getRightExpression();
String type = getLHSType(leftExpression);
if (type != null) {
//System.out.println("### expression: " + leftExpression);
//System.out.println("### type: " + type);
// lets not cast for primitive types as we handle these in field setting etc
if (BytecodeHelper.isPrimitiveType(type)) {
rightExpression.visit(this);
}
else {
visitCastExpression(new CastExpression(type, rightExpression));
}
}
else {
visitAndAutobox(rightExpression);
}
leftHandExpression = true;
leftExpression.visit(this);
leftHandExpression = false;
}
/**
* Deduces the type name required for some casting
*
* @return the type of the given (LHS) expression or null if it is java.lang.Object or it cannot be deduced
*/
protected String getLHSType(Expression leftExpression) {
if (leftExpression instanceof VariableExpression) {
VariableExpression varExp = (VariableExpression) leftExpression;
String type = varExp.getType();
if (isValidTypeForCast(type)) {
return type;
}
String variableName = varExp.getVariable();
Variable variable = (Variable) variableStack.get(variableName);
if (variable != null) {
if (variable.isHolder() || variable.isProperty()) {
return null;
}
type = variable.getTypeName();
if (isValidTypeForCast(type)) {
return type;
}
}
else {
FieldNode field = classNode.getField(variableName);
if (field == null) {
field = classNode.getOuterField(variableName);
}
if (field != null) {
type = field.getType();
if (!field.isHolder() && isValidTypeForCast(type)) {
return type;
}
}
}
}
return null;
}
protected boolean isValidTypeForCast(String type) {
return type != null && !type.equals("java.lang.Object") && !type.equals("groovy.lang.Reference") && !BytecodeHelper.isPrimitiveType(type);
}
protected void visitAndAutobox(Expression expression) {
expression.visit(this);
if (comparisonExpression(expression)) {
Label l0 = new Label();
cv.visitJumpInsn(IFEQ, l0);
cv.visitFieldInsn(GETSTATIC, "java/lang/Boolean", "TRUE", "Ljava/lang/Boolean;");
Label l1 = new Label();
cv.visitJumpInsn(GOTO, l1);
cv.visitLabel(l0);
cv.visitFieldInsn(GETSTATIC, "java/lang/Boolean", "FALSE", "Ljava/lang/Boolean;");
cv.visitLabel(l1);
}
}
protected void evaluatePrefixMethod(String method, Expression expression) {
if (isNonStaticField(expression) && ! isHolderVariable(expression) && !isStaticMethod()) {
cv.visitVarInsn(ALOAD, 0);
}
expression.visit(this);
cv.visitLdcInsn(method);
invokeNoArgumentsMethod.call(cv);
leftHandExpression = true;
expression.visit(this);
leftHandExpression = false;
expression.visit(this);
}
protected void evaluatePostfixMethod(String method, Expression expression) {
// if (isNonStaticField(expression) && ! isHolderVariable(expression) && !isStaticMethod()) {
// cv.visitVarInsn(ALOAD, 0); // br again, loading this pointer is moved to staying close to variable
leftHandExpression = false;
expression.visit(this);
int tempIdx = defineVariable(createVariableName("postfix"), "java.lang.Object", false).getIndex();
cv.visitVarInsn(ASTORE, tempIdx);
cv.visitVarInsn(ALOAD, tempIdx);
cv.visitLdcInsn(method);
invokeNoArgumentsMethod.call(cv);
leftHandExpression = true;
expression.visit(this);
leftHandExpression = false;
cv.visitVarInsn(ALOAD, tempIdx);
}
protected boolean isHolderVariable(Expression expression) {
if (expression instanceof FieldExpression) {
FieldExpression fieldExp = (FieldExpression) expression;
return fieldExp.getField().isHolder();
}
if (expression instanceof VariableExpression) {
VariableExpression varExp = (VariableExpression) expression;
Variable variable = (Variable) variableStack.get(varExp.getVariable());
if (variable != null) {
return variable.isHolder();
}
FieldNode field = classNode.getField(varExp.getVariable());
if (field != null) {
return field.isHolder();
}
}
return false;
}
protected void evaluateInstanceof(BinaryExpression expression) {
expression.getLeftExpression().visit(this);
Expression rightExp = expression.getRightExpression();
String className = null;
if (rightExp instanceof ClassExpression) {
ClassExpression classExp = (ClassExpression) rightExp;
className = classExp.getType();
}
else {
throw new RuntimeException(
"Right hand side of the instanceof keyworld must be a class name, not: " + rightExp);
}
className = checkValidType(className, expression, "Must be a valid type name for an instanceof statement");
String classInternalName = BytecodeHelper.getClassInternalName(className);
cv.visitTypeInsn(INSTANCEOF, classInternalName);
}
/**
* @return true if the given argument expression requires the stack, in
* which case the arguments are evaluated first, stored in the
* variable stack and then reloaded to make a method call
*/
protected boolean argumentsUseStack(Expression arguments) {
return arguments instanceof TupleExpression || arguments instanceof ClosureExpression;
}
/**
* @return true if the given expression represents a non-static field
*/
protected boolean isNonStaticField(Expression expression) {
FieldNode field = null;
if (expression instanceof VariableExpression) {
VariableExpression varExp = (VariableExpression) expression;
field = classNode.getField(varExp.getVariable());
}
else if (expression instanceof FieldExpression) {
FieldExpression fieldExp = (FieldExpression) expression;
field = classNode.getField(fieldExp.getFieldName());
}
else if (expression instanceof PropertyExpression) {
PropertyExpression fieldExp = (PropertyExpression) expression;
field = classNode.getField(fieldExp.getProperty());
}
if (field != null) {
return !field.isStatic();
}
return false;
}
protected boolean isThisExpression(Expression expression) {
if (expression instanceof VariableExpression) {
VariableExpression varExp = (VariableExpression) expression;
return varExp.getVariable().equals("this");
}
return false;
}
/**
* For assignment expressions, return a safe expression for the LHS we can use
* to return the value
*/
protected Expression createReturnLHSExpression(Expression expression) {
if (expression instanceof BinaryExpression) {
BinaryExpression binExpr = (BinaryExpression) expression;
if (binExpr.getOperation().isA(Types.ASSIGNMENT_OPERATOR)) {
return createReusableExpression(binExpr.getLeftExpression());
}
}
return null;
}
protected Expression createReusableExpression(Expression expression) {
ExpressionTransformer transformer = new ExpressionTransformer() {
public Expression transform(Expression expression) {
if (expression instanceof PostfixExpression) {
PostfixExpression postfixExp = (PostfixExpression) expression;
return postfixExp.getExpression();
}
else if (expression instanceof PrefixExpression) {
PrefixExpression prefixExp = (PrefixExpression) expression;
return prefixExp.getExpression();
}
return expression;
}
};
// could just be a postfix / prefix expression or nested inside some other expression
return transformer.transform(expression.transformExpression(transformer));
}
protected boolean comparisonExpression(Expression expression) {
if (expression instanceof BinaryExpression) {
BinaryExpression binExpr = (BinaryExpression) expression;
switch (binExpr.getOperation().getType()) {
case Types.COMPARE_EQUAL :
case Types.MATCH_REGEX :
case Types.COMPARE_GREATER_THAN :
case Types.COMPARE_GREATER_THAN_EQUAL :
case Types.COMPARE_LESS_THAN :
case Types.COMPARE_LESS_THAN_EQUAL :
case Types.COMPARE_IDENTICAL :
case Types.COMPARE_NOT_EQUAL :
case Types.KEYWORD_INSTANCEOF :
return true;
}
}
else if (expression instanceof BooleanExpression) {
return true;
}
return false;
}
protected void onLineNumber(ASTNode statement) {
int number = statement.getLineNumber();
if (number >= 0 && cv != null) {
Label l = new Label();
cv.visitLabel(l);
cv.visitLineNumber(number, l);
}
}
protected VariableScope getVariableScope() {
if (variableScope == null) {
if (methodNode != null) {
// if we're a closure method we'll have our variable scope already created
variableScope = methodNode.getVariableScope();
if (variableScope == null) {
variableScope = new VariableScope();
methodNode.setVariableScope(variableScope);
VariableScopeCodeVisitor visitor = new VariableScopeCodeVisitor(variableScope);
visitor.setParameters(methodNode.getParameters());
Statement code = methodNode.getCode();
if (code != null) {
code.visit(visitor);
}
}
addFieldsToVisitor(variableScope);
}
else if (constructorNode != null) {
variableScope = new VariableScope();
constructorNode.setVariableScope(variableScope);
VariableScopeCodeVisitor visitor = new VariableScopeCodeVisitor(variableScope);
visitor.setParameters(constructorNode.getParameters());
Statement code = constructorNode.getCode();
if (code != null) {
code.visit(visitor);
}
addFieldsToVisitor(variableScope);
}
else {
throw new RuntimeException("Can't create a variable scope outside of a method or constructor");
}
}
return variableScope;
}
/**
* @return a list of parameters for each local variable which needs to be
* passed into a closure
*/
protected Parameter[] getClosureSharedVariables(ClosureExpression expression) {
List vars = new ArrayList();
// First up, get the scopes for outside and inside the closure.
// The inner scope must cover all nested closures, as well, as
// everything that will be needed must be imported.
VariableScope outerScope = getVariableScope().createRecursiveParentScope();
VariableScope innerScope = expression.getVariableScope();
if (innerScope == null) {
System.out.println(
"No variable scope for: " + expression + " method: " + methodNode + " constructor: " + constructorNode);
innerScope = new VariableScope(getVariableScope());
}
else {
innerScope = innerScope.createRecursiveChildScope();
}
// DeclaredVariables include any name that was assigned to within
// the scope. ReferencedVariables include any name that was read
// from within the scope. We get the sets from each and must piece
// together the stack variable import list for the closure. Note
// that we don't worry about field variables here, as we don't have
// to do anything special with them. Stack variables, on the other
// hand, have to be wrapped up in References for use.
Set outerDecls = outerScope.getDeclaredVariables();
Set outerRefs = outerScope.getReferencedVariables();
Set innerDecls = innerScope.getDeclaredVariables();
Set innerRefs = innerScope.getReferencedVariables();
// So, we care about any name referenced in the closure UNLESS:
// 1) it's not declared in the outer context;
// 2) it's a parameter;
// 3) it's a field in the context class that isn't overridden
// by a stack variable in the outer context.
// BUG: We don't actually have the necessary information to do
// this right! The outer declarations don't distinguish
// between assignments and variable declarations. Therefore
// we can't tell when field variables have been overridden
// by stack variables in the outer context. This must
// be fixed!
Set varSet = new HashSet();
for (Iterator iter = innerRefs.iterator(); iter.hasNext();) {
String var = (String) iter.next();
// lets not pass in fields from the most-outer class, but pass in values from an outer closure
if (outerDecls.contains(var) && (isNotFieldOfOutermostClass(var))) {
String type = getVariableType(var);
vars.add(new Parameter(type, var));
varSet.add(var);
}
}
for (Iterator iter = outerRefs.iterator(); iter.hasNext();) {
String var = (String) iter.next();
// lets not pass in fields from the most-outer class, but pass in values from an outer closure
if (innerDecls.contains(var) && (isNotFieldOfOutermostClass(var)) && !varSet.contains(var)) {
String type = getVariableType(var);
vars.add(new Parameter(type, var));
}
}
Parameter[] answer = new Parameter[vars.size()];
vars.toArray(answer);
return answer;
}
protected boolean isNotFieldOfOutermostClass(String var) {
//return classNode.getField(var) == null || isInnerClass();
return getOutermostClass().getField(var) == null;
}
protected void findMutableVariables() {
/*
VariableScopeCodeVisitor outerVisitor = new VariableScopeCodeVisitor(true);
node.getCode().visit(outerVisitor);
addFieldsToVisitor(outerVisitor);
VariableScopeCodeVisitor innerVisitor = outerVisitor.getClosureVisitor();
*/
VariableScope outerScope = getVariableScope();
// lets create a scope concatenating all the closure expressions
VariableScope innerScope = outerScope.createCompositeChildScope();
Set outerDecls = outerScope.getDeclaredVariables();
Set outerRefs = outerScope.getReferencedVariables();
Set innerDecls = innerScope.getDeclaredVariables();
Set innerRefs = innerScope.getReferencedVariables();
mutableVars.clear();
for (Iterator iter = innerDecls.iterator(); iter.hasNext();) {
String var = (String) iter.next();
if ((outerDecls.contains(var) || outerRefs.contains(var)) && classNode.getField(var) == null) {
mutableVars.add(var);
}
}
// we may call the closure twice and modify the variable in the outer scope
// so for now lets assume that all variables are mutable
for (Iterator iter = innerRefs.iterator(); iter.hasNext();) {
String var = (String) iter.next();
if (outerDecls.contains(var) && classNode.getField(var) == null) {
mutableVars.add(var);
}
}
// System.out.println();
// System.out.println("method: " + methodNode + " classNode: " + classNode);
// System.out.println("child scopes: " + outerScope.getChildren());
// System.out.println("outerDecls: " + outerDecls);
// System.out.println("outerRefs: " + outerRefs);
// System.out.println("innerDecls: " + innerDecls);
// System.out.println("innerRefs: " + innerRefs);
}
protected void addFieldsToVisitor(VariableScope scope) {
for (Iterator iter = classNode.getFields().iterator(); iter.hasNext();) {
FieldNode field = (FieldNode) iter.next();
String name = field.getName();
scope.getDeclaredVariables().add(name);
scope.getReferencedVariables().add(name);
}
}
private boolean isInnerClass() {
return classNode instanceof InnerClassNode;
}
protected String getVariableType(String name) {
Variable variable = (Variable) variableStack.get(name);
if (variable != null) {
return variable.getTypeName();
}
return null;
}
protected void resetVariableStack(Parameter[] parameters) {
lastVariableIndex = -1;
variableStack.clear();
scope = null;
pushBlockScope();
// lets push this onto the stack
definingParameters = true;
if (!isStaticMethod()) {
defineVariable("this", classNode.getName()).getIndex();
} // now lets create indices for the parameteres
for (int i = 0; i < parameters.length; i++) {
Parameter parameter = parameters[i];
String type = parameter.getType();
int idx = defineVariable(parameter.getName(), type).getIndex();
if (BytecodeHelper.isPrimitiveType(type)) {
helper.load(type, idx);
helper.box(type);
cv.visitVarInsn(ASTORE, idx);
}
}
definingParameters = false;
}
protected void popScope() {
int lastID = scope.getLastVariableIndex();
List removeKeys = new ArrayList();
for (Iterator iter = variableStack.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
String name = (String) entry.getKey();
Variable value = (Variable) entry.getValue();
if (value.getIndex() >= lastID) {
removeKeys.add(name);
}
}
for (Iterator iter = removeKeys.iterator(); iter.hasNext();) {
variableStack.remove(iter.next());
}
scope = scope.getParent();
}
protected void pushBlockScope() {
pushBlockScope(true, true);
}
protected void pushBlockScope(boolean canContinue, boolean canBreak) {
scope = new BlockScope(scope);
scope.setContinueLabel(canContinue ? new Label() : null);
scope.setBreakLabel(canBreak? new Label() : null);
scope.setLastVariableIndex(getNextVariableID());
}
/**
* Defines the given variable in scope and assigns it to the stack
*/
protected Variable defineVariable(String name, String type) {
return defineVariable(name, type, true);
}
protected Variable defineVariable(String name, String type, boolean define) {
return defineVariable(name, new Type(type), define);
}
private Variable defineVariable(String name, Type type, boolean define) {
Variable answer = (Variable) variableStack.get(name);
if (answer == null) {
lastVariableIndex = getNextVariableID();
answer = new Variable(lastVariableIndex, type, name);
if (mutableVars.contains(name)) {
answer.setHolder(true);
}
variableStack.put(name, answer);
if (define) {
if (definingParameters) {
if (answer.isHolder()) {
cv.visitTypeInsn(NEW, "groovy/lang/Reference"); // br todo to associate a label with the variable
cv.visitInsn(DUP);
cv.visitVarInsn(ALOAD, lastVariableIndex);
cv.visitMethodInsn(INVOKESPECIAL, "groovy/lang/Reference", "<init>", "(Ljava/lang/Object;)V"); // br wrap the param in a ref
cv.visitVarInsn(ASTORE, lastVariableIndex);
}
}
else {
// using new variable inside a comparison expression
// so lets initialize it too
if (answer.isHolder() && !isInScriptBody()) { // br doesn't seem to need different treatment, in script or not
//cv.visitVarInsn(ASTORE, lastVariableIndex + 1); // I might need this to set the reference value
cv.visitTypeInsn(NEW, "groovy/lang/Reference");
cv.visitInsn(DUP);
cv.visitMethodInsn(INVOKESPECIAL, "groovy/lang/Reference", "<init>", "()V");
cv.visitVarInsn(ASTORE, lastVariableIndex);
//cv.visitVarInsn(ALOAD, idx + 1);
}
else {
if (!leftHandExpression) {
cv.visitInsn(ACONST_NULL);
cv.visitVarInsn(ASTORE, lastVariableIndex);
}
}
}
}
}
return answer;
}
private int getNextVariableID() {
return Math.max(lastVariableIndex + 1, variableStack.size());
}
/** @return true if the given name is a local variable or a field */
protected boolean isFieldOrVariable(String name) {
return variableStack.containsKey(name) || classNode.getField(name) != null;
}
protected Type checkValidType(Type type, ASTNode node, String message) {
if (type.isDynamic()) {
return type;
}
String name = checkValidType(type.getName(), node, message);
if (type.getName().equals(name)) {
return type;
}
return new Type(name);
}
protected String checkValidType(String type, ASTNode node, String message) {
if (type.endsWith("[]")) {
String postfix = "[]";
String prefix = type.substring(0, type.length() - 2);
return checkValidType(prefix, node, message) + postfix;
}
int idx = type.indexOf('$');
if (idx > 0) {
String postfix = type.substring(idx);
String prefix = type.substring(0, idx);
return checkValidType(prefix, node, message) + postfix;
}
if (BytecodeHelper.isPrimitiveType(type) || "void".equals(type)) {
return type;
}
String original = type;
type = resolveClassName(type);
if (type != null) {
return type;
}
throw new MissingClassException(original, node, message + " for class: " + classNode.getName());
}
protected String resolveClassName(String type) {
return classNode.resolveClassName(type);
}
protected String createVariableName(String type) {
return "__" + type + (++tempVariableNameCounter);
}
/**
* @return if the type of the expression can be determined at compile time
* then this method returns the type - otherwise null
*/
protected String getExpressionType(Expression expression) {
if (comparisonExpression(expression)) {
return "boolean";
}
if (expression instanceof VariableExpression) {
VariableExpression varExpr = (VariableExpression) expression;
Variable variable = (Variable) variableStack.get(varExpr.getVariable());
if (variable != null && !variable.isHolder()) {
Type type = variable.getType();
if (! type.isDynamic()) {
return type.getName();
}
}
}
return null;
}
/**
* @return true if the value is an Integer, a Float, a Long, a Double or a
* String .
*/
protected boolean isPrimitiveFieldType(String type) {
return type.equals("java.lang.String")
|| type.equals("java.lang.Integer")
|| type.equals("java.lang.Double")
|| type.equals("java.lang.Long")
|| type.equals("java.lang.Float");
}
protected boolean isInClosureConstructor() {
return constructorNode != null
&& classNode.getOuterClass() != null
&& classNode.getSuperClass().equals(Closure.class.getName());
}
protected boolean isStaticMethod() {
if (methodNode == null) { // we're in a constructor
return false;
}
return methodNode.isStatic();
}
/**
* @return loads the given type name
*/
protected Class loadClass(String name) {
try {
CompileUnit compileUnit = getCompileUnit();
if (compileUnit != null) {
return compileUnit.loadClass(name);
}
else {
throw new ClassGeneratorException("Could not load class: " + name);
}
}
catch (ClassNotFoundException e) {
throw new ClassGeneratorException("Could not load class: " + name + " reason: " + e, e);
}
}
protected CompileUnit getCompileUnit() {
CompileUnit answer = classNode.getCompileUnit();
if (answer == null) {
answer = context.getCompileUnit();
}
return answer;
}
}
|
package org.testng.remote.adapter;
import java.util.Map;
import org.testng.ISuite;
import org.testng.ISuiteResult;
import org.testng.ITestContext;
import org.testng.SuiteRunner;
import org.testng.reporters.TestHTMLReporter;
/**
* This listener is called by the {@link IWorkerApadter} implementation when a remote test result is ready.
*
* @author Guy Korland
* @date April 9, 2007
* @see IWorkerApadter
*/
public class RemoteResultListener
{
/**
* Holds the corresponded {@link SuiteRunner} for the processed {@link org.testng.xml.XmlSuite}.
*/
final private SuiteRunner m_runner;
/**
* Creates a listener for an {@link org.testng.xml.XmlSuite} result.
* @param runner the corresponded {@link SuiteRunner}
*/
public RemoteResultListener( SuiteRunner runner)
{
m_runner = runner;
}
/**
* Should called by the {@link IWorkerApadter} implementation when a remote suite result is ready.
* @param remoteSuiteRunner remote result.
*/
public void onResult( ISuite remoteSuiteRunner)
{
m_runner.setHost(remoteSuiteRunner.getHost());
Map<String, ISuiteResult> tmpResults = remoteSuiteRunner.getResults();
Map<String, ISuiteResult> suiteResults = m_runner.getResults();
for (String tests : tmpResults.keySet())
{
ISuiteResult suiteResult = tmpResults.get(tests);
suiteResults.put(tests, suiteResult);
ITestContext tc = suiteResult.getTestContext();
TestHTMLReporter.generateLog(tc, remoteSuiteRunner.getHost(),
m_runner.getOutputDirectory(),
tc.getFailedConfigurations().getAllResults(),
tc.getSkippedConfigurations().getAllResults(),
tc.getPassedTests().getAllResults(),
tc.getFailedTests().getAllResults(),
tc.getSkippedTests().getAllResults(),
tc.getFailedButWithinSuccessPercentageTests().getAllResults());
}
}
}
|
package be.ibridge.kettle.core.database;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.value.Value;
/**
* Contains AS/400 specific information through static final members
*
* @author Matt
* @since 11-mrt-2005
*/
public class AS400DatabaseMeta extends BaseDatabaseMeta implements DatabaseInterface
{
/**
* Construct a new database connection.
*
*/
public AS400DatabaseMeta(String name, String access, String host, String db, String port, String user, String pass)
{
super(name, access, host, db, port, user, pass);
}
public AS400DatabaseMeta()
{
}
public String getDatabaseTypeDesc()
{
return "AS/400";
}
public String getDatabaseTypeDescLong()
{
return "AS/400";
}
/**
* @return Returns the databaseType.
*/
public int getDatabaseType()
{
return DatabaseMeta.TYPE_DATABASE_AS400;
}
public int[] getAccessTypeList()
{
return new int[] { DatabaseMeta.TYPE_ACCESS_NATIVE, DatabaseMeta.TYPE_ACCESS_ODBC };
}
public String getDriverClass()
{
if (getAccessType()==DatabaseMeta.TYPE_ACCESS_ODBC)
{
return "sun.jdbc.odbc.JdbcOdbcDriver";
}
else
{
return "com.ibm.as400.access.AS400JDBCDriver";
}
}
/**
* Get the maximum length of a text field for this database connection.
* This includes optional CLOB, Memo and Text fields. (the maximum!)
* @return The maximum text field length for this database type. (mostly CLOB_LENGTH)
*/
public int getMaxTextFieldLength()
{
return 65536;
}
public String getURL()
{
if (getAccessType()==DatabaseMeta.TYPE_ACCESS_ODBC)
{
return "jdbc:odbc:"+getDatabaseName();
}
else
{
return "jdbc:as400://"+getHostname()+"/"+getDatabaseName();
}
}
/**
* @param tableName The table to be truncated.
* @return The SQL statement to truncate a table: remove all rows from it without a transaction
*/
public String getTruncateTableStatement(String tableName)
{
return "DELETE FROM "+tableName;
}
/**
* Generates the SQL statement to add a column to the specified table
* @param tablename The table to add
* @param v The column defined as a value
* @param tk the name of the technical key field
* @param use_autoinc whether or not this field uses auto increment
* @param pk the name of the primary key field
* @param semicolon whether or not to add a semi-colon behind the statement.
* @return the SQL statement to add a column to the specified table
*/
public String getAddColumnStatement(String tablename, Value v, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
return "ALTER TABLE "+tablename+" ADD "+getFieldDefinition(v, tk, pk, use_autoinc, true, false);
}
/**
* Generates the SQL statement to modify a column in the specified table
* @param tablename The table to add
* @param v The column defined as a value
* @param tk the name of the technical key field
* @param use_autoinc whether or not this field uses auto increment
* @param pk the name of the primary key field
* @param semicolon whether or not to add a semi-colon behind the statement.
* @return the SQL statement to modify a column in the specified table
*/
public String getModifyColumnStatement(String tablename, Value v, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
return "ALTER TABLE "+tablename+" ALTER COLUMN "+v.getName()+" SET "+getFieldDefinition(v, tk, pk, use_autoinc, false, false);
}
public String getFieldDefinition(Value v, String tk, String pk, boolean use_autoinc, boolean add_fieldname, boolean add_cr)
{
String retval="";
String fieldname = v.getName();
int length = v.getLength();
int precision = v.getPrecision();
if (add_fieldname) retval+=fieldname+" ";
int type = v.getType();
switch(type)
{
case Value.VALUE_TYPE_DATE : retval+="TIMESTAMP"; break;
case Value.VALUE_TYPE_BOOLEAN: retval+="CHAR(1)"; break;
case Value.VALUE_TYPE_NUMBER :
case Value.VALUE_TYPE_INTEGER:
case Value.VALUE_TYPE_BIGNUMBER:
if (length<=0 && precision<=0)
{
retval+="DOUBLE";
}
else
{
retval+="DECIMAL";
if (length>0)
{
retval+="("+length;
if (precision>0)
{
retval+=", "+precision;
}
retval+=")";
}
}
break;
case Value.VALUE_TYPE_STRING:
if (length>getMaxVARCHARLength() || length>=DatabaseMeta.CLOB_LENGTH)
{
retval+="CLOB";
}
else
{
retval+="VARCHAR";
if (length>0)
{
retval+="("+length;
}
else
{
retval+="("; // Maybe use some default DB String length?
}
retval+=")";
}
break;
default:
retval+=" UNKNOWN";
break;
}
if (add_cr) retval+=Const.CR;
return retval;
}
/* (non-Javadoc)
* @see be.ibridge.kettle.core.database.DatabaseInterface#getReservedWords()
*/
public String[] getReservedWords()
{
return new String[]
{
//This is the list of currently reserved DB2 UDB for iSeries words. Words may be added at any time.
//For a list of additional words that may become reserved in the future, see the IBM SQL and
//ANSI reserved words in the IBM SQL Reference Version 1 SC26-3255.
"ACTIVATE", "ADD", "ALIAS", "ALL", "ALLOCATE", "ALLOW", "ALTER", "AND", "ANY", "AS", "ASENSITIVE", "AT",
"ATTRIBUTES", "AUTHORIZATION",
"BEGIN", "BETWEEN", "BINARY", "BY",
"CACHE", "CALL", "CALLED", "CARDINALITY", "CASE", "CAST", "CCSID", "CHAR", "CHARACTER", "CHECK", "CLOSE",
"COLLECTION", "COLUMN", "COMMENT", "COMMIT", "CONCAT", "CONDITION", "CONNECT", "CONNECTION", "CONSTRAINT",
"CONTAINS", "CONTINUE", "COUNT", "COUNT_BIG", "CREATE", "CROSS", "CURRENT", "CURRENT_DATE", "CURRENT_PATH",
"CURRENT_SCHEMA", "CURRENT_SERVER", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_TIMEZONE", "CURRENT_USER", "CURSOR", "CYCLE",
"DATABASE", "DATAPARTITIONNAME", "DATAPARTITIONNUM", "DATE", "DAY", "DAYS", "DBINFO", "DBPARTITIONNAME",
"DBPARTITIONNUM", "DB2GENERAL", "DB2GENRL", "DB2SQL", "DEALLOCATE", "DECLARE", "DEFAULT", "DEFAULTS",
"DEFINITION", "DELETE", "DENSERANK", "DENSE_RANK", "DESCRIBE", "DESCRIPTOR", "DETERMINISTIC",
"DIAGNOSTICS", "DISABLE", "DISALLOW", "DISCONNECT", "DISTINCT", "DO", "DOUBLE", "DROP", "DYNAMIC",
"EACH", "ELSE", "ELSEIF", "ENABLE", "ENCRYPTION", "END", "ENDING", "END-EXEC", "ESCAPE", "EVERY",
"EXCEPT", "EXCEPTION", "EXCLUDING", "EXCLUSIVE", "EXECUTE", "EXISTS", "EXIT", "EXTERNAL", "EXTRACT",
"FENCED", "FETCH", "FILE", "FINAL", "FOR", "FOREIGN", "FREE", "FROM", "FULL", "FUNCTION",
"GENERAL", "GENERATED", "GET", "GLOBAL", "GO", "GOTO", "GRANT", "GRAPHIC", "GROUP",
"HANDLER", "HASH", "HASHED_VALUE", "HAVING", "HINT", "HOLD", "HOUR", "HOURS",
"IDENTITY", "IF", "IMMEDIATE", "IN", "INCLUDING", "INCLUSIVE", "INCREMENT", "INDEX", "INDICATOR",
"INHERIT", "INNER", "INOUT", "INSENSITIVE", "INSERT", "INTEGRITY", "INTERSECT", "INTO", "IS",
"ISOLATION", "ITERATE",
"JAVA", "JOIN",
"KEY",
"LABEL", "LANGUAGE", "LATERAL", "LEAVE", "LEFT", "LIKE", "LINKTYPE", "LOCAL", "LOCALDATE", "LOCALTIME",
"LOCALTIMESTAMP", "LOCK", "LONG", "LOOP",
"MAINTAINED", "MATERIALIZED", "MAXVALUE", "MICROSECOND", "MICROSECONDS", "MINUTE", "MINUTES", "MINVALUE",
"MODE", "MODIFIES", "MONTH", "MONTHS",
"NEW", "NEW_TABLE", "NEXTVAL", "NO", "NOCACHE", "NOCYCLE", "NODENAME", "NODENUMBER", "NOMAXVALUE",
"NOMINVALUE", "NOORDER", "NORMALIZED", "NOT", "NULL",
"OF", "OLD", "OLD_TABLE", "ON", "OPEN", "OPTIMIZE", "OPTION", "OR", "ORDER", "OUT", "OUTER", "OVER",
"OVERRIDING",
"PACKAGE", "PAGESIZE", "PARAMETER", "PART", "PARTITION", "PARTITIONING", "PARTITIONS", "PASSWORD",
"PATH", "POSITION", "PREPARE", "PREVVAL", "PRIMARY", "PRIVILEGES", "PROCEDURE", "PROGRAM",
"QUERY",
"RANGE", "RANK", "READ", "READS", "RECOVERY", "REFERENCES", "REFERENCING", "REFRESH", "RELEASE",
"RENAME", "REPEAT", "RESET", "RESIGNAL", "RESTART", "RESULT", "RETURN", "RETURNS", "REVOKE", "RIGHT",
"ROLLBACK", "ROUTINE", "ROW", "ROWNUMBER", "ROW_NUMBER", "ROWS", "RRN", "RUN",
"SAVEPOINT", "SCHEMA", "SCRATCHPAD", "SCROLL", "SEARCH", "SECOND", "SECONDS", "SELECT", "SENSITIVE",
"SEQUENCE", "SESSION", "SESSION_USER", "SET", "SIGNAL", "SIMPLE", "SOME", "SOURCE", "SPECIFIC", "SQL",
"SQLID", "STACKED", "START", "STARTING", "STATEMENT", "STATIC", "SUBSTRING", "SUMMARY", "SYNONYM", "SYSTEM_USER",
"TABLE", "THEN", "TIME", "TIMESTAMP", "TO", "TRANSACTION", "TRIGGER", "TRIM", "TYPE",
"UNDO", "UNION", "UNIQUE", "UNTIL", "UPDATE", "USAGE", "USER", "USING",
"VALUE", "VALUES", "VARIABLE", "VARIANT", "VERSION", "VIEW", "VOLATILE",
"WHEN", "WHERE", "WHILE", "WITH", "WITHOUT", "WRITE",
"YEAR", "YEARS"
};
}
/**
* Most databases round number(7,2) 17.29999999 to 17.30, but some don't.
* @return true if the database supports roundinf of floating point data on update/insert
*/
public boolean supportsFloatRoundingOnUpdate()
{
return false;
}
/**
* Get the maximum length of a text field (VARCHAR) for this database connection.
* If this size is exceeded use a CLOB.
* @return The maximum VARCHAR field length for this database type. (mostly identical to getMaxTextFieldLength() - CLOB_LENGTH)
*/
public int getMaxVARCHARLength()
{
return 32672;
}
}
|
package com.rultor.board;
import java.util.Arrays;
import org.junit.Assume;
import org.junit.Test;
/**
* Integration case for {@link SES}.
* @author Yegor Bugayenko (yegor@tpc2.com)
* @version $Id$
*/
public final class SESITCase {
/**
* SES can send emails.
* @throws Exception If some problem inside
*/
@Test
public void sendsEmail() throws Exception {
final String key = System.getProperty("failsafe.ses.key");
Assume.assumeNotNull(key);
final Billboard board = new SES(
new Bill.Simple(
"test message from rultor",
"yegor@tpc2.com",
Arrays.asList("yegor.bugayenko@tpc2.com")
),
key,
System.getProperty("failsafe.ses.secret")
);
board.announce(true);
}
}
|
package ch.eonum.pipeline.analysis;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.LinkedHashMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import ch.eonum.pipeline.core.DataSet;
import ch.eonum.pipeline.core.Instance;
import ch.eonum.pipeline.core.SparseInstance;
/**
* <p>
* Analyze the results of a classification task.
* </p>
*
* <p>
* Recognition rate. Recognition rate per class, class distributions, confusion
* matrix etc..
* </p>
*
* @author tim
*
*/
public class ClassificationAnalyzer<E extends Instance> {
private Map<String, Double> totalMetrics;
private Map<String, Instance> metricsPerClass;
/**
*
*
* @param data
* labeled data set after classification
* @param fileName
* file name for the CSV file, where all analysis results will be
* written to.
* @throws IOException
*/
public void analyze(DataSet<E> data, String fileName) throws IOException {
totalMetrics = new LinkedHashMap<String, Double>();
metricsPerClass = new LinkedHashMap<String, Instance>();
totalMetrics.put("N", (double) data.size());
int correct = 0;
for (Instance i : data)
if (i.groundTruth != null && i.groundTruth.equals(i.label))
correct++;
totalMetrics.put("RecognitionRate", correct / (double) data.size()
* 100.0);
Set<String> classes = data.collectClasses();
Map<String, Integer> indicesByClassName = new HashMap<String, Integer>();
Map<Integer, String> classNamesByIndex = new HashMap<Integer, String>();
int[][] confusionMatrix = new int[classes.size()][classes.size()];
int j = 0;
for (String i : classes){
metricsPerClass.put(i, new SparseInstance(i, i,
new HashMap<String, Double>()));
indicesByClassName.put(i, j);
classNamesByIndex.put(j, i);
j++;
}
for (Instance i : data) {
Instance metrics = metricsPerClass.get(i.groundTruth);
metrics.put("N", metrics.get("N") + 1.);
for (String c : classes) {
Instance m = metricsPerClass.get(c);
m.put("classProb",
m.get("classProb") + i.getResult("classProb" + c));
}
int y = indicesByClassName.get(i.label);
int x = indicesByClassName.get(i.groundTruth);
confusionMatrix[x][y]++;
if (i.groundTruth != null && i.groundTruth.equals(i.label))
metrics.put("correct", metrics.get("correct") + 1.);
else if (metricsPerClass.containsKey(i.label))
metricsPerClass.get(i.label).put("falsePositive",
metricsPerClass.get(i.label).get("falsePositive") + 1.);
}
for (String c : classes) {
Instance metrics = metricsPerClass.get(c);
metrics.put("RecognitionRate",
metrics.get("correct") / metrics.get("N") * 100.0);
metrics.put("classDistribution", metrics.get("N") / data.size()
* 100.0);
metrics.put("classProb", metrics.get("classProb") / data.size()
* 100.0);
}
String[] columns = new String[] { "N", "RecognitionRate",
"classDistribution", "classProb", "correct", "falsePositive" };
/** write results. */
PrintStream ps = new PrintStream(new File(fileName));
ps.println();
ps.println("Total;" + data.size() + ";Recognition Rate;"
+ totalMetrics.get("RecognitionRate"));
ps.println();
ps.print("class;");
for (String c : columns)
ps.print(c + ";");
ps.println();
for (String cl : classes) {
ps.print(cl + ";");
for (String c : columns)
ps.print(metricsPerClass.get(cl).get(c) + ";");
ps.println();
}
ps.println();ps.println();
ps.println("Confusion matrix (x-axis: ground truth, y-axis: prediction");
ps.print(";");
for(int i = 0; i < classes.size(); i++)
ps.print(classNamesByIndex.get(i) + ";");
ps.println();
for(int y = 0; y < classes.size(); y++){
ps.print(classNamesByIndex.get(y) + ";");
for(int x = 0; x < classes.size(); x++)
ps.print(confusionMatrix[x][y] + ";");
ps.println();
}
ps.close();
}
public Map<String, Instance> getMetricsByClass() {
return this.metricsPerClass;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ch.unizh.ini.jaer.projects.cochsoundloc;
import ch.unizh.ini.jaer.chip.cochlea.BinauralCochleaEvent;
import ch.unizh.ini.jaer.chip.cochlea.BinauralCochleaEvent.Ear;
import ch.unizh.ini.jaer.chip.cochlea.CochleaAMSEvent;
import net.sf.jaer.chip.*;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.eventprocessing.EventFilter2D;
import java.util.*;
import com.sun.opengl.util.GLUT;
import java.awt.Graphics2D;
import javax.media.opengl.GL;
import javax.media.opengl.GLAutoDrawable;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.util.EngineeringFormat;
import java.io.*;
import java.util.concurrent.ArrayBlockingQueue;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
/**
* Extracts interaural time difference (ITD) from a binaural cochlea input.
*
* @author Holger
*/
public class ITDFilter extends EventFilter2D implements Observer, FrameAnnotater {
public static String getDescription() {
return "Measures ITD (Interaural time difference) using a variety of methods";
}
private ITDCalibrationGaussians calibration = null;
private float averagingDecay = getPrefs().getFloat("ITDFilter.averagingDecay", 1);
private int maxITD = getPrefs().getInt("ITDFilter.maxITD", 800);
private int numOfBins = getPrefs().getInt("ITDFilter.numOfBins", 16);
private int maxWeight = getPrefs().getInt("ITDFilter.maxWeight", 5);
private int dimLastTs = getPrefs().getInt("ITDFilter.dimLastTs", 4);
private int maxWeightTime = getPrefs().getInt("ITDFilter.maxWeightTime", 500000);
private boolean display = getPrefs().getBoolean("ITDFilter.display", false);
private boolean useLaterSpikeForWeight = getPrefs().getBoolean("ITDFilter.useLaterSpikeForWeight", true);
private boolean usePriorSpikeForWeight = getPrefs().getBoolean("ITDFilter.usePriorSpikeForWeight", true);
private boolean computeMeanInLoop = getPrefs().getBoolean("ITDFilter.computeMeanInLoop", true);
private boolean writeITD2File = getPrefs().getBoolean("ITDFilter.writeITD2File", false);
private boolean sendITDsToOtherThread = getPrefs().getBoolean("ITDFilter.sendITDsToOtherThread", false);
private int itdEventQueueSize = getPrefs().getInt("ITDFilter.itdEventQueueSize", 1000);
private boolean writeBin2File = getPrefs().getBoolean("ITDFilter.writeBin2File", false);
private boolean invert = getPrefs().getBoolean("ITDFilter.invert", false);
private boolean write2FileForEverySpike = getPrefs().getBoolean("ITDFilter.write2FileForEverySpike", false);
private boolean normToConfThresh = getPrefs().getBoolean("ITDFilter.normToConfThresh", false);
private boolean showAnnotations = getPrefs().getBoolean("ITDFilter.showAnnotations", false);
private int confidenceThreshold = getPrefs().getInt("ITDFilter.confidenceThreshold", 30);
private int numLoopMean = getPrefs().getInt("ITDFilter.numLoopMean", 2);
private int numOfCochleaChannels = getPrefs().getInt("ITDFilter.numOfCochleaChannels", 32);
private boolean useCalibration = getPrefs().getBoolean("ITDFilter.useCalibration", false);
private String calibrationFilePath = getPrefs().get("ITDFilter.calibrationFilePath", null);
ITDFrame frame;
private ITDBins myBins;
private boolean connectToPanTiltThread = false;
//private LinkedList[][] lastTimestamps;
//private ArrayList<LinkedList<Integer>> lastTimestamps0;
//private ArrayList<LinkedList<Integer>> lastTimestamps1;
private int[][][][] lastTs;
private int[][][] lastTsCursor;
//private int[][] AbsoluteLastTimestamp;
Iterator iterator;
private float lastWeight = 1f;
private int avgITD;
private float avgITDConfidence = 0;
private float ILD;
EngineeringFormat fmt = new EngineeringFormat();
FileWriter fstream;
FileWriter fstreamBins;
BufferedWriter ITDFile;
BufferedWriter BinFile;
private boolean wasMoving = false;
private int numNeuronTypes = 1;
private static ArrayBlockingQueue ITDEventQueue = null;
private boolean ITDEventQueueFull = false;
public enum EstimationMethod {
useMedian, useMean, useMax
};
private EstimationMethod estimationMethod = EstimationMethod.valueOf(getPrefs().get("ITDFilter.estimationMethod", "useMedian"));
public enum AMSprocessingMethod {
NeuronsIndividually, AllNeuronsTogether, StoreSeparetlyCompareEvery
};
private AMSprocessingMethod amsProcessingMethod = AMSprocessingMethod.valueOf(getPrefs().get("ITDFilter.amsProcessingMethod", "NeuronsIndividually"));
// public enum UseGanglionCellType {
// LPF, BPF
private CochleaAMSEvent.FilterType useGanglionCellType = CochleaAMSEvent.FilterType.valueOf(getPrefs().get("ITDFilter.useGanglionCellType", "LPF"));
private boolean hasMultipleGanglionCellTypes = false;
// private ActionListener updateBinFrame = new ActionListener() {
// public void actionPerformed(ActionEvent evt) {
// //wasMoving = false;
// private javax.swing.Timer timer = new javax.swing.Timer(5, updateBinFrame);
private float averagingDecayTmp = 0;
public ITDFilter(AEChip chip) {
super(chip);
chip.addObserver(this);
initFilter();
//resetFilter();
//lastTimestamps = (LinkedList[][])new LinkedList[32][2];
//LinkedList[][] <Integer>lastTimestamps = new LinkedList<Integer>[1][2]();
// lastTimestamps0 = new ArrayList<LinkedList<Integer>>(32);
// lastTimestamps1 = new ArrayList<LinkedList<Integer>>(32);
// for (int k=0;k<32;k++) {
// lastTimestamps0.add(new LinkedList<Integer>());
// lastTimestamps1.add(new LinkedList<Integer>());
//AbsoluteLastTimestamp = new int[32][2];
setPropertyTooltip("averagingDecay", "The decay constant of the fade out of old ITDs (in sec). Set to 0 to disable fade out.");
setPropertyTooltip("maxITD", "maximum ITD to compute in us");
setPropertyTooltip("numOfBins", "total number of bins");
setPropertyTooltip("dimLastTs", "how many lastTs save");
setPropertyTooltip("maxWeight", "maximum weight for ITDs");
setPropertyTooltip("maxWeightTime", "maximum time to use for weighting ITDs");
setPropertyTooltip("display", "display bins");
setPropertyTooltip("useLaterSpikeForWeight", "use the side of the later arriving spike to weight the ITD");
setPropertyTooltip("usePriorSpikeForWeight", "use the side of the prior arriving spike to weight the ITD");
setPropertyTooltip("computeMeanInLoop", "use a loop to compute the mean or median to avoid biasing");
setPropertyTooltip("useCalibration", "use xml calibration file");
setPropertyTooltip("confidenceThreshold", "ITDs with confidence below this threshold are neglected");
setPropertyTooltip("writeITD2File", "Write the ITD-values to a File");
setPropertyTooltip("writeBin2File", "Write the Bin-values to a File");
setPropertyTooltip("write2FileForEverySpike", "Write the values to file after every spike or after every packet");
setPropertyTooltip("invert", "exchange right and left ear.");
setPropertyTooltip("SelectCalibrationFile", "select the xml file which can be created by matlab");
setPropertyTooltip("calibrationFilePath", "Full path to xml calibration file");
setPropertyTooltip("estimationMethod", "Method used to compute the ITD");
setPropertyTooltip("useGanglionCellType", "If CochleaAMS which Ganglion cells to use");
setPropertyTooltip("amsProcessingMethod", "If CochleaAMS how to process different neurons");
setPropertyTooltip("numLoopMean", "Method used to compute the ITD");
setPropertyTooltip("numOfCochleaChannels", "The number of frequency channels of the cochleae");
setPropertyTooltip("normToConfThresh", "Normalize the bins before every spike to the value of the confidence Threshold");
setPropertyTooltip("ToggleITDDisplay", "Toggles graphical display of ITD");
addPropertyToGroup("ITDWeighting", "useLaterSpikeForWeight");
addPropertyToGroup("ITDWeighting", "usePriorSpikeForWeight");
addPropertyToGroup("ITDWeighting", "maxWeight");
addPropertyToGroup("ITDWeighting", "maxWeightTime");
}
public EventPacket<?> filterPacket(EventPacket<?> in) {
if (!filterEnabled) {
return in;
}
if (connectToPanTiltThread) {
CommObjForITDFilter commObjIncomming = PanTilt.pollBlockingQForITDFilter();
while (commObjIncomming != null) {
log.info("Got a commObj from the PanTiltThread!");
switch (commObjIncomming.getCommand()) {
case 0:
break;
case 1:
break;
case 2:
break;
case 3:
averagingDecayTmp = this.averagingDecay;
this.setAveragingDecay(0);
break;
case 4:
this.setAveragingDecay(averagingDecayTmp);
break;
case 5:
this.myBins.clear();
break;
}
commObjIncomming = PanTilt.pollBlockingQForITDFilter();
}
}
if (connectToPanTiltThread && (PanTilt.isMoving() || PanTilt.isWasMoving())) {
this.wasMoving = true;
return in;
}
if (this.wasMoving == true) {
this.wasMoving = false;
this.myBins.clear();
log.info("clear bins!");
}
checkOutputPacketEventType(in);
if (in.isEmpty()) {
return in;
}
int nleft = 0, nright = 0;
for (Object e : in) {
BinauralCochleaEvent i = (BinauralCochleaEvent) e;
int ganglionCellThreshold;
if (hasMultipleGanglionCellTypes &&
(this.amsProcessingMethod == AMSprocessingMethod.NeuronsIndividually ||
this.amsProcessingMethod == AMSprocessingMethod.StoreSeparetlyCompareEvery)) {
CochleaAMSEvent camsevent = ((CochleaAMSEvent) i);
ganglionCellThreshold = camsevent.getThreshold();
// if (useGanglionCellType != camsevent.getFilterType()) {
// continue;
} else {
ganglionCellThreshold = 0;
}
try {
int ear;
if (i.getEar() == Ear.RIGHT) {
ear = 0;
} else {
ear = 1;
}
if (this.invert) {
ear = (ear+1)%2;
}
if (i.x >= numOfCochleaChannels) {
log.warning("there was a BasicEvent i with i.x=" + i.x + " >= " + numOfCochleaChannels + "=numOfCochleaChannels! Therefore set numOfCochleaChannels=" + (i.x + 1));
setNumOfCochleaChannels(i.x + 1);
} else {
int cursor = lastTsCursor[i.x][ganglionCellThreshold][1 - ear];
do {
int diff = i.timestamp - lastTs[i.x][ganglionCellThreshold][1 - ear][cursor];
if (ear == 0) {
diff = -diff;
nright++;
} else {
nleft++;
}
if (java.lang.Math.abs(diff) < maxITD) {
lastWeight = 1f;
//Compute weight:
if (useLaterSpikeForWeight == true) {
int weightTimeThisSide = i.timestamp - lastTs[i.x][ganglionCellThreshold][ear][lastTsCursor[i.x][ganglionCellThreshold][ear]];
if (weightTimeThisSide > maxWeightTime) {
weightTimeThisSide = maxWeightTime;
}
lastWeight *= ((weightTimeThisSide * (maxWeight - 1f)) / (float) maxWeightTime) + 1f;
if (weightTimeThisSide < 0) {
//log.warning("weightTimeThisSide < 0");
lastWeight = 0;
}
}
if (usePriorSpikeForWeight == true) {
int weightTimeOtherSide = lastTs[i.x][ganglionCellThreshold][1 - ear][cursor] - lastTs[i.x][ganglionCellThreshold][1 - ear][(cursor + 1) % dimLastTs];
if (weightTimeOtherSide > maxWeightTime) {
weightTimeOtherSide = maxWeightTime;
}
lastWeight *= ((weightTimeOtherSide * (maxWeight - 1f)) / (float) maxWeightTime) + 1f;
if (weightTimeOtherSide < 0) {
//log.warning("weightTimeOtherSide < 0");
lastWeight = 0;
}
}
if (this.normToConfThresh == true) {
myBins.addITD(diff, i.timestamp, i.x, lastWeight, this.confidenceThreshold);
} else {
myBins.addITD(diff, i.timestamp, i.x, lastWeight, 0);
}
if (this.sendITDsToOtherThread) {
if (ITDEventQueue==null) {
ITDEventQueue = new ArrayBlockingQueue(this.itdEventQueueSize);
}
ITDEvent itdEvent = new ITDEvent(diff, i.timestamp, i.x, lastWeight);
boolean success = ITDEventQueue.offer(itdEvent);
if (success == false) {
ITDEventQueueFull = true;
log.warning("Could not add ITD-Event to the ITDEventQueue. Probably itdEventQueueSize is too small!!!");
}
else
{
ITDEventQueueFull = false;
}
}
} else {
break;
}
cursor = (++cursor) % dimLastTs;
} while (cursor != lastTsCursor[i.x][ganglionCellThreshold][1 - ear]);
//Now decrement the cursor (circularly)
if (lastTsCursor[i.x][ganglionCellThreshold][ear] == 0) {
lastTsCursor[i.x][ganglionCellThreshold][ear] = dimLastTs;
}
lastTsCursor[i.x][ganglionCellThreshold][ear]
//Add the new timestamp to the list
lastTs[i.x][ganglionCellThreshold][ear][lastTsCursor[i.x][ganglionCellThreshold][ear]] = i.timestamp;
if (this.write2FileForEverySpike == true) {
if (this.writeITD2File == true && ITDFile != null) {
refreshITD();
ITDFile.write(i.timestamp + "\t" + avgITD + "\t" + avgITDConfidence + "\n");
}
if (this.writeBin2File == true && BinFile != null) {
refreshITD();
BinFile.write(i.timestamp + "\t" + myBins.toString() + "\n");
}
}
}
} catch (Exception e1) {
log.warning("In for-loop in filterPacket caught exception " + e1);
e1.printStackTrace();
}
}
try {
if (this.normToConfThresh == true) {
myBins.updateTime(this.confidenceThreshold, in.getLastTimestamp());
} else {
myBins.updateTime(0, in.getLastTimestamp());
}
refreshITD();
ILD = (float) (nleft - nright) / (float) (nright + nleft); //Max ILD is 1 (if only one side active)
if (this.write2FileForEverySpike == false) {
if (this.writeITD2File == true && ITDFile != null) {
ITDFile.write(in.getLastTimestamp() + "\t" + avgITD + "\t" + avgITDConfidence + "\n");
}
if (this.writeBin2File == true && BinFile != null) {
BinFile.write(in.getLastTimestamp() + "\t" + myBins.toString() + "\n");
}
}
} catch (Exception e) {
log.warning("In filterPacket caught exception " + e);
e.printStackTrace();
}
return in;
}
public void refreshITD() {
int avgITDtemp = 0;
switch (estimationMethod) {
case useMedian:
avgITDtemp = myBins.getITDMedian();
break;
case useMean:
avgITDtemp = myBins.getITDMean();
break;
case useMax:
avgITDtemp = myBins.getITDMax();
}
avgITDConfidence = myBins.getITDConfidence();
if (avgITDConfidence > confidenceThreshold) {
avgITD = avgITDtemp;
if (connectToPanTiltThread == true) {
CommObjForPanTilt filterOutput = new CommObjForPanTilt();
filterOutput.setFromCochlea(true);
filterOutput.setPanOffset((float) avgITD);
filterOutput.setConfidence(avgITDConfidence);
PanTilt.offerBlockingQ(filterOutput);
}
}
if (frame != null) {
frame.binsPanel.repaint();
}
}
public Object getFilterState() {
return null;
}
public void resetFilter() {
initFilter();
}
@Override
public void initFilter() {
// log.info("init() called");
int dim = 1;
switch (amsProcessingMethod) {
case AllNeuronsTogether:
dim = 1;
break;
case NeuronsIndividually:
dim = this.numNeuronTypes;
break;
case StoreSeparetlyCompareEvery:
dim = this.numNeuronTypes;
}
lastTs = new int[numOfCochleaChannels][dim][2][dimLastTs];
lastTsCursor = new int[numOfCochleaChannels][dim][2];
for (int i = 0; i < numOfCochleaChannels; i++) {
for (int j = 0; j < dim; j++) {
for (int k = 0; k < 2; k++) {
for (int l = 0; l < dimLastTs; l++) {
lastTs[i][j][k][l] = Integer.MIN_VALUE;
}
}
}
}
if (isFilterEnabled()) {
createBins();
setDisplay(display);
}
}
@Override
public void setFilterEnabled(boolean yes) {
// log.info("ITDFilter.setFilterEnabled() is called");
super.setFilterEnabled(yes);
if (yes) {
// try {
// createBins();
// } catch (Exception e) {
// log.warning("In genBins() caught exception " + e);
// e.printStackTrace();
// display = getPrefs().getBoolean("ITDFilter.display", false);
// setDisplay(display);
initFilter();
}
}
public void update(Observable o, Object arg) {
if (arg != null) {
// log.info("ITDFilter.update() is called from " + o + " with arg=" + arg);
if (arg.equals("eventClass")) {
if (chip.getEventClass() == CochleaAMSEvent.class) {
hasMultipleGanglionCellTypes = true;
this.numNeuronTypes = 4;
} else {
hasMultipleGanglionCellTypes = false;
this.numNeuronTypes = 1;
}
this.initFilter();
}
}
}
public int getMaxITD() {
return this.maxITD;
}
public void setMaxITD(int maxITD) {
getPrefs().putInt("ITDFilter.maxITD", maxITD);
support.firePropertyChange("maxITD", this.maxITD, maxITD);
this.maxITD = maxITD;
createBins();
}
public int getNumOfBins() {
return this.numOfBins;
}
public void setNumOfBins(int numOfBins) {
getPrefs().putInt("ITDFilter.numOfBins", numOfBins);
support.firePropertyChange("numOfBins", this.numOfBins, numOfBins);
this.numOfBins = numOfBins;
createBins();
}
public int getMaxWeight() {
return this.maxWeight;
}
public void setMaxWeight(int maxWeight) {
getPrefs().putInt("ITDFilter.maxWeight", maxWeight);
support.firePropertyChange("maxWeight", this.maxWeight, maxWeight);
this.maxWeight = maxWeight;
if (!isFilterEnabled()) {
return;
}
createBins();
}
public int getConfidenceThreshold() {
return this.confidenceThreshold;
}
public void setConfidenceThreshold(int confidenceThreshold) {
getPrefs().putInt("ITDFilter.confidenceThreshold", confidenceThreshold);
support.firePropertyChange("confidenceThreshold", this.confidenceThreshold, confidenceThreshold);
this.confidenceThreshold = confidenceThreshold;
}
public int getItdEventQueueSize() {
return this.itdEventQueueSize;
}
public void setItdEventQueueSize(int itdEventQueueSize) {
getPrefs().putInt("ITDFilter.itdEventQueueSize", itdEventQueueSize);
support.firePropertyChange("itdEventQueueSize", this.itdEventQueueSize, itdEventQueueSize);
this.itdEventQueueSize = itdEventQueueSize;
if (this.sendITDsToOtherThread) {
ITDEventQueue = new ArrayBlockingQueue(itdEventQueueSize);
}
}
public int getMaxWeightTime() {
return this.maxWeightTime;
}
public void setMaxWeightTime(int maxWeightTime) {
getPrefs().putInt("ITDFilter.maxWeightTime", maxWeightTime);
support.firePropertyChange("maxWeightTime", this.maxWeightTime, maxWeightTime);
this.maxWeightTime = maxWeightTime;
if (!isFilterEnabled()) {
return;
}
createBins();
}
public int getDimLastTs() {
return this.dimLastTs;
}
public void setDimLastTs(int dimLastTs) {
getPrefs().putInt("ITDFilter.dimLastTs", dimLastTs);
support.firePropertyChange("dimLastTs", this.dimLastTs, dimLastTs);
//lastTs = new int[numOfCochleaChannels][numNeuronTypes][2][dimLastTs];
this.dimLastTs = dimLastTs;
this.initFilter();
}
public int getNumLoopMean() {
return this.numLoopMean;
}
public void setNumLoopMean(int numLoopMean) {
getPrefs().putInt("ITDFilter.numLoopMean", numLoopMean);
support.firePropertyChange("numLoopMean", this.numLoopMean, numLoopMean);
this.numLoopMean = numLoopMean;
if (!isFilterEnabled() || this.computeMeanInLoop == false) {
return;
}
if (myBins == null) {
createBins();
} else {
myBins.setNumLoopMean(numLoopMean);
}
}
public int getNumOfCochleaChannels() {
return this.numOfCochleaChannels;
}
public void setNumOfCochleaChannels(int numOfCochleaChannels) {
getPrefs().putInt("ITDFilter.numOfCochleaChannels", numOfCochleaChannels);
support.firePropertyChange("numOfCochleaChannels", this.numOfCochleaChannels, numOfCochleaChannels);
this.numOfCochleaChannels = numOfCochleaChannels;
lastTs = new int[numOfCochleaChannels][numNeuronTypes][2][dimLastTs];
lastTsCursor = new int[numOfCochleaChannels][numNeuronTypes][2];
}
public float getAveragingDecay() {
return this.averagingDecay;
}
public void setAveragingDecay(float averagingDecay) {
getPrefs().putDouble("ITDFilter.averagingDecay", averagingDecay);
support.firePropertyChange("averagingDecay", this.averagingDecay, averagingDecay);
this.averagingDecay = averagingDecay;
if (!isFilterEnabled()) {
return;
}
if (myBins == null) {
createBins();
} else {
myBins.setAveragingDecay(averagingDecay * 1000000);
}
}
/** Adds button to show display */
public void doToggleITDDisplay() {
boolean old = isDisplay();
setDisplay(!isDisplay());
support.firePropertyChange("display", old, display);
}
public void doConnectToPanTiltThread() {
PanTilt.initPanTilt();
this.connectToPanTiltThread = true;
}
public void doFitGaussianToBins(){
numOfBins=myBins.getNumOfBins();
double xData[] = new double[numOfBins];
double yData[] = new double[numOfBins];
for(int i=0;i<numOfBins;i++) {
xData[i]=i;
}
for(int i=0;i<numOfBins;i++) {
yData[i]=myBins.getBin(i);
}
//double yData[] = {4,6,5.6,3,2,1,0.1,1,1.4,1,0.6,1,1,0,0.5,0};
flanagan.analysis.Regression reg = new flanagan.analysis.Regression(xData, yData);
reg.gaussian();
double[] regResult = reg.getBestEstimates();
log.info("mean="+regResult[0]+" standardDeviation="+regResult[1]+" scale="+regResult[2]);
}
public boolean isDisplay() {
return this.display;
}
public void setDisplay(boolean display) {
getPrefs().putBoolean("ITDFilter.display", display);
support.firePropertyChange("display", this.display, display);
this.display = display;
if (!isFilterEnabled()) {
return;
}
if (display == false && frame != null) {
// frame.setVisible(false);
frame.dispose();
frame = null;
} else if (display == true) {
if (frame == null) {
try {
frame = new ITDFrame();
frame.binsPanel.updateBins(myBins);
// getChip().getFilterFrame().addWindowListener(new java.awt.event.WindowAdapter() {
// @Override
// public void windowClosed(java.awt.event.WindowEvent evt) {
// if (frame == null) {
// return;
// log.info("disposing of " + frame);
// frame.dispose(); // close ITD frame if filter frame is closed.
// frame = null;
// ITDFilter.this.display = false; // set this so we know that itdframe has been disposed so that next button press on doToggleITDDisplay works correctly
log.info("ITD-Jframe created with height=" + frame.getHeight() + " and width:" + frame.getWidth());
} catch (Exception e) {
log.warning("while creating ITD-Jframe, caught exception " + e);
e.printStackTrace();
}
}
if (!frame.isVisible()) {
frame.setVisible(true); // only grab focus by setting frame visible 0if frame is not already visible
}
}
}
@Override
public synchronized void cleanup() {
setDisplay(false);
}
public boolean getUseLaterSpikeForWeight() {
return this.useLaterSpikeForWeight;
}
public void setUseLaterSpikeForWeight(boolean useLaterSpikeForWeight) {
getPrefs().putBoolean("ITDFilter.useLaterSpikeForWeight", useLaterSpikeForWeight);
support.firePropertyChange("useLaterSpikeForWeight", this.useLaterSpikeForWeight, useLaterSpikeForWeight);
this.useLaterSpikeForWeight = useLaterSpikeForWeight;
if (!isFilterEnabled()) {
return;
}
createBins();
}
public boolean isUsePriorSpikeForWeight() {
return this.usePriorSpikeForWeight;
}
public void setUsePriorSpikeForWeight(boolean usePriorSpikeForWeight) {
getPrefs().putBoolean("ITDFilter.usePriorSpikeForWeight", usePriorSpikeForWeight);
support.firePropertyChange("usePriorSpikeForWeight", this.usePriorSpikeForWeight, usePriorSpikeForWeight);
this.usePriorSpikeForWeight = usePriorSpikeForWeight;
if (!isFilterEnabled()) {
return;
}
createBins();
}
public boolean isWriteBin2File() {
return this.writeBin2File;
}
public void setWriteBin2File(boolean writeBin2File) {
if (writeBin2File == true) {
try {
JFileChooser fc = new JFileChooser();
fc.setDialogType(JFileChooser.SAVE_DIALOG);
int state = fc.showSaveDialog(null);
if (state == JFileChooser.APPROVE_OPTION) {
String path = fc.getSelectedFile().getPath();
// Create file
fstreamBins = new FileWriter(path);
BinFile = new BufferedWriter(fstreamBins);
String titles = "time\t";
for (int i = 0; i < this.numOfBins; i++) {
titles += "Bin" + i + "\t";
}
BinFile.write(titles);
getPrefs().putBoolean("ITDFilter.writeBin2File", writeBin2File);
support.firePropertyChange("writeBin2File", this.writeBin2File, writeBin2File);
this.writeBin2File = writeBin2File;
}
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
} else if (BinFile != null) {
try {
//Close the output stream
BinFile.close();
BinFile = null;
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
public boolean isWriteITD2File() {
return this.writeITD2File;
}
public void setWriteITD2File(boolean writeITD2File) {
getPrefs().putBoolean("ITDFilter.writeITD2File", writeITD2File);
support.firePropertyChange("writeITD2File", this.writeITD2File, writeITD2File);
this.writeITD2File = writeITD2File;
if (writeITD2File == true) {
try {
// Create file
fstream = new FileWriter("ITDoutput.dat");
ITDFile = new BufferedWriter(fstream);
ITDFile.write("time\tITD\tconf\n");
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
} else {
try {
//Close the output stream
ITDFile.close();
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
if (writeITD2File == true) {
try {
JFileChooser fc = new JFileChooser();
fc.setDialogType(JFileChooser.SAVE_DIALOG);
int state = fc.showSaveDialog(null);
if (state == JFileChooser.APPROVE_OPTION) {
String path = fc.getSelectedFile().getPath();
// Create file
fstream = new FileWriter(path);
ITDFile = new BufferedWriter(fstream);
ITDFile.write("time\tITD\tconf\n");
getPrefs().putBoolean("ITDFilter.writeITD2File", writeITD2File);
support.firePropertyChange("writeITD2File", this.writeITD2File, writeITD2File);
this.writeITD2File = writeITD2File;
}
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
} else if (ITDFile != null) {
try {
//Close the output stream
ITDFile.close();
ITDFile = null;
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
public boolean isSendITDsToOtherThread() {
return this.sendITDsToOtherThread;
}
public void setSendITDsToOtherThread(boolean sendITDsToOtherThread) {
getPrefs().putBoolean("ITDFilter.sendITDsToOtherThread", sendITDsToOtherThread);
support.firePropertyChange("sendITDsToOtherThread", this.sendITDsToOtherThread, sendITDsToOtherThread);
this.sendITDsToOtherThread = sendITDsToOtherThread;
if (sendITDsToOtherThread == true) {
ITDEventQueue = new ArrayBlockingQueue(this.itdEventQueueSize);
} else {
ITDEventQueue = null;
}
}
public boolean isWrite2FileForEverySpike() {
return this.write2FileForEverySpike;
}
public void setWrite2FileForEverySpike(boolean write2FileForEverySpike) {
getPrefs().putBoolean("ITDFilter.write2FileForEverySpike", write2FileForEverySpike);
support.firePropertyChange("write2FileForEverySpike", this.write2FileForEverySpike, write2FileForEverySpike);
this.write2FileForEverySpike = write2FileForEverySpike;
}
public boolean isNormToConfThresh() {
return this.normToConfThresh;
}
public void setNormToConfThresh(boolean normToConfThresh) {
getPrefs().putBoolean("ITDFilter.normToConfThresh", normToConfThresh);
support.firePropertyChange("normToConfThresh", this.normToConfThresh, normToConfThresh);
this.normToConfThresh = normToConfThresh;
}
public boolean isShowAnnotations() {
return this.showAnnotations;
}
public void setShowAnnotations(boolean showAnnotations) {
getPrefs().putBoolean("ITDFilter.showAnnotations", showAnnotations);
support.firePropertyChange("showAnnotations", this.showAnnotations, showAnnotations);
this.showAnnotations = showAnnotations;
}
public boolean isComputeMeanInLoop() {
return this.useLaterSpikeForWeight;
}
public void setComputeMeanInLoop(boolean computeMeanInLoop) {
getPrefs().putBoolean("ITDFilter.computeMeanInLoop", computeMeanInLoop);
support.firePropertyChange("computeMeanInLoop", this.computeMeanInLoop, computeMeanInLoop);
this.computeMeanInLoop = computeMeanInLoop;
if (!isFilterEnabled()) {
return;
}
if (computeMeanInLoop == true) {
if (myBins == null) {
createBins();
} else {
myBins.setNumLoopMean(numLoopMean);
}
} else {
if (myBins == null) {
createBins();
} else {
myBins.setNumLoopMean(1);
}
}
}
public boolean isUseCalibration() {
return this.useCalibration;
}
public void setUseCalibration(boolean useCalibration) {
getPrefs().putBoolean("ITDFilter.useCalibration", useCalibration);
support.firePropertyChange("useCalibration", this.useCalibration, useCalibration);
this.useCalibration = useCalibration;
createBins();
}
public boolean isInvert() {
return this.invert;
}
public void setInvert(boolean invert) {
getPrefs().putBoolean("ITDFilter.invert", invert);
support.firePropertyChange("invert", this.invert, invert);
this.invert = invert;
}
public void doSelectCalibrationFile() {
if (calibrationFilePath == null || calibrationFilePath.isEmpty()) {
calibrationFilePath = System.getProperty("user.dir");
}
JFileChooser chooser = new JFileChooser(calibrationFilePath);
chooser.setDialogTitle("Choose calibration .xml file (created with matlab)");
chooser.setFileFilter(new FileFilter() {
@Override
public boolean accept(File f) {
return f.isDirectory() || f.getName().toLowerCase().endsWith(".xml");
}
@Override
public String getDescription() {
return "Executables";
}
});
chooser.setMultiSelectionEnabled(false);
int retval = chooser.showOpenDialog(getChip().getAeViewer().getFilterFrame());
if (retval == JFileChooser.APPROVE_OPTION) {
File f = chooser.getSelectedFile();
if (f != null && f.isFile()) {
setCalibrationFilePath(f.toString());
log.info("selected xml calibration file " + calibrationFilePath);
setUseCalibration(true);
}
}
}
/**
* @return the calibrationFilePath
*/
public String getCalibrationFilePath() {
return calibrationFilePath;
}
/**
* @param calibrationFilePath the calibrationFilePath to set
*/
public void setCalibrationFilePath(String calibrationFilePath) {
support.firePropertyChange("calibrationFilePath", this.calibrationFilePath, calibrationFilePath);
this.calibrationFilePath = calibrationFilePath;
getPrefs().put("ITDFilter.calibrationFilePath", calibrationFilePath);
}
public EstimationMethod getEstimationMethod() {
return estimationMethod;
}
synchronized public void setEstimationMethod(EstimationMethod estimationMethod) {
support.firePropertyChange("estimationMethod", this.estimationMethod, estimationMethod);
getPrefs().put("ITDfilter.estimationMethod", estimationMethod.toString());
this.estimationMethod = estimationMethod;
}
public AMSprocessingMethod getAmsProcessingMethod() {
return amsProcessingMethod;
}
synchronized public void setAmsProcessingMethod(AMSprocessingMethod amsProcessingMethod) {
support.firePropertyChange("amsProcessingMethod", this.amsProcessingMethod, amsProcessingMethod);
getPrefs().put("ITDfilter.amsProcessingMethod", amsProcessingMethod.toString());
this.amsProcessingMethod = amsProcessingMethod;
this.initFilter();
}
public CochleaAMSEvent.FilterType getUseGanglionCellType() {
return useGanglionCellType;
}
synchronized public void setUseGanglionCellType(CochleaAMSEvent.FilterType useGanglionCellType) {
support.firePropertyChange("useGanglionCellType", this.useGanglionCellType, useGanglionCellType);
getPrefs().put("ITDfilter.useGanglionCellType", useGanglionCellType.toString());
this.useGanglionCellType = useGanglionCellType;
}
public static ITDEvent takeITDEvent() throws InterruptedException {
return (ITDEvent) ITDEventQueue.take();
}
public static ITDEvent pollITDEvent() {
if (ITDEventQueue != null) {
return (ITDEvent) ITDEventQueue.poll();
} else {
return null;
}
}
private void createBins() {
int numLoop;
if (this.computeMeanInLoop == true) {
numLoop = numLoopMean;
} else {
numLoop = 1;
}
if (useCalibration == false) {
//log.info("create Bins with averagingDecay=" + averagingDecay + " and maxITD=" + maxITD + " and numOfBins=" + numOfBins);
myBins = new ITDBins((float) averagingDecay * 1000000, numLoop, maxITD, numOfBins);
} else {
if (calibration == null) {
calibration = new ITDCalibrationGaussians();
calibration.loadCalibrationFile(calibrationFilePath);
support.firePropertyChange("numOfBins", this.numOfBins, calibration.getNumOfBins());
this.numOfBins = calibration.getNumOfBins();
}
//log.info("create Bins with averagingDecay=" + averagingDecay + " and calibration file");
myBins = new ITDBins((float) averagingDecay * 1000000, numLoop, calibration);
}
if (display == true && frame != null) {
frame.binsPanel.updateBins(myBins);
}
}
public void annotate(GLAutoDrawable drawable) {
if (!isFilterEnabled()) {
return;
}
GL gl = drawable.getGL();
gl.glPushMatrix();
final GLUT glut = new GLUT();
gl.glColor3f(1, 1, 1);
gl.glRasterPos3f(0, 0, 0);
if (showAnnotations == true) {
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, String.format("avgITD(us)=%s", fmt.format(avgITD)));
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, String.format(" ITDConfidence=%f", avgITDConfidence));
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, String.format(" ILD=%f", ILD));
if (useLaterSpikeForWeight == true || usePriorSpikeForWeight == true) {
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, String.format(" lastWeight=%f", lastWeight));
}
}
if (display == true && frame != null) {
//frame.setITD(avgITD);
frame.setText(String.format("avgITD(us)=%s ITDConfidence=%f ILD=%f", fmt.format(avgITD), avgITDConfidence, ILD));
}
gl.glPopMatrix();
}
public void annotate(float[][][] frame) {
throw new UnsupportedOperationException("Not supported yet, use openGL rendering.");
}
public void annotate(Graphics2D g) {
throw new UnsupportedOperationException("Not supported yet, use openGL rendering..");
}
/** Returns the ITDBins object.
*
* @return the ITDBins object.
*/
public ITDBins getITDBins(){
return myBins;
}
}
|
package com.exedio.cope.util;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import com.exedio.cope.junit.CopeAssert;
public class PoolCounterTest extends CopeAssert
{
public void testIt()
{
final Date before = new Date();
final PoolCounter c = new PoolCounter(new int[]{0,2});
final Date after = new Date();
assertWithin(before, after, c.getStart());
final Iterator pi = c.getPools().iterator();
final PoolCounter.Pool p0 = (PoolCounter.Pool)pi.next();
final PoolCounter.Pool p2 = (PoolCounter.Pool)pi.next();
assertFalse(pi.hasNext());
assertIt(c, 0, 0);
assertIt(p0, 0, 0, 0, 0, 0, 0);
assertIt(p2, 2, 0, 0, 0, 0, 0);
c.incrementGet();
assertIt(c, 1, 0); assertIt(p0,0, 0, 0, 1, 0, 0); assertIt(p2,2, 0, 0, 1, 0, 0);
c.incrementGet();
assertIt(c, 2, 0); assertIt(p0,0, 0, 0, 2, 0, 0); assertIt(p2,2, 0, 0, 2, 0, 0);
c.incrementPut();
assertIt(c, 2, 1); assertIt(p0,0, 0, 0, 2, 1, 50); assertIt(p2,2, 1, 1, 2, 0, 0);
c.incrementPut();
assertIt(c, 2, 2); assertIt(p0,0, 0, 0, 2, 2,100); assertIt(p2,2, 2, 2, 2, 0, 0);
c.incrementPut();
assertIt(c, 2, 3); assertIt(p0,0, 0, 0, 2, 3,150); assertIt(p2,2, 2, 2, 2, 1,50);
c.incrementGet();
assertIt(c, 3, 3); assertIt(p0,0, 0, 0, 3, 3,100); assertIt(p2,2, 1, 2, 2, 1,33);
final PoolCounter c2 = new PoolCounter(c);
final Iterator p2i = c2.getPools().iterator();
final PoolCounter.Pool p20 = (PoolCounter.Pool)p2i.next();
final PoolCounter.Pool p22 = (PoolCounter.Pool)p2i.next();
assertFalse(p2i.hasNext());
assertIt(c2, 3, 3); assertIt(p20,0, 0, 0, 3, 3,100); assertIt(p22,2, 1, 2, 2, 1,33);
}
public void testExtend()
{
final PoolCounter c = new PoolCounter(new int[]{0,2,4,6});
{
final List<PoolCounter.Pool> ps = c.getPools();
assertEquals(4, ps.size());
assertIt(ps.get(0), 0, 0, 0, 0, 0, 0);
assertIt(ps.get(1), 2, 0, 0, 0, 0, 0);
assertIt(ps.get(2), 4, 0, 0, 0, 0, 0);
assertIt(ps.get(3), 6, 0, 0, 0, 0, 0);
}
c.incrementGet();
{
final List<PoolCounter.Pool> ps = c.getPools();
assertEquals(4, ps.size());
assertIt(ps.get(0), 0, 0, 0, 1, 0, 0);
assertIt(ps.get(1), 2, 0, 0, 1, 0, 0);
assertIt(ps.get(2), 4, 0, 0, 1, 0, 0);
assertIt(ps.get(3), 6, 0, 0, 1, 0, 0);
}
c.incrementGet();
{
final List<PoolCounter.Pool> ps = c.getPools();
assertEquals(4, ps.size());
assertIt(ps.get(0), 0, 0, 0, 2, 0, 0);
assertIt(ps.get(1), 2, 0, 0, 2, 0, 0);
assertIt(ps.get(2), 4, 0, 0, 2, 0, 0);
assertIt(ps.get(3), 6, 0, 0, 2, 0, 0);
}
c.incrementGet();
{
final List<PoolCounter.Pool> ps = c.getPools();
assertEquals(4, ps.size());
assertIt(ps.get(0), 0, 0, 0, 3, 0, 0);
assertIt(ps.get(1), 2, 0, 0, 3, 0, 0);
assertIt(ps.get(2), 4, 0, 0, 3, 0, 0);
assertIt(ps.get(3), 6, 0, 0, 3, 0, 0);
}
c.incrementGet();
{
final List<PoolCounter.Pool> ps = c.getPools();
assertEquals(4, ps.size());
assertIt(ps.get(0), 0, 0, 0, 4, 0, 0);
assertIt(ps.get(1), 2, 0, 0, 4, 0, 0);
assertIt(ps.get(2), 4, 0, 0, 4, 0, 0);
assertIt(ps.get(3), 6, 0, 0, 4, 0, 0);
}
c.incrementGet();
{
final List<PoolCounter.Pool> ps = c.getPools();
assertEquals(4, ps.size());
assertIt(ps.get(0), 0, 0, 0, 5, 0, 0);
assertIt(ps.get(1), 2, 0, 0, 5, 0, 0);
assertIt(ps.get(2), 4, 0, 0, 5, 0, 0);
assertIt(ps.get(3), 6, 0, 0, 5, 0, 0);
}
c.incrementGet();
{
final List<PoolCounter.Pool> ps = c.getPools();
assertEquals(4, ps.size());
assertIt(ps.get(0), 0, 0, 0, 6, 0, 0);
assertIt(ps.get(1), 2, 0, 0, 6, 0, 0);
assertIt(ps.get(2), 4, 0, 0, 6, 0, 0);
assertIt(ps.get(3), 6, 0, 0, 6, 0, 0);
}
c.incrementGet();
{
final List<PoolCounter.Pool> ps = c.getPools();
assertEquals(4, ps.size());
assertIt(ps.get(0), 0, 0, 0, 7, 0, 0);
assertIt(ps.get(1), 2, 0, 0, 7, 0, 0);
assertIt(ps.get(2), 4, 0, 0, 7, 0, 0);
assertIt(ps.get(3), 6, 0, 0, 7, 0, 0);
}
c.incrementPut();
{
final List<PoolCounter.Pool> ps = c.getPools();
assertEquals(4, ps.size());
assertIt(ps.get(0), 0, 0, 0, 7, 1, 14);
assertIt(ps.get(1), 2, 1, 1, 7, 0, 0);
assertIt(ps.get(2), 4, 1, 1, 7, 0, 0);
assertIt(ps.get(3), 6, 1, 1, 7, 0, 0);
}
c.incrementPut();
{
final List<PoolCounter.Pool> ps = c.getPools();
assertEquals(4, ps.size());
assertIt(ps.get(0), 0, 0, 0, 7, 2, 28);
assertIt(ps.get(1), 2, 2, 2, 7, 0, 0);
assertIt(ps.get(2), 4, 2, 2, 7, 0, 0);
assertIt(ps.get(3), 6, 2, 2, 7, 0, 0);
}
c.incrementPut();
{
final List<PoolCounter.Pool> ps = c.getPools();
assertEquals(4, ps.size());
assertIt(ps.get(0), 0, 0, 0, 7, 3, 42);
assertIt(ps.get(1), 2, 2, 2, 7, 1, 14);
assertIt(ps.get(2), 4, 3, 3, 7, 0, 0);
assertIt(ps.get(3), 6, 3, 3, 7, 0, 0);
}
}
static final void assertIt(final PoolCounter p, final int getCounter, final int putCounter)
{
assertEquals(getCounter, p.getGetCounter());
assertEquals(putCounter, p.getPutCounter());
}
static final void assertIt(
final PoolCounter.Pool p, final int size,
final int idleCount, final int idleCountMax,
final int createCounter, final int destroyCounter,
final int loss)
{
assertEquals(size, p.getSize());
assertEquals(idleCount, p.getIdleCount());
assertEquals(idleCountMax, p.getIdleCountMax());
assertEquals(createCounter, p.getCreateCounter());
assertEquals(destroyCounter, p.getDestroyCounter());
assertEquals(loss, p.getLoss());
assertTrue(p.isConsistent());
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ch.unizh.ini.jaer.projects.cochsoundloc;
import ch.unizh.ini.jaer.chip.cochlea.BinauralCochleaEvent;
import ch.unizh.ini.jaer.chip.cochlea.BinauralCochleaEvent.Ear;
import ch.unizh.ini.jaer.chip.cochlea.CochleaAMSEvent;
import net.sf.jaer.chip.*;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.eventprocessing.EventFilter2D;
import java.util.*;
import com.sun.opengl.util.GLUT;
import java.awt.Graphics2D;
import javax.media.opengl.GL;
import javax.media.opengl.GLAutoDrawable;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.util.EngineeringFormat;
import java.io.*;
import java.util.concurrent.ArrayBlockingQueue;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
/**
* Extracts interaural time difference (ITD) from a binaural cochlea input.
*
* @author Holger
*/
public class ITDFilter extends EventFilter2D implements Observer, FrameAnnotater {
public static String getDescription() {
return "Measures ITD (Interaural time difference) using a variety of methods";
}
private ITDCalibrationGaussians calibration = null;
private float averagingDecay = getPrefs().getFloat("ITDFilter.averagingDecay", 1);
private int maxITD = getPrefs().getInt("ITDFilter.maxITD", 800);
private int numOfBins = getPrefs().getInt("ITDFilter.numOfBins", 16);
private int maxWeight = getPrefs().getInt("ITDFilter.maxWeight", 5);
private int dimLastTs = getPrefs().getInt("ITDFilter.dimLastTs", 4);
private int maxWeightTime = getPrefs().getInt("ITDFilter.maxWeightTime", 500000);
private boolean display = getPrefs().getBoolean("ITDFilter.display", false);
private boolean useLaterSpikeForWeight = getPrefs().getBoolean("ITDFilter.useLaterSpikeForWeight", true);
private boolean usePriorSpikeForWeight = getPrefs().getBoolean("ITDFilter.usePriorSpikeForWeight", true);
private boolean computeMeanInLoop = getPrefs().getBoolean("ITDFilter.computeMeanInLoop", true);
private boolean writeITD2File = getPrefs().getBoolean("ITDFilter.writeITD2File", false);
private boolean sendITDsToOtherThread = getPrefs().getBoolean("ITDFilter.sendITDsToOtherThread", false);
private int itdEventQueueSize = getPrefs().getInt("ITDFilter.itdEventQueueSize", 1000);
private boolean writeBin2File = getPrefs().getBoolean("ITDFilter.writeBin2File", false);
private boolean write2FileForEverySpike = getPrefs().getBoolean("ITDFilter.write2FileForEverySpike", false);
private boolean normToConfThresh = getPrefs().getBoolean("ITDFilter.normToConfThresh", false);
private boolean showAnnotations = getPrefs().getBoolean("ITDFilter.showAnnotations", false);
private int confidenceThreshold = getPrefs().getInt("ITDFilter.confidenceThreshold", 30);
private int numLoopMean = getPrefs().getInt("ITDFilter.numLoopMean", 2);
private int numOfCochleaChannels = getPrefs().getInt("ITDFilter.numOfCochleaChannels", 32);
private boolean useCalibration = getPrefs().getBoolean("ITDFilter.useCalibration", false);
private String calibrationFilePath = getPrefs().get("ITDFilter.calibrationFilePath", null);
ITDFrame frame;
private ITDBins myBins;
private boolean connectToPanTiltThread = false;
//private LinkedList[][] lastTimestamps;
//private ArrayList<LinkedList<Integer>> lastTimestamps0;
//private ArrayList<LinkedList<Integer>> lastTimestamps1;
private int[][][][] lastTs;
private int[][][] lastTsCursor;
//private int[][] AbsoluteLastTimestamp;
Iterator iterator;
private float lastWeight = 1f;
private int avgITD;
private float avgITDConfidence = 0;
private float ILD;
EngineeringFormat fmt = new EngineeringFormat();
FileWriter fstream;
FileWriter fstreamBins;
BufferedWriter ITDFile;
BufferedWriter BinFile;
private boolean wasMoving = false;
private int numNeuronTypes = 1;
private static ArrayBlockingQueue ITDEventQueue = null;
private boolean ITDEventQueueFull = false;
public enum EstimationMethod {
useMedian, useMean, useMax
};
private EstimationMethod estimationMethod = EstimationMethod.valueOf(getPrefs().get("ITDFilter.estimationMethod", "useMedian"));
public enum AMSprocessingMethod {
NeuronsIndividually, AllNeuronsTogether, StoreSeparetlyCompareEvery
};
private AMSprocessingMethod amsProcessingMethod = AMSprocessingMethod.valueOf(getPrefs().get("ITDFilter.amsProcessingMethod", "NeuronsIndividually"));
// public enum UseGanglionCellType {
// LPF, BPF
private CochleaAMSEvent.FilterType useGanglionCellType = CochleaAMSEvent.FilterType.valueOf(getPrefs().get("ITDFilter.useGanglionCellType", "LPF"));
private boolean hasMultipleGanglionCellTypes = false;
// private ActionListener updateBinFrame = new ActionListener() {
// public void actionPerformed(ActionEvent evt) {
// //wasMoving = false;
// private javax.swing.Timer timer = new javax.swing.Timer(5, updateBinFrame);
private float averagingDecayTmp = 0;
public ITDFilter(AEChip chip) {
super(chip);
chip.addObserver(this);
initFilter();
//resetFilter();
//lastTimestamps = (LinkedList[][])new LinkedList[32][2];
//LinkedList[][] <Integer>lastTimestamps = new LinkedList<Integer>[1][2]();
// lastTimestamps0 = new ArrayList<LinkedList<Integer>>(32);
// lastTimestamps1 = new ArrayList<LinkedList<Integer>>(32);
// for (int k=0;k<32;k++) {
// lastTimestamps0.add(new LinkedList<Integer>());
// lastTimestamps1.add(new LinkedList<Integer>());
//AbsoluteLastTimestamp = new int[32][2];
setPropertyTooltip("averagingDecay", "The decay constant of the fade out of old ITDs (in sec). Set to 0 to disable fade out.");
setPropertyTooltip("maxITD", "maximum ITD to compute in us");
setPropertyTooltip("numOfBins", "total number of bins");
setPropertyTooltip("dimLastTs", "how many lastTs save");
setPropertyTooltip("maxWeight", "maximum weight for ITDs");
setPropertyTooltip("maxWeightTime", "maximum time to use for weighting ITDs");
setPropertyTooltip("display", "display bins");
setPropertyTooltip("useLaterSpikeForWeight", "use the side of the later arriving spike to weight the ITD");
setPropertyTooltip("usePriorSpikeForWeight", "use the side of the prior arriving spike to weight the ITD");
setPropertyTooltip("computeMeanInLoop", "use a loop to compute the mean or median to avoid biasing");
setPropertyTooltip("useCalibration", "use xml calibration file");
setPropertyTooltip("confidenceThreshold", "ITDs with confidence below this threshold are neglected");
setPropertyTooltip("writeITD2File", "Write the ITD-values to a File");
setPropertyTooltip("writeBin2File", "Write the Bin-values to a File");
setPropertyTooltip("write2FileForEverySpike", "Write the values to file after every spike or after every packet");
setPropertyTooltip("SelectCalibrationFile", "select the xml file which can be created by matlab");
setPropertyTooltip("calibrationFilePath", "Full path to xml calibration file");
setPropertyTooltip("estimationMethod", "Method used to compute the ITD");
setPropertyTooltip("useGanglionCellType", "If CochleaAMS which Ganglion cells to use");
setPropertyTooltip("amsProcessingMethod", "If CochleaAMS how to process different neurons");
setPropertyTooltip("numLoopMean", "Method used to compute the ITD");
setPropertyTooltip("numOfCochleaChannels", "The number of frequency channels of the cochleae");
setPropertyTooltip("normToConfThresh", "Normalize the bins before every spike to the value of the confidence Threshold");
setPropertyTooltip("ToggleITDDisplay", "Toggles graphical display of ITD");
addPropertyToGroup("ITDWeighting", "useLaterSpikeForWeight");
addPropertyToGroup("ITDWeighting", "usePriorSpikeForWeight");
addPropertyToGroup("ITDWeighting", "maxWeight");
addPropertyToGroup("ITDWeighting", "maxWeightTime");
}
public EventPacket<?> filterPacket(EventPacket<?> in) {
if (!filterEnabled) {
return in;
}
if (connectToPanTiltThread) {
CommObjForITDFilter commObjIncomming = PanTilt.pollBlockingQForITDFilter();
while (commObjIncomming != null) {
log.info("Got a commObj from the PanTiltThread!");
switch (commObjIncomming.getCommand()) {
case 0:
break;
case 1:
break;
case 2:
break;
case 3:
averagingDecayTmp = this.averagingDecay;
this.setAveragingDecay(0);
break;
case 4:
this.setAveragingDecay(averagingDecayTmp);
break;
case 5:
this.myBins.clear();
break;
}
commObjIncomming = PanTilt.pollBlockingQForITDFilter();
}
}
if (connectToPanTiltThread && (PanTilt.isMoving() || PanTilt.isWasMoving())) {
this.wasMoving = true;
return in;
}
if (this.wasMoving == true) {
this.wasMoving = false;
this.myBins.clear();
log.info("clear bins!");
}
checkOutputPacketEventType(in);
if (in.isEmpty()) {
return in;
}
int nleft = 0, nright = 0;
for (Object e : in) {
BinauralCochleaEvent i = (BinauralCochleaEvent) e;
int ganglionCellThreshold;
if (hasMultipleGanglionCellTypes &&
(this.amsProcessingMethod == AMSprocessingMethod.NeuronsIndividually ||
this.amsProcessingMethod == AMSprocessingMethod.StoreSeparetlyCompareEvery)) {
CochleaAMSEvent camsevent = ((CochleaAMSEvent) i);
ganglionCellThreshold = camsevent.getThreshold();
// if (useGanglionCellType != camsevent.getFilterType()) {
// continue;
} else {
ganglionCellThreshold = 0;
}
try {
int ear;
if (i.getEar() == Ear.RIGHT) {
ear = 0;
} else {
ear = 1;
}
//log.info("ear="+i.getEar()+" type="+i.getType());
if (i.x >= numOfCochleaChannels) {
log.warning("there was a BasicEvent i with i.x=" + i.x + " >= " + numOfCochleaChannels + "=numOfCochleaChannels! Therefore set numOfCochleaChannels=" + (i.x + 1));
setNumOfCochleaChannels(i.x + 1);
} else {
int cursor = lastTsCursor[i.x][ganglionCellThreshold][1 - ear];
do {
int diff = i.timestamp - lastTs[i.x][ganglionCellThreshold][1 - ear][cursor];
if (ear == 0) {
diff = -diff;
nright++;
} else {
nleft++;
}
if (java.lang.Math.abs(diff) < maxITD) {
lastWeight = 1f;
//Compute weight:
if (useLaterSpikeForWeight == true) {
int weightTimeThisSide = i.timestamp - lastTs[i.x][ganglionCellThreshold][ear][lastTsCursor[i.x][ganglionCellThreshold][ear]];
if (weightTimeThisSide > maxWeightTime) {
weightTimeThisSide = maxWeightTime;
}
lastWeight *= ((weightTimeThisSide * (maxWeight - 1f)) / (float) maxWeightTime) + 1f;
if (weightTimeThisSide < 0) {
//log.warning("weightTimeThisSide < 0");
lastWeight = 0;
}
}
if (usePriorSpikeForWeight == true) {
int weightTimeOtherSide = lastTs[i.x][ganglionCellThreshold][1 - ear][cursor] - lastTs[i.x][ganglionCellThreshold][1 - ear][(cursor + 1) % dimLastTs];
if (weightTimeOtherSide > maxWeightTime) {
weightTimeOtherSide = maxWeightTime;
}
lastWeight *= ((weightTimeOtherSide * (maxWeight - 1f)) / (float) maxWeightTime) + 1f;
if (weightTimeOtherSide < 0) {
//log.warning("weightTimeOtherSide < 0");
lastWeight = 0;
}
}
if (this.normToConfThresh == true) {
myBins.addITD(diff, i.timestamp, i.x, lastWeight, this.confidenceThreshold);
} else {
myBins.addITD(diff, i.timestamp, i.x, lastWeight, 0);
}
if (this.sendITDsToOtherThread) {
if (ITDEventQueue==null) {
ITDEventQueue = new ArrayBlockingQueue(this.itdEventQueueSize);
}
ITDEvent itdEvent = new ITDEvent(diff, i.timestamp, i.x, lastWeight);
boolean success = ITDEventQueue.offer(itdEvent);
if (success == false) {
ITDEventQueueFull = true;
log.warning("Could not add ITD-Event to the ITDEventQueue. Probably itdEventQueueSize is too small!!!");
}
else
{
ITDEventQueueFull = false;
}
}
} else {
break;
}
cursor = (++cursor) % dimLastTs;
} while (cursor != lastTsCursor[i.x][ganglionCellThreshold][1 - ear]);
//Now decrement the cursor (circularly)
if (lastTsCursor[i.x][ganglionCellThreshold][ear] == 0) {
lastTsCursor[i.x][ganglionCellThreshold][ear] = dimLastTs;
}
lastTsCursor[i.x][ganglionCellThreshold][ear]
//Add the new timestamp to the list
lastTs[i.x][ganglionCellThreshold][ear][lastTsCursor[i.x][ganglionCellThreshold][ear]] = i.timestamp;
if (this.write2FileForEverySpike == true) {
if (this.writeITD2File == true && ITDFile != null) {
refreshITD();
ITDFile.write(i.timestamp + "\t" + avgITD + "\t" + avgITDConfidence + "\n");
}
if (this.writeBin2File == true && BinFile != null) {
refreshITD();
BinFile.write(i.timestamp + "\t" + myBins.toString() + "\n");
}
}
}
} catch (Exception e1) {
log.warning("In for-loop in filterPacket caught exception " + e1);
e1.printStackTrace();
}
}
try {
if (this.normToConfThresh == true) {
myBins.updateTime(this.confidenceThreshold, in.getLastTimestamp());
} else {
myBins.updateTime(0, in.getLastTimestamp());
}
refreshITD();
ILD = (float) (nleft - nright) / (float) (nright + nleft); //Max ILD is 1 (if only one side active)
if (this.write2FileForEverySpike == false) {
if (this.writeITD2File == true && ITDFile != null) {
ITDFile.write(in.getLastTimestamp() + "\t" + avgITD + "\t" + avgITDConfidence + "\n");
}
if (this.writeBin2File == true && BinFile != null) {
BinFile.write(in.getLastTimestamp() + "\t" + myBins.toString() + "\n");
}
}
} catch (Exception e) {
log.warning("In filterPacket caught exception " + e);
e.printStackTrace();
}
return in;
}
public void refreshITD() {
int avgITDtemp = 0;
switch (estimationMethod) {
case useMedian:
avgITDtemp = myBins.getITDMedian();
break;
case useMean:
avgITDtemp = myBins.getITDMean();
break;
case useMax:
avgITDtemp = myBins.getITDMax();
}
avgITDConfidence = myBins.getITDConfidence();
if (avgITDConfidence > confidenceThreshold) {
avgITD = avgITDtemp;
if (connectToPanTiltThread == true) {
CommObjForPanTilt filterOutput = new CommObjForPanTilt();
filterOutput.setFromCochlea(true);
filterOutput.setPanOffset((float) avgITD);
filterOutput.setConfidence(avgITDConfidence);
PanTilt.offerBlockingQ(filterOutput);
}
}
if (frame != null) {
frame.binsPanel.repaint();
}
}
public Object getFilterState() {
return null;
}
public void resetFilter() {
initFilter();
}
@Override
public void initFilter() {
// log.info("init() called");
int dim = 1;
switch (amsProcessingMethod) {
case AllNeuronsTogether:
dim = 1;
break;
case NeuronsIndividually:
dim = this.numNeuronTypes;
break;
case StoreSeparetlyCompareEvery:
dim = this.numNeuronTypes;
}
lastTs = new int[numOfCochleaChannels][dim][2][dimLastTs];
lastTsCursor = new int[numOfCochleaChannels][dim][2];
for (int i = 0; i < numOfCochleaChannels; i++) {
for (int j = 0; j < dim; j++) {
for (int k = 0; k < 2; k++) {
for (int l = 0; l < dimLastTs; l++) {
lastTs[i][j][k][l] = Integer.MIN_VALUE;
}
}
}
}
if (isFilterEnabled()) {
createBins();
setDisplay(display);
}
}
@Override
public void setFilterEnabled(boolean yes) {
// log.info("ITDFilter.setFilterEnabled() is called");
super.setFilterEnabled(yes);
if (yes) {
// try {
// createBins();
// } catch (Exception e) {
// log.warning("In genBins() caught exception " + e);
// e.printStackTrace();
// display = getPrefs().getBoolean("ITDFilter.display", false);
// setDisplay(display);
initFilter();
}
}
public void update(Observable o, Object arg) {
if (arg != null) {
// log.info("ITDFilter.update() is called from " + o + " with arg=" + arg);
if (arg.equals("eventClass")) {
if (chip.getEventClass() == CochleaAMSEvent.class) {
hasMultipleGanglionCellTypes = true;
this.numNeuronTypes = 4;
} else {
hasMultipleGanglionCellTypes = false;
this.numNeuronTypes = 1;
}
this.initFilter();
}
}
}
public int getMaxITD() {
return this.maxITD;
}
public void setMaxITD(int maxITD) {
getPrefs().putInt("ITDFilter.maxITD", maxITD);
support.firePropertyChange("maxITD", this.maxITD, maxITD);
this.maxITD = maxITD;
createBins();
}
public int getNumOfBins() {
return this.numOfBins;
}
public void setNumOfBins(int numOfBins) {
getPrefs().putInt("ITDFilter.numOfBins", numOfBins);
support.firePropertyChange("numOfBins", this.numOfBins, numOfBins);
this.numOfBins = numOfBins;
createBins();
}
public int getMaxWeight() {
return this.maxWeight;
}
public void setMaxWeight(int maxWeight) {
getPrefs().putInt("ITDFilter.maxWeight", maxWeight);
support.firePropertyChange("maxWeight", this.maxWeight, maxWeight);
this.maxWeight = maxWeight;
if (!isFilterEnabled()) {
return;
}
createBins();
}
public int getConfidenceThreshold() {
return this.confidenceThreshold;
}
public void setConfidenceThreshold(int confidenceThreshold) {
getPrefs().putInt("ITDFilter.confidenceThreshold", confidenceThreshold);
support.firePropertyChange("confidenceThreshold", this.confidenceThreshold, confidenceThreshold);
this.confidenceThreshold = confidenceThreshold;
}
public int getItdEventQueueSize() {
return this.itdEventQueueSize;
}
public void setItdEventQueueSize(int itdEventQueueSize) {
getPrefs().putInt("ITDFilter.itdEventQueueSize", itdEventQueueSize);
support.firePropertyChange("itdEventQueueSize", this.itdEventQueueSize, itdEventQueueSize);
this.itdEventQueueSize = itdEventQueueSize;
if (this.sendITDsToOtherThread) {
ITDEventQueue = new ArrayBlockingQueue(itdEventQueueSize);
}
}
public int getMaxWeightTime() {
return this.maxWeightTime;
}
public void setMaxWeightTime(int maxWeightTime) {
getPrefs().putInt("ITDFilter.maxWeightTime", maxWeightTime);
support.firePropertyChange("maxWeightTime", this.maxWeightTime, maxWeightTime);
this.maxWeightTime = maxWeightTime;
if (!isFilterEnabled()) {
return;
}
createBins();
}
public int getDimLastTs() {
return this.dimLastTs;
}
public void setDimLastTs(int dimLastTs) {
getPrefs().putInt("ITDFilter.dimLastTs", dimLastTs);
support.firePropertyChange("dimLastTs", this.dimLastTs, dimLastTs);
//lastTs = new int[numOfCochleaChannels][numNeuronTypes][2][dimLastTs];
this.dimLastTs = dimLastTs;
this.initFilter();
}
public int getNumLoopMean() {
return this.numLoopMean;
}
public void setNumLoopMean(int numLoopMean) {
getPrefs().putInt("ITDFilter.numLoopMean", numLoopMean);
support.firePropertyChange("numLoopMean", this.numLoopMean, numLoopMean);
this.numLoopMean = numLoopMean;
if (!isFilterEnabled() || this.computeMeanInLoop == false) {
return;
}
if (myBins == null) {
createBins();
} else {
myBins.setNumLoopMean(numLoopMean);
}
}
public int getNumOfCochleaChannels() {
return this.numOfCochleaChannels;
}
public void setNumOfCochleaChannels(int numOfCochleaChannels) {
getPrefs().putInt("ITDFilter.numOfCochleaChannels", numOfCochleaChannels);
support.firePropertyChange("numOfCochleaChannels", this.numOfCochleaChannels, numOfCochleaChannels);
this.numOfCochleaChannels = numOfCochleaChannels;
lastTs = new int[numOfCochleaChannels][numNeuronTypes][2][dimLastTs];
lastTsCursor = new int[numOfCochleaChannels][numNeuronTypes][2];
}
public float getAveragingDecay() {
return this.averagingDecay;
}
public void setAveragingDecay(float averagingDecay) {
getPrefs().putDouble("ITDFilter.averagingDecay", averagingDecay);
support.firePropertyChange("averagingDecay", this.averagingDecay, averagingDecay);
this.averagingDecay = averagingDecay;
if (!isFilterEnabled()) {
return;
}
if (myBins == null) {
createBins();
} else {
myBins.setAveragingDecay(averagingDecay * 1000000);
}
}
/** Adds button to show display */
public void doToggleITDDisplay() {
boolean old = isDisplay();
setDisplay(!isDisplay());
support.firePropertyChange("display", old, display);
}
public void doConnectToPanTiltThread() {
PanTilt.initPanTilt();
this.connectToPanTiltThread = true;
}
public void doFitGaussianToBins(){
numOfBins=myBins.getNumOfBins();
double xData[] = new double[numOfBins];
double yData[] = new double[numOfBins];
for(int i=0;i<numOfBins;i++) {
xData[i]=i;
}
for(int i=0;i<numOfBins;i++) {
yData[i]=myBins.getBin(i);
}
//double yData[] = {4,6,5.6,3,2,1,0.1,1,1.4,1,0.6,1,1,0,0.5,0};
flanagan.analysis.Regression reg = new flanagan.analysis.Regression(xData, yData);
reg.gaussian();
double[] regResult = reg.getBestEstimates();
log.info("mean="+regResult[0]+" standardDeviation="+regResult[1]+" scale="+regResult[2]);
}
public boolean isDisplay() {
return this.display;
}
public void setDisplay(boolean display) {
getPrefs().putBoolean("ITDFilter.display", display);
support.firePropertyChange("display", this.display, display);
this.display = display;
if (!isFilterEnabled()) {
return;
}
if (display == false && frame != null) {
// frame.setVisible(false);
frame.dispose();
frame = null;
} else if (display == true) {
if (frame == null) {
try {
frame = new ITDFrame();
frame.binsPanel.updateBins(myBins);
// getChip().getFilterFrame().addWindowListener(new java.awt.event.WindowAdapter() {
// @Override
// public void windowClosed(java.awt.event.WindowEvent evt) {
// if (frame == null) {
// return;
// log.info("disposing of " + frame);
// frame.dispose(); // close ITD frame if filter frame is closed.
// frame = null;
// ITDFilter.this.display = false; // set this so we know that itdframe has been disposed so that next button press on doToggleITDDisplay works correctly
log.info("ITD-Jframe created with height=" + frame.getHeight() + " and width:" + frame.getWidth());
} catch (Exception e) {
log.warning("while creating ITD-Jframe, caught exception " + e);
e.printStackTrace();
}
}
if (!frame.isVisible()) {
frame.setVisible(true); // only grab focus by setting frame visible 0if frame is not already visible
}
}
}
@Override
public synchronized void cleanup() {
setDisplay(false);
}
public boolean getUseLaterSpikeForWeight() {
return this.useLaterSpikeForWeight;
}
public void setUseLaterSpikeForWeight(boolean useLaterSpikeForWeight) {
getPrefs().putBoolean("ITDFilter.useLaterSpikeForWeight", useLaterSpikeForWeight);
support.firePropertyChange("useLaterSpikeForWeight", this.useLaterSpikeForWeight, useLaterSpikeForWeight);
this.useLaterSpikeForWeight = useLaterSpikeForWeight;
if (!isFilterEnabled()) {
return;
}
createBins();
}
public boolean isUsePriorSpikeForWeight() {
return this.usePriorSpikeForWeight;
}
public void setUsePriorSpikeForWeight(boolean usePriorSpikeForWeight) {
getPrefs().putBoolean("ITDFilter.usePriorSpikeForWeight", usePriorSpikeForWeight);
support.firePropertyChange("usePriorSpikeForWeight", this.usePriorSpikeForWeight, usePriorSpikeForWeight);
this.usePriorSpikeForWeight = usePriorSpikeForWeight;
if (!isFilterEnabled()) {
return;
}
createBins();
}
public boolean isWriteBin2File() {
return this.writeBin2File;
}
public void setWriteBin2File(boolean writeBin2File) {
if (writeBin2File == true) {
try {
JFileChooser fc = new JFileChooser();
fc.setDialogType(JFileChooser.SAVE_DIALOG);
int state = fc.showSaveDialog(null);
if (state == JFileChooser.APPROVE_OPTION) {
String path = fc.getSelectedFile().getPath();
// Create file
fstreamBins = new FileWriter(path);
BinFile = new BufferedWriter(fstreamBins);
String titles = "time\t";
for (int i = 0; i < this.numOfBins; i++) {
titles += "Bin" + i + "\t";
}
BinFile.write(titles);
getPrefs().putBoolean("ITDFilter.writeBin2File", writeBin2File);
support.firePropertyChange("writeBin2File", this.writeBin2File, writeBin2File);
this.writeBin2File = writeBin2File;
}
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
} else if (BinFile != null) {
try {
//Close the output stream
BinFile.close();
BinFile = null;
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
public boolean isWriteITD2File() {
return this.writeITD2File;
}
public void setWriteITD2File(boolean writeITD2File) {
getPrefs().putBoolean("ITDFilter.writeITD2File", writeITD2File);
support.firePropertyChange("writeITD2File", this.writeITD2File, writeITD2File);
this.writeITD2File = writeITD2File;
if (writeITD2File == true) {
try {
// Create file
fstream = new FileWriter("ITDoutput.dat");
ITDFile = new BufferedWriter(fstream);
ITDFile.write("time\tITD\tconf\n");
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
} else {
try {
//Close the output stream
ITDFile.close();
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
if (writeITD2File == true) {
try {
JFileChooser fc = new JFileChooser();
fc.setDialogType(JFileChooser.SAVE_DIALOG);
int state = fc.showSaveDialog(null);
if (state == JFileChooser.APPROVE_OPTION) {
String path = fc.getSelectedFile().getPath();
// Create file
fstream = new FileWriter(path);
ITDFile = new BufferedWriter(fstream);
ITDFile.write("time\tITD\tconf\n");
getPrefs().putBoolean("ITDFilter.writeITD2File", writeITD2File);
support.firePropertyChange("writeITD2File", this.writeITD2File, writeITD2File);
this.writeITD2File = writeITD2File;
}
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
} else if (ITDFile != null) {
try {
//Close the output stream
ITDFile.close();
ITDFile = null;
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
public boolean isSendITDsToOtherThread() {
return this.sendITDsToOtherThread;
}
public void setSendITDsToOtherThread(boolean sendITDsToOtherThread) {
getPrefs().putBoolean("ITDFilter.sendITDsToOtherThread", sendITDsToOtherThread);
support.firePropertyChange("sendITDsToOtherThread", this.sendITDsToOtherThread, sendITDsToOtherThread);
this.sendITDsToOtherThread = sendITDsToOtherThread;
if (sendITDsToOtherThread == true) {
ITDEventQueue = new ArrayBlockingQueue(this.itdEventQueueSize);
} else {
ITDEventQueue = null;
}
}
public boolean isWrite2FileForEverySpike() {
return this.write2FileForEverySpike;
}
public void setWrite2FileForEverySpike(boolean write2FileForEverySpike) {
getPrefs().putBoolean("ITDFilter.write2FileForEverySpike", write2FileForEverySpike);
support.firePropertyChange("write2FileForEverySpike", this.write2FileForEverySpike, write2FileForEverySpike);
this.write2FileForEverySpike = write2FileForEverySpike;
}
public boolean isNormToConfThresh() {
return this.normToConfThresh;
}
public void setNormToConfThresh(boolean normToConfThresh) {
getPrefs().putBoolean("ITDFilter.normToConfThresh", normToConfThresh);
support.firePropertyChange("normToConfThresh", this.normToConfThresh, normToConfThresh);
this.normToConfThresh = normToConfThresh;
}
public boolean isShowAnnotations() {
return this.showAnnotations;
}
public void setShowAnnotations(boolean showAnnotations) {
getPrefs().putBoolean("ITDFilter.showAnnotations", showAnnotations);
support.firePropertyChange("showAnnotations", this.showAnnotations, showAnnotations);
this.showAnnotations = showAnnotations;
}
public boolean isComputeMeanInLoop() {
return this.useLaterSpikeForWeight;
}
public void setComputeMeanInLoop(boolean computeMeanInLoop) {
getPrefs().putBoolean("ITDFilter.computeMeanInLoop", computeMeanInLoop);
support.firePropertyChange("computeMeanInLoop", this.computeMeanInLoop, computeMeanInLoop);
this.computeMeanInLoop = computeMeanInLoop;
if (!isFilterEnabled()) {
return;
}
if (computeMeanInLoop == true) {
if (myBins == null) {
createBins();
} else {
myBins.setNumLoopMean(numLoopMean);
}
} else {
if (myBins == null) {
createBins();
} else {
myBins.setNumLoopMean(1);
}
}
}
public boolean isUseCalibration() {
return this.useCalibration;
}
public void setUseCalibration(boolean useCalibration) {
getPrefs().putBoolean("ITDFilter.useCalibration", useCalibration);
support.firePropertyChange("useCalibration", this.useCalibration, useCalibration);
this.useCalibration = useCalibration;
createBins();
}
public void doSelectCalibrationFile() {
if (calibrationFilePath == null || calibrationFilePath.isEmpty()) {
calibrationFilePath = System.getProperty("user.dir");
}
JFileChooser chooser = new JFileChooser(calibrationFilePath);
chooser.setDialogTitle("Choose calibration .xml file (created with matlab)");
chooser.setFileFilter(new FileFilter() {
@Override
public boolean accept(File f) {
return f.isDirectory() || f.getName().toLowerCase().endsWith(".xml");
}
@Override
public String getDescription() {
return "Executables";
}
});
chooser.setMultiSelectionEnabled(false);
int retval = chooser.showOpenDialog(getChip().getAeViewer().getFilterFrame());
if (retval == JFileChooser.APPROVE_OPTION) {
File f = chooser.getSelectedFile();
if (f != null && f.isFile()) {
setCalibrationFilePath(f.toString());
log.info("selected xml calibration file " + calibrationFilePath);
setUseCalibration(true);
}
}
}
/**
* @return the calibrationFilePath
*/
public String getCalibrationFilePath() {
return calibrationFilePath;
}
/**
* @param calibrationFilePath the calibrationFilePath to set
*/
public void setCalibrationFilePath(String calibrationFilePath) {
support.firePropertyChange("calibrationFilePath", this.calibrationFilePath, calibrationFilePath);
this.calibrationFilePath = calibrationFilePath;
getPrefs().put("ITDFilter.calibrationFilePath", calibrationFilePath);
}
public EstimationMethod getEstimationMethod() {
return estimationMethod;
}
synchronized public void setEstimationMethod(EstimationMethod estimationMethod) {
support.firePropertyChange("estimationMethod", this.estimationMethod, estimationMethod);
getPrefs().put("ITDfilter.estimationMethod", estimationMethod.toString());
this.estimationMethod = estimationMethod;
}
public AMSprocessingMethod getAmsProcessingMethod() {
return amsProcessingMethod;
}
synchronized public void setAmsProcessingMethod(AMSprocessingMethod amsProcessingMethod) {
support.firePropertyChange("amsProcessingMethod", this.amsProcessingMethod, amsProcessingMethod);
getPrefs().put("ITDfilter.amsProcessingMethod", amsProcessingMethod.toString());
this.amsProcessingMethod = amsProcessingMethod;
this.initFilter();
}
public CochleaAMSEvent.FilterType getUseGanglionCellType() {
return useGanglionCellType;
}
synchronized public void setUseGanglionCellType(CochleaAMSEvent.FilterType useGanglionCellType) {
support.firePropertyChange("useGanglionCellType", this.useGanglionCellType, useGanglionCellType);
getPrefs().put("ITDfilter.useGanglionCellType", useGanglionCellType.toString());
this.useGanglionCellType = useGanglionCellType;
}
public static ITDEvent takeITDEvent() throws InterruptedException {
return (ITDEvent) ITDEventQueue.take();
}
public static ITDEvent pollITDEvent() {
if (ITDEventQueue != null) {
return (ITDEvent) ITDEventQueue.poll();
} else {
return null;
}
}
private void createBins() {
int numLoop;
if (this.computeMeanInLoop == true) {
numLoop = numLoopMean;
} else {
numLoop = 1;
}
if (useCalibration == false) {
//log.info("create Bins with averagingDecay=" + averagingDecay + " and maxITD=" + maxITD + " and numOfBins=" + numOfBins);
myBins = new ITDBins((float) averagingDecay * 1000000, numLoop, maxITD, numOfBins);
} else {
if (calibration == null) {
calibration = new ITDCalibrationGaussians();
calibration.loadCalibrationFile(calibrationFilePath);
support.firePropertyChange("numOfBins", this.numOfBins, calibration.getNumOfBins());
this.numOfBins = calibration.getNumOfBins();
}
//log.info("create Bins with averagingDecay=" + averagingDecay + " and calibration file");
myBins = new ITDBins((float) averagingDecay * 1000000, numLoop, calibration);
}
if (display == true && frame != null) {
frame.binsPanel.updateBins(myBins);
}
}
public void annotate(GLAutoDrawable drawable) {
if (!isFilterEnabled()) {
return;
}
GL gl = drawable.getGL();
gl.glPushMatrix();
final GLUT glut = new GLUT();
gl.glColor3f(1, 1, 1);
gl.glRasterPos3f(0, 0, 0);
if (showAnnotations == true) {
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, String.format("avgITD(us)=%s", fmt.format(avgITD)));
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, String.format(" ITDConfidence=%f", avgITDConfidence));
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, String.format(" ILD=%f", ILD));
if (useLaterSpikeForWeight == true || usePriorSpikeForWeight == true) {
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, String.format(" lastWeight=%f", lastWeight));
}
}
if (display == true && frame != null) {
//frame.setITD(avgITD);
frame.setText(String.format("avgITD(us)=%s ITDConfidence=%f ILD=%f", fmt.format(avgITD), avgITDConfidence, ILD));
}
gl.glPopMatrix();
}
public void annotate(float[][][] frame) {
throw new UnsupportedOperationException("Not supported yet, use openGL rendering.");
}
public void annotate(Graphics2D g) {
throw new UnsupportedOperationException("Not supported yet, use openGL rendering..");
}
}
|
package org.openecard.sal;
import iso.std.iso_iec._24727.tech.schema.ACLList;
import iso.std.iso_iec._24727.tech.schema.ACLListResponse;
import iso.std.iso_iec._24727.tech.schema.ACLModify;
import iso.std.iso_iec._24727.tech.schema.ACLModifyResponse;
import iso.std.iso_iec._24727.tech.schema.AlgorithmInfoType;
import iso.std.iso_iec._24727.tech.schema.AuthorizationServiceActionName;
import iso.std.iso_iec._24727.tech.schema.CardApplicationConnect;
import iso.std.iso_iec._24727.tech.schema.CardApplicationConnectResponse;
import iso.std.iso_iec._24727.tech.schema.CardApplicationCreate;
import iso.std.iso_iec._24727.tech.schema.CardApplicationCreateResponse;
import iso.std.iso_iec._24727.tech.schema.CardApplicationDelete;
import iso.std.iso_iec._24727.tech.schema.CardApplicationDeleteResponse;
import iso.std.iso_iec._24727.tech.schema.CardApplicationDisconnect;
import iso.std.iso_iec._24727.tech.schema.CardApplicationDisconnectResponse;
import iso.std.iso_iec._24727.tech.schema.CardApplicationEndSession;
import iso.std.iso_iec._24727.tech.schema.CardApplicationEndSessionResponse;
import iso.std.iso_iec._24727.tech.schema.CardApplicationList;
import iso.std.iso_iec._24727.tech.schema.CardApplicationListResponse;
import iso.std.iso_iec._24727.tech.schema.CardApplicationListResponse.CardApplicationNameList;
import iso.std.iso_iec._24727.tech.schema.CardApplicationPath;
import iso.std.iso_iec._24727.tech.schema.CardApplicationPathResponse;
import iso.std.iso_iec._24727.tech.schema.CardApplicationPathResponse.CardAppPathResultSet;
import iso.std.iso_iec._24727.tech.schema.CardApplicationPathType;
import iso.std.iso_iec._24727.tech.schema.CardApplicationSelect;
import iso.std.iso_iec._24727.tech.schema.CardApplicationSelectResponse;
import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceActionName;
import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceCreate;
import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceCreateResponse;
import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceDelete;
import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceDeleteResponse;
import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceDescribe;
import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceDescribeResponse;
import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceList;
import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceListResponse;
import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceListResponse.CardApplicationServiceNameList;
import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceLoad;
import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceLoadResponse;
import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceType;
import iso.std.iso_iec._24727.tech.schema.CardApplicationStartSession;
import iso.std.iso_iec._24727.tech.schema.CardApplicationStartSessionResponse;
import iso.std.iso_iec._24727.tech.schema.CardApplicationType;
import iso.std.iso_iec._24727.tech.schema.ChannelHandleType;
import iso.std.iso_iec._24727.tech.schema.Connect;
import iso.std.iso_iec._24727.tech.schema.ConnectResponse;
import iso.std.iso_iec._24727.tech.schema.ConnectionHandleType;
import iso.std.iso_iec._24727.tech.schema.ConnectionServiceActionName;
import iso.std.iso_iec._24727.tech.schema.CreateSession;
import iso.std.iso_iec._24727.tech.schema.CreateSessionResponse;
import iso.std.iso_iec._24727.tech.schema.DIDAuthenticate;
import iso.std.iso_iec._24727.tech.schema.DIDAuthenticateResponse;
import iso.std.iso_iec._24727.tech.schema.DIDAuthenticationDataType;
import iso.std.iso_iec._24727.tech.schema.DIDCreate;
import iso.std.iso_iec._24727.tech.schema.DIDCreateResponse;
import iso.std.iso_iec._24727.tech.schema.DIDDelete;
import iso.std.iso_iec._24727.tech.schema.DIDDeleteResponse;
import iso.std.iso_iec._24727.tech.schema.DIDGet;
import iso.std.iso_iec._24727.tech.schema.DIDGetResponse;
import iso.std.iso_iec._24727.tech.schema.DIDInfoType;
import iso.std.iso_iec._24727.tech.schema.DIDList;
import iso.std.iso_iec._24727.tech.schema.DIDListResponse;
import iso.std.iso_iec._24727.tech.schema.DIDNameListType;
import iso.std.iso_iec._24727.tech.schema.DIDQualifierType;
import iso.std.iso_iec._24727.tech.schema.DIDScopeType;
import iso.std.iso_iec._24727.tech.schema.DIDStructureType;
import iso.std.iso_iec._24727.tech.schema.DIDUpdate;
import iso.std.iso_iec._24727.tech.schema.DIDUpdateDataType;
import iso.std.iso_iec._24727.tech.schema.DIDUpdateResponse;
import iso.std.iso_iec._24727.tech.schema.DSICreate;
import iso.std.iso_iec._24727.tech.schema.DSICreateResponse;
import iso.std.iso_iec._24727.tech.schema.DSIDelete;
import iso.std.iso_iec._24727.tech.schema.DSIDeleteResponse;
import iso.std.iso_iec._24727.tech.schema.DSIList;
import iso.std.iso_iec._24727.tech.schema.DSIListResponse;
import iso.std.iso_iec._24727.tech.schema.DSINameListType;
import iso.std.iso_iec._24727.tech.schema.DSIRead;
import iso.std.iso_iec._24727.tech.schema.DSIReadResponse;
import iso.std.iso_iec._24727.tech.schema.DSIType;
import iso.std.iso_iec._24727.tech.schema.DSIWrite;
import iso.std.iso_iec._24727.tech.schema.DSIWriteResponse;
import iso.std.iso_iec._24727.tech.schema.DataSetCreate;
import iso.std.iso_iec._24727.tech.schema.DataSetCreateResponse;
import iso.std.iso_iec._24727.tech.schema.DataSetDelete;
import iso.std.iso_iec._24727.tech.schema.DataSetDeleteResponse;
import iso.std.iso_iec._24727.tech.schema.DataSetInfoType;
import iso.std.iso_iec._24727.tech.schema.DataSetList;
import iso.std.iso_iec._24727.tech.schema.DataSetListResponse;
import iso.std.iso_iec._24727.tech.schema.DataSetNameListType;
import iso.std.iso_iec._24727.tech.schema.DataSetSelect;
import iso.std.iso_iec._24727.tech.schema.DataSetSelectResponse;
import iso.std.iso_iec._24727.tech.schema.Decipher;
import iso.std.iso_iec._24727.tech.schema.DecipherResponse;
import iso.std.iso_iec._24727.tech.schema.DestroySession;
import iso.std.iso_iec._24727.tech.schema.DestroySessionResponse;
import iso.std.iso_iec._24727.tech.schema.DifferentialIdentityServiceActionName;
import iso.std.iso_iec._24727.tech.schema.Disconnect;
import iso.std.iso_iec._24727.tech.schema.DisconnectResponse;
import iso.std.iso_iec._24727.tech.schema.EmptyResponseDataType;
import iso.std.iso_iec._24727.tech.schema.Encipher;
import iso.std.iso_iec._24727.tech.schema.EncipherResponse;
import iso.std.iso_iec._24727.tech.schema.ExecuteAction;
import iso.std.iso_iec._24727.tech.schema.ExecuteActionResponse;
import iso.std.iso_iec._24727.tech.schema.GetRandom;
import iso.std.iso_iec._24727.tech.schema.GetRandomResponse;
import iso.std.iso_iec._24727.tech.schema.Hash;
import iso.std.iso_iec._24727.tech.schema.HashResponse;
import iso.std.iso_iec._24727.tech.schema.Initialize;
import iso.std.iso_iec._24727.tech.schema.InitializeResponse;
import iso.std.iso_iec._24727.tech.schema.NamedDataServiceActionName;
import iso.std.iso_iec._24727.tech.schema.PathType;
import iso.std.iso_iec._24727.tech.schema.PathType.TagRef;
import iso.std.iso_iec._24727.tech.schema.Sign;
import iso.std.iso_iec._24727.tech.schema.SignResponse;
import iso.std.iso_iec._24727.tech.schema.TargetNameType;
import iso.std.iso_iec._24727.tech.schema.Terminate;
import iso.std.iso_iec._24727.tech.schema.TerminateResponse;
import iso.std.iso_iec._24727.tech.schema.VerifyCertificate;
import iso.std.iso_iec._24727.tech.schema.VerifyCertificateResponse;
import iso.std.iso_iec._24727.tech.schema.VerifySignature;
import iso.std.iso_iec._24727.tech.schema.VerifySignatureResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.openecard.addon.AddonManager;
import org.openecard.addon.AddonNotFoundException;
import org.openecard.addon.AddonSelector;
import org.openecard.addon.HighestVersionSelector;
import org.openecard.addon.manifest.AddonSpecification;
import org.openecard.addon.manifest.ProtocolPluginSpecification;
import org.openecard.addon.sal.FunctionType;
import org.openecard.addon.sal.SALProtocol;
import org.openecard.common.ECardConstants;
import org.openecard.common.ECardException;
import org.openecard.common.ThreadTerminateException;
import org.openecard.common.WSHelper;
import org.openecard.common.apdu.DeleteFile;
import org.openecard.common.apdu.EraseBinary;
import org.openecard.common.apdu.EraseRecord;
import org.openecard.common.apdu.GetData;
import org.openecard.common.apdu.GetResponse;
import org.openecard.common.apdu.ReadBinary;
import org.openecard.common.apdu.ReadRecord;
import org.openecard.common.apdu.Select;
import org.openecard.common.apdu.UpdateBinary;
import org.openecard.common.apdu.UpdateRecord;
import org.openecard.common.apdu.WriteBinary;
import org.openecard.common.apdu.WriteRecord;
import org.openecard.common.apdu.common.CardCommandAPDU;
import org.openecard.common.apdu.common.CardResponseAPDU;
import org.openecard.common.apdu.common.TrailerConstants;
import org.openecard.common.apdu.utils.CardUtils;
import org.openecard.common.interfaces.Environment;
import org.openecard.common.interfaces.InvocationTargetExceptionUnchecked;
import org.openecard.common.interfaces.Publish;
import org.openecard.common.sal.Assert;
import org.openecard.common.sal.exception.InappropriateProtocolForActionException;
import org.openecard.common.sal.exception.IncorrectParameterException;
import org.openecard.common.sal.exception.NameExistsException;
import org.openecard.common.sal.exception.NamedEntityNotFoundException;
import org.openecard.common.sal.exception.PrerequisitesNotSatisfiedException;
import org.openecard.common.sal.exception.SecurityConditionNotSatisfiedException;
import org.openecard.common.sal.exception.UnknownConnectionHandleException;
import org.openecard.common.sal.exception.UnknownProtocolException;
import org.openecard.common.sal.state.CardEntry;
import org.openecard.common.sal.state.ConnectedCardEntry;
import org.openecard.common.sal.state.NoSuchSession;
import org.openecard.common.sal.state.SalStateManager;
import org.openecard.common.sal.state.SessionAlreadyExists;
import org.openecard.common.sal.state.StateEntry;
import org.openecard.common.sal.state.cif.CardApplicationWrapper;
import org.openecard.common.sal.state.cif.CardInfoWrapper;
import org.openecard.common.sal.util.SALUtils;
import org.openecard.common.tlv.TLV;
import org.openecard.common.tlv.TLVException;
import org.openecard.common.tlv.iso7816.DataElements;
import org.openecard.common.tlv.iso7816.FCP;
import org.openecard.common.util.ByteUtils;
import org.openecard.crypto.common.sal.did.CryptoMarkerType;
import org.openecard.gui.UserConsent;
import org.openecard.ws.SAL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TinySAL implements SAL {
private static final Logger LOG = LoggerFactory.getLogger(TinySAL.class);
private static final byte[] MF = new byte[] {(byte) 0x3F, (byte) 0x00};
private final Environment env;
private final SalStateManager salStates;
// private final CardStateMap states = null; // TODO: replace with SalStateManager
private byte[] ifdCtx;
private AddonManager addonManager;
private AddonSelector protocolSelector;
private UserConsent userConsent;
private SalEventManager evtMan;
/**
* Creates a new TinySAL.
*
* @param env Environment
*/
public TinySAL(Environment env) {
this.env = env;
this.salStates = new SalStateManager();
}
public void setAddonManager(AddonManager manager) {
this.addonManager = manager;
protocolSelector = new AddonSelector(manager);
protocolSelector.setStrategy(new HighestVersionSelector());
// TODO: check if returnSALProtocol must be called when the entry is removed.
// states.setProtocolSelector(protocolSelector);
}
@Override
public Set<String> supportedProtocols() {
TreeSet<String> protos = new TreeSet<>();
for (AddonSpecification aSpec : addonManager.getRegistry().listAddons()) {
for (ProtocolPluginSpecification pSpec : aSpec.getSalActions()) {
protos.add(pSpec.getUri());
}
}
return protos;
}
public void setIfdCtx(byte[] ctx) {
this.ifdCtx = ByteUtils.clone(ctx);
}
/**
* The Initialize function is executed when the ISO24727-3-Interface is invoked for the first time.
* The interface is initialised with this function.
* See BSI-TR-03112-4, version 1.1.2, section 3.1.1.
*
* @param request Initialize
* @return InitializeResponse
*/
@Override
public InitializeResponse initialize(Initialize request) {
evtMan = new SalEventManager(salStates, env, ifdCtx);
InitializeResponse res = WSHelper.makeResponse(InitializeResponse.class, WSHelper.makeResultOK());
evtMan.initialize();
return res;
}
/**
* The Terminate function is executed when the ISO24727-3-Interface is terminated.
* This function closes all established connections and open sessions.
* See BSI-TR-03112-4, version 1.1.2, section 3.1.2.
*
* @param request Terminate
* @return TerminateResponse
*/
@Override
public TerminateResponse terminate(Terminate request) {
if (evtMan != null) {
evtMan.terminate();
}
TerminateResponse res = WSHelper.makeResponse(TerminateResponse.class, WSHelper.makeResultOK());
return res;
}
@Override
public CreateSessionResponse createSession(CreateSession parameters) {
CreateSessionResponse response = new CreateSessionResponse();
if (parameters == null || parameters.getSessionIdentifier() == null) {
StateEntry entry = this.salStates.createSession(this.ifdCtx);
response.setConnectionHandle(entry.copyHandle());
response.setResult(WSHelper.makeResultOK());
} else {
try {
StateEntry entry = this.salStates.createSession(parameters.getSessionIdentifier(), this.ifdCtx);
response.setConnectionHandle(entry.copyHandle());
response.setResult(WSHelper.makeResultOK());
} catch (SessionAlreadyExists ex) {
// TODO: Add minor error code and message
response.setResult(WSHelper.makeResultError("DUPLICATE_SESSION_IDENTIFIER", "The given session identifier is not unique."));
}
}
return response;
}
@Override
public DestroySessionResponse destroySession(DestroySession parameters) {
byte[] contextHandle = null;
if (parameters != null) {
ConnectionHandleType connectionHandle = parameters.getConnectionHandle();
if (connectionHandle != null) {
contextHandle = connectionHandle.getContextHandle();
}
}
DestroySessionResponse response = new DestroySessionResponse();
boolean didRemoveSession = this.salStates.destroySessionByContextHandle(contextHandle);
if (didRemoveSession) {
response.setResult(WSHelper.makeResultOK());
} else {
response.setResult(WSHelper.makeResultError("NO_SESSION_MATCHED_GIVEN_CONTEXT_HANDLE_HANDLE", "No session was found for the given context handle."));
}
return response;
}
/**
* The CardApplicationPath function determines a path between the client application and a card application.
* See BSI-TR-03112-4, version 1.1.2, section 3.1.3.
*
* @param request CardApplicationPath
* @return CardApplicationPathResponse
*/
@Override
public CardApplicationPathResponse cardApplicationPath(CardApplicationPath request) {
CardApplicationPathResponse response = WSHelper.makeResponse(CardApplicationPathResponse.class,
WSHelper.makeResultOK());
try {
CardApplicationPathType cardAppPath = request.getCardAppPathRequest();
Assert.assertIncorrectParameter(cardAppPath, "The parameter CardAppPathRequest is empty.");
ChannelHandleType reqChannelHandle = cardAppPath.getChannelHandle();
boolean hasSessionIdentifier = reqChannelHandle.getSessionIdentifier() != null;
// Set<CardStateEntry> entries = states.getMatchingEntries(cardAppPath);
List<CardEntry> entries = SALUtils.filterEntries(cardAppPath, salStates.listCardEntries());
// Copy entries to result set
CardAppPathResultSet resultSet = new CardAppPathResultSet();
List<CardApplicationPathType> resultPaths = resultSet.getCardApplicationPathResult();
for (CardEntry entry : entries) {
CardApplicationPathType pathCopy = entry.copyHandle();
final byte[] cardApplication = cardAppPath.getCardApplication();
if (cardApplication != null) {
pathCopy.setCardApplication(cardApplication);
} else {
final byte[] implicitApplication = entry.getCif().getImplicitlySelectedApplication();
if (implicitApplication != null) {
pathCopy.setCardApplication(implicitApplication);
} else {
LOG.warn("No CardApplication and ImplicitlySelectedApplication available using MF now.");
pathCopy.setCardApplication(MF);
}
}
if (hasSessionIdentifier) {
ChannelHandleType copyChannelHandle = pathCopy.getChannelHandle();
if (copyChannelHandle == null) {
copyChannelHandle = new ChannelHandleType();
pathCopy.setChannelHandle(copyChannelHandle);
}
copyChannelHandle.setSessionIdentifier(reqChannelHandle.getSessionIdentifier());
}
resultPaths.add(pathCopy);
}
response.setCardAppPathResultSet(resultSet);
} catch (IncorrectParameterException e) {
response.setResult(e.getResult());
}
return response;
}
/**
* The CardApplicationConnect function establishes an unauthenticated connection between the client
* application and the card application.
* See BSI-TR-03112-4, version 1.1.2, section 3.2.1.
*
* @param request CardApplicationConnect
* @return CardApplicationConnectResponse
*/
@Override
public CardApplicationConnectResponse cardApplicationConnect(CardApplicationConnect request) {
CardApplicationConnectResponse response = WSHelper.makeResponse(CardApplicationConnectResponse.class,
WSHelper.makeResultOK());
try {
Assert.assertIncorrectParameter(request, "The parameter CardApplicationConnect is empty.");
CardApplicationPathType cardAppPath = request.getCardApplicationPath();
Assert.assertIncorrectParameter(cardAppPath, "The parameter CardAppPathRequest is empty.");
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
/*
* [TR-03112-4] If the provided path fragments are valid for more than one card application
* the eCard-API-Framework SHALL return any of the possible choices.
*/
// CardStateEntry cardStateEntry = cardStateEntrySet.iterator().next();
CardEntry baseCardStateEntry = SALUtils.getMatchingEntry(cardAppPath, salStates);
Assert.assertIncorrectParameter(baseCardStateEntry, "The given ConnectionHandle is invalid.");
byte[] applicationID = cardAppPath.getCardApplication();
if (applicationID == null) {
byte[] implicitlySelectedApplication = baseCardStateEntry.getCif().getImplicitlySelectedApplication();
if (implicitlySelectedApplication != null) {
applicationID = implicitlySelectedApplication;
} else {
applicationID = MF;
}
}
Assert.securityConditionApplication(baseCardStateEntry.getCif(), new HashSet<>(), applicationID,
ConnectionServiceActionName.CARD_APPLICATION_CONNECT);
// Connect to the card
// ConnectionHandleType handle = cardStateEntry.handleCopy();
// cardStateEntry = cardStateEntry.derive(handle);
ConnectionHandleType handle = baseCardStateEntry.copyHandle();
Connect connect = new Connect();
connect.setContextHandle(handle.getContextHandle());
connect.setIFDName(handle.getIFDName());
connect.setSlot(handle.getSlotIndex());
ConnectResponse connectResponse = (ConnectResponse) env.getDispatcher().safeDeliver(connect);
WSHelper.checkResult(connectResponse);
// Select the card application
CardCommandAPDU select;
final byte[] slotHandle = connectResponse.getSlotHandle();
// TODO: proper determination of path, file and app id
if (applicationID.length == 2) {
select = new Select.File(applicationID);
List<byte[]> responses = new ArrayList<>();
responses.add(TrailerConstants.Success.OK());
responses.add(TrailerConstants.Error.WRONG_P1_P2());
CardResponseAPDU resp = select.transmit(env.getDispatcher(), slotHandle, responses);
if (Arrays.equals(resp.getTrailer(), TrailerConstants.Error.WRONG_P1_P2())) {
select = new Select.AbsolutePath(applicationID);
select.transmit(env.getDispatcher(), slotHandle);
}
} else {
select = new Select.Application(applicationID);
select.transmit(env.getDispatcher(), slotHandle);
}
ConnectedCardEntry connectedCardEntry = stateEntry.setConnectedCard(slotHandle, applicationID, baseCardStateEntry);
// reset the ef FCP
connectedCardEntry.unsetFCPOfSelectedEF();
salStates.addCard(connectedCardEntry);
response.setConnectionHandle(stateEntry.copyHandle());
response.getConnectionHandle().setCardApplication(applicationID);
} catch (ECardException e) {
response.setResult(e.getResult());
}
return response;
}
@Override
public CardApplicationSelectResponse cardApplicationSelect(CardApplicationSelect request) {
CardApplicationSelectResponse response = WSHelper.makeResponse(CardApplicationSelectResponse.class,
WSHelper.makeResultOK());
try {
byte[] slotHandle = request.getSlotHandle();
// CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle);
StateEntry stateEntry = salStates.getSessionBySlotHandle(slotHandle);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
byte[] reqApplicationID = request.getCardApplication();
Assert.assertIncorrectParameter(reqApplicationID, "The parameter CardApplication is empty.");
CardInfoWrapper cardInfoWrapper = cardStateEntry.getCif();
CardApplicationWrapper appInfo = cardInfoWrapper.getCardApplication(reqApplicationID);
Assert.assertNamedEntityNotFound(appInfo, "The given Application cannot be found.");
Assert.securityConditionApplication(cardInfoWrapper, cardStateEntry.getAuthenticatedDIDs(),
reqApplicationID, ConnectionServiceActionName.CARD_APPLICATION_CONNECT);
// check if the currently selected application is already what the caller wants
byte[] curApplicationID = cardStateEntry.getCurrentCardApplication().getApplicationIdentifier();
if (! ByteUtils.compare(reqApplicationID, curApplicationID)) {
// Select the card application
CardCommandAPDU select;
// TODO: proper determination of path, file and app id
if (reqApplicationID.length == 2) {
select = new Select.File(reqApplicationID);
List<byte[]> responses = new ArrayList<>();
responses.add(TrailerConstants.Success.OK());
responses.add(TrailerConstants.Error.WRONG_P1_P2());
CardResponseAPDU resp = select.transmit(env.getDispatcher(), slotHandle, responses);
if (Arrays.equals(resp.getTrailer(), TrailerConstants.Error.WRONG_P1_P2())) {
select = new Select.AbsolutePath(reqApplicationID);
select.transmit(env.getDispatcher(), slotHandle);
}
} else {
select = new Select.Application(reqApplicationID);
select.transmit(env.getDispatcher(), slotHandle);
}
cardStateEntry.setCurrentCardApplication(reqApplicationID);
// reset the ef FCP
cardStateEntry.unsetFCPOfSelectedEF();
}
response.setConnectionHandle(stateEntry.copyHandle());
} catch (ECardException e) {
response.setResult(e.getResult());
}
return response;
}
/**
* The CardApplicationDisconnect function terminates the connection to a card application.
* See BSI-TR-03112-4, version 1.1.2, section 3.2.2.
*
* @param request CardApplicationDisconnect
* @return CardApplicationDisconnectResponse
*/
@Override
public CardApplicationDisconnectResponse cardApplicationDisconnect(CardApplicationDisconnect request) {
CardApplicationDisconnectResponse response = WSHelper.makeResponse(CardApplicationDisconnectResponse.class,
WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
byte[] slotHandle = connectionHandle.getSlotHandle();
// check existence of required parameters
if (slotHandle == null) {
return WSHelper.makeResponse(CardApplicationDisconnectResponse.class,
WSHelper.makeResultError(ECardConstants.Minor.App.INCORRECT_PARM, "ConnectionHandle is null"));
}
StateEntry stateEntry = salStates.getSessionBySlotHandle(slotHandle);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
Disconnect disconnect = new Disconnect();
disconnect.setSlotHandle(slotHandle);
if (request.getAction() != null) {
disconnect.setAction(request.getAction());
}
stateEntry.removeCard();
// remove entries associated with this handle
DisconnectResponse disconnectResponse = (DisconnectResponse) env.getDispatcher().safeDeliver(disconnect);
response.setResult(disconnectResponse.getResult());
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
/**
* This CardApplicationStartSession function starts a session between the client application and the card application.
* See BSI-TR-03112-4, version 1.1.2, section 3.2.3.
*
* @param request CardApplicationStartSession
* @return CardApplicationStartSessionResponse
*/
@Publish
@Override
public CardApplicationStartSessionResponse cardApplicationStartSession(CardApplicationStartSession request) {
CardApplicationStartSessionResponse response = WSHelper.makeResponse(CardApplicationStartSessionResponse.class,
WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
// CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(request, connectionHandle);
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
Assert.assertIncorrectParameter(cardStateEntry,
"The parameter session identifier did not identify a session with a connected card.");
byte[] cardApplicationID = connectionHandle.getCardApplication();
String didName = SALUtils.getDIDName(request);
Assert.assertIncorrectParameter(didName, "The parameter didName is empty.");
DIDAuthenticationDataType didAuthenticationProtocolData = request.getAuthenticationProtocolData();
Assert.assertIncorrectParameter(didAuthenticationProtocolData,
"The parameter didAuthenticationProtocolData is empty.");
DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, cardApplicationID);
Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found.");
Assert.securityConditionApplication(cardStateEntry.getCif(), cardStateEntry.getAuthenticatedDIDs(),
cardApplicationID, ConnectionServiceActionName.CARD_APPLICATION_START_SESSION);
String protocolURI = didStructure.getDIDMarker().getProtocol();
SALProtocol protocol = getProtocol(connectionHandle, request.getDIDScope(), protocolURI);
if (protocol.hasNextStep(FunctionType.CardApplicationStartSession)) {
response = protocol.cardApplicationStartSession(request);
removeFinishedProtocol(connectionHandle, protocolURI, protocol);
} else {
throw new InappropriateProtocolForActionException("CardApplicationStartSession", protocol.toString());
}
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
/**
* The CardApplicationEndSession function closes the session between the client application and the card application.
* See BSI-TR-03112-4, version 1.1.2, section 3.2.4.
*
* @param request CardApplicationEndSession
* @return CardApplicationEndSessionResponse
*/
@Publish
@Override
public CardApplicationEndSessionResponse cardApplicationEndSession(CardApplicationEndSession request) {
CardApplicationEndSessionResponse response = WSHelper.makeResponse(CardApplicationEndSessionResponse.class,
WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
// CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle);
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
byte[] cardApplicationID = connectionHandle.getCardApplication();
String didName = SALUtils.getDIDName(request);
DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, cardApplicationID);
Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found.");
Assert.securityConditionApplication(cardStateEntry.getCif(), cardStateEntry.getAuthenticatedDIDs(),
cardApplicationID, ConnectionServiceActionName.CARD_APPLICATION_END_SESSION);
String protocolURI = didStructure.getDIDMarker().getProtocol();
SALProtocol protocol = getProtocol(connectionHandle, null, protocolURI);
if (protocol.hasNextStep(FunctionType.CardApplicationEndSession)) {
response = protocol.cardApplicationEndSession(request);
removeFinishedProtocol(connectionHandle, protocolURI, protocol);
} else {
throw new InappropriateProtocolForActionException("CardApplicationEndSession", protocol.toString());
}
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
/**
* The CardApplicationList function returns a list of the available card applications on an eCard.
* See BSI-TR-03112-4, version 1.1.2, section 3.3.1.
*
* @param request CardApplicationList
* @return CardApplicationListResponse
*/
@Publish
@Override
public CardApplicationListResponse cardApplicationList(CardApplicationList request) {
CardApplicationListResponse response = WSHelper.makeResponse(CardApplicationListResponse.class,
WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
// CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false);
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
/*
TR-03112-4 section 3.3.2 states that the alpha application have to be connected with
CardApplicationConnect.
In case of using CardInfo file descriptions this is not necessary because we just work on a file.
*/
// byte[] cardApplicationID = connectionHandle.getCardApplication();
// Assert.securityConditionApplication(cardStateEntry, cardApplicationID,
// CardApplicationServiceActionName.CARD_APPLICATION_LIST);
CardInfoWrapper cardInfoWrapper = cardStateEntry.getCif();
CardApplicationNameList cardApplicationNameList = new CardApplicationNameList();
cardApplicationNameList.getCardApplicationName().addAll(cardInfoWrapper.getCardApplicationNameList());
response.setCardApplicationNameList(cardApplicationNameList);
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
@Override
public CardApplicationCreateResponse cardApplicationCreate(CardApplicationCreate request) {
return WSHelper.makeResponse(CardApplicationCreateResponse.class,
WSHelper.makeResultUnknownError("Not supported yet."));
}
/**
* The CardApplicationDelete function deletes a card application as well as all corresponding
* data sets, DSIs, DIDs and services.
* See BSI-TR-03112-4, version 1.1.2, section 3.3.3.
*
* @param request CardApplicationDelete
* @return CardApplicationDeleteResponse
*/
@Override
public CardApplicationDeleteResponse cardApplicationDelete(CardApplicationDelete request) {
CardApplicationDeleteResponse response = WSHelper.makeResponse(CardApplicationDeleteResponse.class,
WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
// CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false);
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
byte[] cardApplicationName = request.getCardApplicationName();
Assert.assertIncorrectParameter(cardApplicationName, "The parameter CardApplicationName is empty.");
Assert.securityConditionApplication(cardStateEntry.getCif(), cardStateEntry.getAuthenticatedDIDs(),
connectionHandle.getCardApplication(), CardApplicationServiceActionName.CARD_APPLICATION_DELETE);
// TODO: determine how the deletion have to be performed. A card don't have to support the Deletion by
// application identifier. Necessary attributes should be available in the ATR or EF.ATR.
DeleteFile delFile = new DeleteFile.Application(cardApplicationName);
delFile.transmit(env.getDispatcher(), connectionHandle.getSlotHandle());
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
/**
* The CardApplicationServiceList function returns a list of all available services of a card application.
* See BSI-TR-03112-4, version 1.1.2, section 3.3.4.
*
* @param request CardApplicationServiceList
* @return CardApplicationServiceListResponse
*/
@Publish
@Override
public CardApplicationServiceListResponse cardApplicationServiceList(CardApplicationServiceList request) {
CardApplicationServiceListResponse response = WSHelper.makeResponse(CardApplicationServiceListResponse.class,
WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
// CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle);
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
byte[] cardApplicationID = connectionHandle.getCardApplication();
Assert.securityConditionApplication(cardStateEntry.getCif(), cardStateEntry.getAuthenticatedDIDs(), cardApplicationID,
CardApplicationServiceActionName.CARD_APPLICATION_SERVICE_LIST);
CardApplicationServiceNameList cardApplicationServiceNameList = new CardApplicationServiceNameList();
CardInfoWrapper cardInfoWrapper = cardStateEntry.getCif();
Iterator<CardApplicationType> it = cardInfoWrapper.getApplicationCapabilities().getCardApplication().iterator();
while (it.hasNext()) {
CardApplicationType next = it.next();
byte[] appName = next.getApplicationIdentifier();
if (Arrays.equals(appName, cardApplicationID)) {
Iterator<CardApplicationServiceType> itt = next.getCardApplicationServiceInfo().iterator();
while (itt.hasNext()) {
CardApplicationServiceType nextt = itt.next();
cardApplicationServiceNameList.getCardApplicationServiceName().add(nextt.getCardApplicationServiceName());
}
}
}
response.setCardApplicationServiceNameList(cardApplicationServiceNameList);
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
/**
* The CardApplicationServiceCreate function creates a new service in the card application.
* See BSI-TR-03112-4, version 1.1.2, section 3.3.5.
*
* @param request CardApplicationServiceCreate
* @return CardApplicationServiceCreateResponse
*/
@Override
public CardApplicationServiceCreateResponse cardApplicationServiceCreate(CardApplicationServiceCreate request) {
return WSHelper.makeResponse(CardApplicationServiceCreateResponse.class,
WSHelper.makeResultUnknownError("Not supported yet."));
}
/**
* Code for a specific card application service was loaded into the card application with the aid
* of the CardApplicationServiceLoad function.
* See BSI-TR-03112-4, version 1.1.2, section 3.3.6.
*
* @param request CardApplicationServiceLoad
* @return CardApplicationServiceLoadResponse
*/
@Override
public CardApplicationServiceLoadResponse cardApplicationServiceLoad(CardApplicationServiceLoad request) {
return WSHelper.makeResponse(CardApplicationServiceLoadResponse.class,
WSHelper.makeResultUnknownError("Not supported yet."));
}
/**
* The CardApplicationServiceDelete function deletes a card application service in a card application.
* See BSI-TR-03112-4, version 1.1.2, section 3.3.7.
*
* @param request CardApplicationServiceDelete
* @return CardApplicationServiceDeleteResponse
*/
@Override
public CardApplicationServiceDeleteResponse cardApplicationServiceDelete(CardApplicationServiceDelete request) {
return WSHelper.makeResponse(CardApplicationServiceDeleteResponse.class,
WSHelper.makeResultUnknownError("Not supported yet."));
}
/**
* The CardApplicationServiceDescribe function can be used to request an URI, an URL or a detailed description
* of the selected card application service.
* See BSI-TR-03112-4, version 1.1.2, section 3.3.8.
*
* @param request CardApplicationServiceDescribe
* @return CardApplicationServiceDescribeResponse
*/
@Publish
@Override
public CardApplicationServiceDescribeResponse cardApplicationServiceDescribe(CardApplicationServiceDescribe request) {
CardApplicationServiceDescribeResponse response =
WSHelper.makeResponse(CardApplicationServiceDescribeResponse.class, WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
// CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle);
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
byte[] cardApplicationID = connectionHandle.getCardApplication();
String cardApplicationServiceName = request.getCardApplicationServiceName();
Assert.assertIncorrectParameter(cardApplicationServiceName,
"The parameter CardApplicationServiceName is empty.");
Assert.securityConditionApplication(cardStateEntry.getCif(), cardStateEntry.getAuthenticatedDIDs(), cardApplicationID,
CardApplicationServiceActionName.CARD_APPLICATION_SERVICE_DESCRIBE);
CardInfoWrapper cardInfoWrapper = cardStateEntry.getCif();
Iterator<CardApplicationType> it = cardInfoWrapper.getApplicationCapabilities().getCardApplication().iterator();
while (it.hasNext()) {
CardApplicationType next = it.next();
byte[] appName = next.getApplicationIdentifier();
if (Arrays.equals(appName, cardApplicationID)){
Iterator<CardApplicationServiceType> itt = next.getCardApplicationServiceInfo().iterator();
while (itt.hasNext()) {
CardApplicationServiceType nextt = itt.next();
if (nextt.getCardApplicationServiceName().equals(cardApplicationServiceName)) {
response.setServiceDescription(nextt.getCardApplicationServiceDescription());
return response;
}
}
}
}
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
/**
* The ExecuteAction function permits use of additional card application services by the client application
* which are not explicitly specified in [ISO24727-3] but which can be implemented by the eCard with additional code.
* See BSI-TR-03112-4, version 1.1.2, section 3.3.9.
*
* @param request ExecuteAction
* @return ExecuteActionResponse
*/
@Override
public ExecuteActionResponse executeAction(ExecuteAction request) {
return WSHelper.makeResponse(ExecuteActionResponse.class, WSHelper.makeResultUnknownError("Not supported yet."));
}
/**
* The DataSetList function returns the list of the data sets in the card application addressed with the
* ConnectionHandle.
* See BSI-TR-03112-4, version 1.1.2, section 3.4.1.
*
* @param request DataSetList
* @return DataSetListResponse
*/
@Publish
@Override
public DataSetListResponse dataSetList(DataSetList request) {
DataSetListResponse response = WSHelper.makeResponse(DataSetListResponse.class, WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
// CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false);
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
byte[] cardApplicationID = connectionHandle.getCardApplication();
Assert.securityConditionApplication(cardStateEntry.getCif(), cardStateEntry.getAuthenticatedDIDs(), cardApplicationID,
NamedDataServiceActionName.DATA_SET_LIST);
CardInfoWrapper cardInfoWrapper = cardStateEntry.getCif();
DataSetNameListType dataSetNameList = cardInfoWrapper.getDataSetNameList(cardApplicationID);
response.setDataSetNameList(dataSetNameList);
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
/**
* The DataSetCreate function creates a new data set in the card application addressed with the
* ConnectionHandle (or otherwise in a previously selected data set if this is implemented as a DF).
* See BSI-TR-03112-4, version 1.1.2, section 3.4.2.
*
* @param request DataSetCreate
* @return DataSetCreateResponse
*/
@Override
public DataSetCreateResponse dataSetCreate(DataSetCreate request) {
return WSHelper.makeResponse(DataSetCreateResponse.class, WSHelper.makeResultUnknownError("Not supported yet."));
}
/**
* The DataSetSelect function selects a data set in a card application.
* See BSI-TR-03112-4, version 1.1.2, section 3.4.3.
*
* @param request DataSetSelect
* @return DataSetSelectResponse
*/
@Publish
@Override
public DataSetSelectResponse dataSetSelect(DataSetSelect request) {
DataSetSelectResponse response = WSHelper.makeResponse(DataSetSelectResponse.class, WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
// CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle);
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
byte[] applicationID = connectionHandle.getCardApplication();
String dataSetName = request.getDataSetName();
Assert.assertIncorrectParameter(dataSetName, "The parameter DataSetName is empty.");
CardInfoWrapper cardInfoWrapper = cardStateEntry.getCif();
DataSetInfoType dataSetInfo = cardInfoWrapper.getDataSet(dataSetName, applicationID);
Assert.assertNamedEntityNotFound(dataSetInfo, "The given DataSet cannot be found.");
Assert.securityConditionDataSet(cardStateEntry, applicationID, dataSetName,
NamedDataServiceActionName.DATA_SET_SELECT);
byte[] fileID = dataSetInfo.getDataSetPath().getEfIdOrPath();
byte[] slotHandle = connectionHandle.getSlotHandle();
CardResponseAPDU result = CardUtils.selectFileWithOptions(env.getDispatcher(), slotHandle, fileID,
null, CardUtils.FCP_RESPONSE_DATA);
FCP fcp = null;
if (result != null && result.getData().length > 0) {
try {
fcp = new FCP(result.getData());
} catch (TLVException ex) {
LOG.warn("Invalid FCP received.");
}
}
if (fcp == null) {
LOG.info("Using fake FCP.");
fcp = new FCP(createFakeFCP(Arrays.copyOfRange(fileID, fileID.length - 2, fileID.length)));
}
cardStateEntry.setFCPOfSelectedEF(fcp);
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
/**
* The DataSetDelete function deletes a data set of a card application on an eCard.
* See BSI-TR-03112-4, version 1.1.2, section 3.4.4.
*
* @param request DataSetDelete
* @return DataSetDeleteResponse
*/
@Override
public DataSetDeleteResponse dataSetDelete(DataSetDelete request) {
DataSetDeleteResponse response = WSHelper.makeResponse(DataSetDeleteResponse.class, WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
// CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle);
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
byte[] cardApplicationID = connectionHandle.getCardApplication();
CardInfoWrapper cardInfoWrapper = cardStateEntry.getCif();
String dataSetName = request.getDataSetName();
Assert.assertIncorrectParameter(dataSetName, "The parameter DataSetName is empty.");
Assert.securityConditionDataSet(cardStateEntry, cardApplicationID, dataSetName,
NamedDataServiceActionName.DATA_SET_DELETE);
DataSetInfoType dataSet = cardInfoWrapper.getDataSet(dataSetName, cardApplicationID);
if (dataSet == null) {
throw new NamedEntityNotFoundException("The data set " + dataSetName + " does not exist.");
}
byte[] path = dataSet.getDataSetPath().getEfIdOrPath();
int len = path.length;
byte[] fid = new byte[] {path[len - 2], path[len - 1]};
DeleteFile delFile = new DeleteFile.ChildFile(fid);
delFile.transmit(env.getDispatcher(), connectionHandle.getSlotHandle());
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
/**
* The function DSIList supplies the list of the DSI (Data Structure for Interoperability) which exist in the
* selected data set.
* See BSI-TR-03112-4, version 1.1.2, section 3.4.5. <br>
* <br>
* Prerequisites: <br>
* - a connection to a card application has been established <br>
* - a data set has been selected <br>
*
* @param request DSIList
* @return DSIListResponse
*/
@Publish
@Override
public DSIListResponse dsiList(DSIList request) {
DSIListResponse response = WSHelper.makeResponse(DSIListResponse.class, WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
// CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false);
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
CardInfoWrapper cardInfoWrapper = cardStateEntry.getCif();
byte[] cardApplicationID = connectionHandle.getCardApplication();
if (cardStateEntry.getFCPOfSelectedEF() == null) {
throw new PrerequisitesNotSatisfiedException("No EF selected.");
}
DataSetInfoType dataSet = cardInfoWrapper.getDataSetByFid(
cardStateEntry.getFCPOfSelectedEF().getFileIdentifiers().get(0));
Assert.securityConditionDataSet(cardStateEntry, cardApplicationID, dataSet.getDataSetName(),
NamedDataServiceActionName.DSI_LIST);
DSINameListType dsiNameList = new DSINameListType();
for (DSIType dsi : dataSet.getDSI()) {
dsiNameList.getDSIName().add(dsi.getDSIName());
}
response.setDSINameList(dsiNameList);
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
/**
* The DSICreate function creates a DSI (Data Structure for Interoperability) in the currently selected data set.
* See BSI-TR-03112-4, version 1.1.2, section 3.4.6.
* <br>
* <br>
* Preconditions: <br>
* - Connection to a card application established via CardApplicationConnect <br>
* - A data set has been selected with DataSetSelect <br>
* - The DSI does not exist in the data set. <br>
*
* @param request DSICreate
* @return DSICreateResponse
*/
@Override
public DSICreateResponse dsiCreate(DSICreate request) {
DSICreateResponse response = WSHelper.makeResponse(DSICreateResponse.class, WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
// CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle);
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
CardInfoWrapper cardInfoWrapper = cardStateEntry.getCif();
byte[] cardApplicationID = connectionHandle.getCardApplication();
byte[] dsiContent = request.getDSIContent();
Assert.assertIncorrectParameter(dsiContent, "The parameter DSIContent is empty.");
String dsiName = request.getDSIName();
Assert.assertIncorrectParameter(dsiName, "The parameter DSIName is empty.");
DSIType dsi = cardInfoWrapper.getDSIbyName(dsiName);
if (dsi != null) {
throw new NameExistsException("There is already an DSI with the name " + dsiName + " in the current EF.");
}
byte[] slotHandle = connectionHandle.getSlotHandle();
if (cardStateEntry.getFCPOfSelectedEF() == null) {
throw new PrerequisitesNotSatisfiedException("No data set for writing selected.");
} else {
DataSetInfoType dataSet = cardInfoWrapper.getDataSetByFid(
cardStateEntry.getFCPOfSelectedEF().getFileIdentifiers().get(0));
Assert.securityConditionDataSet(cardStateEntry, cardApplicationID, dataSet.getDataSetName(),
NamedDataServiceActionName.DSI_CREATE);
DataElements dElements = cardStateEntry.getFCPOfSelectedEF().getDataElements();
if (dElements.isTransparent()) {
WriteBinary writeBin = new WriteBinary(WriteBinary.INS_WRITE_BINARY_DATA, (byte) 0x00, (byte) 0x00,
dsiContent);
writeBin.transmit(env.getDispatcher(), slotHandle);
} else if (dElements.isCyclic()) {
WriteRecord writeRec = new WriteRecord((byte) 0x00, WriteRecord.WRITE_PREVIOUS, dsiContent);
writeRec.transmit(env.getDispatcher(), slotHandle);
} else {
WriteRecord writeRec = new WriteRecord((byte) 0x00, WriteRecord.WRITE_LAST, dsiContent);
writeRec.transmit(env.getDispatcher(), slotHandle);
}
}
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
/**
* The DSIDelete function deletes a DSI (Data Structure for Interoperability) in the currently selected data set.
* See BSI-TR-03112-4, version 1.1.2, section 3.4.7.
*
* @param request DSIDelete
* @return DSIDeleteResponse
*/
//TODO: rewiew function and add @Publish annotation
@Override
public DSIDeleteResponse dsiDelete(DSIDelete request) {
DSIDeleteResponse response = WSHelper.makeResponse(DSIDeleteResponse.class, WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
// CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle);
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
CardInfoWrapper cardInfoWrapper = cardStateEntry.getCif();
String dsiName = request.getDSIName();
Assert.assertIncorrectParameter(dsiName, "The parameter DSIName is empty.");
if (cardStateEntry.getFCPOfSelectedEF() == null) {
String msg = "No DataSet selected for deleting the DSI " + request.getDSIName();
throw new PrerequisitesNotSatisfiedException(msg);
}
DataSetInfoType dataSet = cardInfoWrapper.getDataSetByDsiName(request.getDSIName());
byte[] fidOrPath = dataSet.getDataSetPath().getEfIdOrPath();
byte[] dataSetFid = new byte[] {fidOrPath[fidOrPath.length - 2], fidOrPath[fidOrPath.length - 1]};
if (! Arrays.equals(dataSetFid, cardStateEntry.getFCPOfSelectedEF().getFileIdentifiers().get(0))) {
String msg = "The wrong DataSet for the deletion of DSI " + request.getDSIName() + " is selected.";
throw new PrerequisitesNotSatisfiedException(msg);
}
DataSetInfoType dSet =
cardInfoWrapper.getDataSetByFid(cardStateEntry.getFCPOfSelectedEF().getFileIdentifiers().get(0));
Assert.securityConditionDataSet(cardStateEntry, connectionHandle.getCardApplication(), dSet.getDataSetName(),
NamedDataServiceActionName.DSI_DELETE);
DSIType dsi = cardInfoWrapper.getDSIbyName(dsiName);
// We have to define some allowed answers because if the file has an write operation counter we wont get an
// 9000 response.
ArrayList<byte[]> responses = new ArrayList<byte[]>() {
{
add(new byte[] {(byte) 0x90, (byte) 0x00});
add(new byte[] {(byte) 0x63, (byte) 0xC1});
add(new byte[] {(byte) 0x63, (byte) 0xC2});
add(new byte[] {(byte) 0x63, (byte) 0xC3});
add(new byte[] {(byte) 0x63, (byte) 0xC4});
add(new byte[] {(byte) 0x63, (byte) 0xC5});
add(new byte[] {(byte) 0x63, (byte) 0xC6});
add(new byte[] {(byte) 0x63, (byte) 0xC7});
add(new byte[] {(byte) 0x63, (byte) 0xC8});
add(new byte[] {(byte) 0x63, (byte) 0xC9});
add(new byte[] {(byte) 0x63, (byte) 0xCA});
add(new byte[] {(byte) 0x63, (byte) 0xCB});
add(new byte[] {(byte) 0x63, (byte) 0xCC});
add(new byte[] {(byte) 0x63, (byte) 0xCD});
add(new byte[] {(byte) 0x63, (byte) 0xCE});
add(new byte[] {(byte) 0x63, (byte) 0xCF});
}
};
if (cardStateEntry.getFCPOfSelectedEF().getDataElements().isLinear()) {
EraseRecord rmRecord = new EraseRecord(dsi.getDSIPath().getIndex()[0], EraseRecord.ERASE_JUST_P1);
rmRecord.transmit(env.getDispatcher(), connectionHandle.getSlotHandle(), responses);
} else {
// NOTE: Erase binary allows to erase only everything after the offset or everything in front of the offset.
// currently erasing everything after the offset is used.
EraseBinary rmBinary = new EraseBinary((byte) 0x00, (byte) 0x00, dsi.getDSIPath().getIndex());
rmBinary.transmit(env.getDispatcher(), connectionHandle.getSlotHandle(), responses);
}
} catch (ECardException e) {
LOG.error(e.getMessage(), e);
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
/**
* The DSIWrite function changes the content of a DSI (Data Structure for Interoperability).
* See BSI-TR-03112-4, version 1.1.2, section 3.4.8.
* For clarification this method updates an existing DSI and does not create a new one.
*
* The precondition for this method is that a connection to a card application was established and a data set was
* selected. Furthermore the DSI exists already.
*
* @param request DSIWrite
* @return DSIWriteResponse
*/
@Publish
@Override
public DSIWriteResponse dsiWrite(DSIWrite request) {
DSIWriteResponse response = WSHelper.makeResponse(DSIWriteResponse.class, WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
// CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle);
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
byte[] applicationID = connectionHandle.getCardApplication();
String dsiName = request.getDSIName();
byte[] updateData = request.getDSIContent();
Assert.assertIncorrectParameter(dsiName, "The parameter DSIName is empty.");
Assert.assertIncorrectParameter(updateData, "The parameter DSIContent is empty.");
CardInfoWrapper cardInfoWrapper = cardStateEntry.getCif();
DataSetInfoType dataSetInfo = cardInfoWrapper.getDataSetByDsiName(dsiName);
DSIType dsi = cardInfoWrapper.getDSIbyName(dsiName);
Assert.assertNamedEntityNotFound(dataSetInfo, "The given DSIName cannot be found.");
Assert.securityConditionDataSet(cardStateEntry, applicationID, dsiName, NamedDataServiceActionName.DSI_WRITE);
if (cardStateEntry.getFCPOfSelectedEF() == null) {
throw new PrerequisitesNotSatisfiedException("No EF with DSI selected.");
}
if (! Arrays.equals(dataSetInfo.getDataSetPath().getEfIdOrPath(),
cardStateEntry.getFCPOfSelectedEF().getFileIdentifiers().get(0))) {
String msg = "The currently selected data set does not contain the DSI to be updated.";
throw new PrerequisitesNotSatisfiedException(msg);
}
byte[] slotHandle = connectionHandle.getSlotHandle();
if (cardStateEntry.getFCPOfSelectedEF().getDataElements().isTransparent()) {
// currently assuming that the index encodes the offset
byte[] index = dsi.getDSIPath().getIndex();
UpdateBinary updateBin = new UpdateBinary(index[0], index[1], updateData);
updateBin.transmit(env.getDispatcher(), slotHandle);
} else {
// currently assuming that the index encodes the record number
byte index = dsi.getDSIPath().getIndex()[0];
UpdateRecord updateRec = new UpdateRecord(index, updateData);
updateRec.transmit(env.getDispatcher(), slotHandle);
}
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
/**
* The DSIRead function reads out the content of a specific DSI (Data Structure for Interoperability).
* See BSI-TR-03112-4, version 1.1.2, section 3.4.9.
*
* @param request DSIRead
* @return DSIReadResponse
*/
@Publish
@Override
public DSIReadResponse dsiRead(DSIRead request) {
DSIReadResponse response = WSHelper.makeResponse(DSIReadResponse.class, WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
// CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle);
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
byte[] applicationID = cardStateEntry.getCurrentCardApplication().getApplicationIdentifier();
String dsiName = request.getDSIName();
byte[] slotHandle = connectionHandle.getSlotHandle();
Assert.assertIncorrectParameter(dsiName, "The parameter DSIName is empty.");
Assert.securityConditionDataSet(cardStateEntry, applicationID, dsiName, NamedDataServiceActionName.DSI_READ);
if (cardStateEntry.getFCPOfSelectedEF() == null) {
throw new PrerequisitesNotSatisfiedException("No DataSet to read selected.");
}
CardInfoWrapper cardInfoWrapper = cardStateEntry.getCif();
DataSetInfoType dataSetInfo = cardInfoWrapper.getDataSetByDsiName(dsiName);
if (dataSetInfo == null) {
// there is no data set which contains the given dsi name so the name should be an data set name
dataSetInfo = cardInfoWrapper.getDataSetByName(dsiName);
if (dataSetInfo != null) {
if (!cardStateEntry.getFCPOfSelectedEF().getFileIdentifiers().isEmpty()) {
byte[] path = dataSetInfo.getDataSetPath().getEfIdOrPath();
byte[] fid = Arrays.copyOfRange(path, path.length - 2, path.length);
if (!Arrays.equals(fid, cardStateEntry.getFCPOfSelectedEF().getFileIdentifiers().get(0))) {
String msg = "Wrong DataSet for reading the DSI " + dsiName + " is selected.";
throw new PrerequisitesNotSatisfiedException(msg);
}
}
byte[] fileContent = CardUtils.readFile(cardStateEntry.getFCPOfSelectedEF(), env.getDispatcher(),
slotHandle);
response.setDSIContent(fileContent);
} else {
String msg = "The given DSIName does not related to any know DSI or DataSet.";
throw new IncorrectParameterException(msg);
}
} else {
// There exists a data set with the given dsi name
// check whether the correct file is selected
byte[] dataSetPath = dataSetInfo.getDataSetPath().getEfIdOrPath();
byte[] dataSetFID = new byte[] {dataSetPath[dataSetPath.length - 2], dataSetPath[dataSetPath.length - 1]};
if (Arrays.equals(dataSetFID, cardStateEntry.getFCPOfSelectedEF().getFileIdentifiers().get(0))) {
DSIType dsi = cardInfoWrapper.getDSIbyName(dsiName);
PathType dsiPath = dsi.getDSIPath();
if (dsiPath.getTagRef() != null) {
TagRef tagReference = dsiPath.getTagRef();
byte[] tag = tagReference.getTag();
GetData getDataRequest;
if (tag.length == 2) {
getDataRequest = new GetData(GetData.INS_DATA, tag[0], tag[1]);
CardResponseAPDU cardResponse = getDataRequest.transmit(env.getDispatcher(), slotHandle,
Collections.EMPTY_LIST);
byte[] responseData = cardResponse.getData();
while (cardResponse.getTrailer()[0] == (byte) 0x61) {
GetResponse allData = new GetResponse();
cardResponse = allData.transmit(env.getDispatcher(), slotHandle, Collections.EMPTY_LIST);
responseData = ByteUtils.concatenate(responseData, cardResponse.getData());
}
response.setDSIContent(responseData);
} else if (tag.length == 1) {
// how to determine Simple- or BER-TLV in this case correctly?
// Now try Simple-TLV first and if it fail try BER-TLV
getDataRequest = new GetData(GetData.INS_DATA, GetData.SIMPLE_TLV, tag[0]);
CardResponseAPDU cardResponse = getDataRequest.transmit(env.getDispatcher(), slotHandle,
Collections.EMPTY_LIST);
byte[] responseData = cardResponse.getData();
// just an assumption
if (Arrays.equals(cardResponse.getTrailer(), new byte[] {(byte) 0x6A, (byte) 0x88})) {
getDataRequest = new GetData(GetData.INS_DATA, GetData.BER_TLV_ONE_BYTE, tag[0]);
cardResponse = getDataRequest.transmit(env.getDispatcher(), slotHandle,
Collections.EMPTY_LIST);
responseData = cardResponse.getData();
}
while (cardResponse.getTrailer()[0] == (byte) 0x61) {
GetResponse allData = new GetResponse();
cardResponse = allData.transmit(env.getDispatcher(), slotHandle, Collections.EMPTY_LIST);
responseData = ByteUtils.concatenate(responseData, cardResponse.getData());
}
response.setDSIContent(responseData);
}
} else if (dsiPath.getIndex() != null) {
byte[] index = dsiPath.getIndex();
byte[] length = dsiPath.getLength();
List<byte[]> allowedResponse = new ArrayList<>();
allowedResponse.add(new byte[]{(byte) 0x90, (byte) 0x00});
allowedResponse.add(new byte[]{(byte) 0x62, (byte) 0x82});
if (cardStateEntry.getFCPOfSelectedEF().getDataElements().isLinear()) {
// in this case we use the index as record number and the length as length of record
ReadRecord readRecord = new ReadRecord(index[0]);
// NOTE: For record based files TR-0312-4 states to ignore the length field in case of records
CardResponseAPDU cardResponse = readRecord.transmit(env.getDispatcher(), slotHandle,
allowedResponse);
response.setDSIContent(cardResponse.getData());
} else {
// in this case we use index as offset and length as the expected length
ReadBinary readBinary = new ReadBinary(ByteUtils.toShort(index), ByteUtils.toShort(length));
CardResponseAPDU cardResponse = readBinary.transmit(env.getDispatcher(), slotHandle,
allowedResponse);
response.setDSIContent(cardResponse.getData());
}
} else {
String msg = "The currently selected data set does not contain the DSI with the name " + dsiName;
throw new PrerequisitesNotSatisfiedException(msg);
}
}
}
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
/**
* The Encipher function encrypts a transmitted plain text. The detailed behaviour of this function depends on
* the protocol of the DID.
* See BSI-TR-03112-4, version 1.1.2, section 3.5.1.
*
* @param request Encipher
* @return EncipherResponse
*/
@Publish
@Override
public EncipherResponse encipher(Encipher request) {
EncipherResponse response = WSHelper.makeResponse(EncipherResponse.class, WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
// CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false);
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
byte[] applicationID = cardStateEntry.getCurrentCardApplication().getApplicationIdentifier();
String didName = SALUtils.getDIDName(request);
byte[] plainText = request.getPlainText();
Assert.assertIncorrectParameter(plainText, "The parameter PlainText is empty.");
DIDScopeType didScope = request.getDIDScope();
if (didScope == null) {
didScope = DIDScopeType.LOCAL;
}
if (didScope.equals(DIDScopeType.LOCAL)) {
byte[] necessaryCardApp = cardStateEntry.getCif().getApplicationIdByDidName(didName, didScope);
if (! Arrays.equals(necessaryCardApp, applicationID)) {
throw new SecurityConditionNotSatisfiedException("Wrong application selected.");
}
}
DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, didScope);
Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found.");
String protocolURI = didStructure.getDIDMarker().getProtocol();
SALProtocol protocol = getProtocol(connectionHandle, request.getDIDScope(), protocolURI);
if (protocol.hasNextStep(FunctionType.Encipher)) {
response = protocol.encipher(request);
removeFinishedProtocol(connectionHandle, protocolURI, protocol);
} else {
throw new InappropriateProtocolForActionException("Encipher", protocol.toString());
}
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
/**
* The Decipher function decrypts a given cipher text. The detailed behaviour of this function depends on
* the protocol of the DID.
* See BSI-TR-03112-4, version 1.1.2, section 3.5.2.
*
* @param request Decipher
* @return DecipherResponse
*/
@Override
public DecipherResponse decipher(Decipher request) {
DecipherResponse response = WSHelper.makeResponse(DecipherResponse.class, WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
// CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false);
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
byte[] applicationID = cardStateEntry.getCurrentCardApplication().getApplicationIdentifier();
String didName = SALUtils.getDIDName(request);
byte[] cipherText = request.getCipherText();
Assert.assertIncorrectParameter(cipherText, "The parameter CipherText is empty.");
DIDScopeType didScope = request.getDIDScope();
if (didScope == null) {
didScope = DIDScopeType.LOCAL;
}
if (didScope.equals(DIDScopeType.LOCAL)) {
byte[] necessaryCardApp = cardStateEntry.getCif().getApplicationIdByDidName(didName, didScope);
if (! Arrays.equals(necessaryCardApp, applicationID)) {
throw new SecurityConditionNotSatisfiedException("Wrong application selected.");
}
}
DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, didScope);
Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found.");
String protocolURI = didStructure.getDIDMarker().getProtocol();
SALProtocol protocol = getProtocol(connectionHandle, request.getDIDScope(), protocolURI);
if (protocol.hasNextStep(FunctionType.Decipher)) {
response = protocol.decipher(request);
removeFinishedProtocol(connectionHandle, protocolURI, protocol);
} else {
throw new InappropriateProtocolForActionException("Decipher", protocol.toString());
}
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
/**
* The GetRandom function returns a random number which is suitable for authentication with the DID addressed with
* DIDName.
* See BSI-TR-03112-4, version 1.1.2, section 3.5.3.
*
* @param request GetRandom
* @return GetRandomResponse
*/
@Publish
@Override
public GetRandomResponse getRandom(GetRandom request) {
GetRandomResponse response = WSHelper.makeResponse(GetRandomResponse.class, WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
// CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false);
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
byte[] applicationID = cardStateEntry.getCurrentCardApplication().getApplicationIdentifier();
String didName = SALUtils.getDIDName(request);
DIDScopeType didScope = request.getDIDScope();
if (didScope == null) {
didScope = DIDScopeType.LOCAL;
}
if (didScope.equals(DIDScopeType.LOCAL)) {
byte[] necessaryApp = cardStateEntry.getCif().getApplicationIdByDidName(didName, didScope);
if (! Arrays.equals(necessaryApp, applicationID)) {
throw new SecurityConditionNotSatisfiedException("The wrong application is selected for getRandom()");
}
}
DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, didScope);
Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found.");
String protocolURI = didStructure.getDIDMarker().getProtocol();
SALProtocol protocol = getProtocol(connectionHandle, request.getDIDScope(), protocolURI);
if (protocol.hasNextStep(FunctionType.GetRandom)) {
response = protocol.getRandom(request);
removeFinishedProtocol(connectionHandle, protocolURI, protocol);
} else {
throw new InappropriateProtocolForActionException("GetRandom", protocol.toString());
}
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
/**
* The Hash function calculates the hash value of a transmitted message.
* See BSI-TR-03112-4, version 1.1.2, section 3.5.4.
*
* @param request Hash
* @return HashResponse
*/
@Publish
@Override
public HashResponse hash(Hash request) {
HashResponse response = WSHelper.makeResponse(HashResponse.class, WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
// CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false);
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
byte[] applicationID = cardStateEntry.getCurrentCardApplication().getApplicationIdentifier();
String didName = SALUtils.getDIDName(request);
byte[] message = request.getMessage();
Assert.assertIncorrectParameter(message, "The parameter Message is empty.");
DIDScopeType didScope = request.getDIDScope();
if (didScope == null) {
didScope = DIDScopeType.LOCAL;
}
if (didScope.equals(DIDScopeType.LOCAL)) {
byte[] necesssaryApp = cardStateEntry.getCif().getApplicationIdByDidName(didName, didScope);
if (! Arrays.equals(necesssaryApp, applicationID)) {
String msg = "Wrong application for executing Hash with the specified DID " + didName + ".";
throw new SecurityConditionNotSatisfiedException(msg);
}
}
DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, didScope);
Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found.");
String protocolURI = didStructure.getDIDMarker().getProtocol();
SALProtocol protocol = getProtocol(connectionHandle, request.getDIDScope(), protocolURI);
if (protocol.hasNextStep(FunctionType.Hash)) {
response = protocol.hash(request);
removeFinishedProtocol(connectionHandle, protocolURI, protocol);
} else {
throw new InappropriateProtocolForActionException("Hash", protocol.toString());
}
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
/**
* The Sign function signs a transmitted message.
* See BSI-TR-03112-4, version 1.1.2, section 3.5.5.
*
* @param request Sign
* @return SignResponse
*/
@Override
public SignResponse sign(Sign request) {
SignResponse response = WSHelper.makeResponse(SignResponse.class, WSHelper.makeResultOK());
ConnectedCardEntry cardStateEntry = null;
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
// cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false);
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
cardStateEntry = stateEntry.getCardEntry();
byte[] applicationID = cardStateEntry.getCurrentCardApplication().getApplicationIdentifier();
String didName = SALUtils.getDIDName(request);
byte[] message = request.getMessage();
Assert.assertIncorrectParameter(message, "The parameter Message is empty.");
DIDScopeType didScope = request.getDIDScope();
if (didScope == null) {
didScope = DIDScopeType.LOCAL;
}
if (didScope.equals(DIDScopeType.LOCAL)) {
byte[] necessarySelectedApp = cardStateEntry.getCif().getApplicationIdByDidName(didName, didScope);
if (! Arrays.equals(necessarySelectedApp, applicationID)) {
String msg = "Wrong application selected for the execution of Sign with the DID " + didName + ".";
throw new SecurityConditionNotSatisfiedException(msg);
}
}
DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, didScope);
Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found.");
String protocolURI = didStructure.getDIDMarker().getProtocol();
SALProtocol protocol = getProtocol(connectionHandle, request.getDIDScope(), protocolURI);
if (protocol.hasNextStep(FunctionType.Sign)) {
response = protocol.sign(request);
removeFinishedProtocol(connectionHandle, protocolURI, protocol);
} else {
throw new InappropriateProtocolForActionException("Sign", protocol.toString());
}
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
// TODO: remove when PIN state tracking is implemented
setPinNotAuth(cardStateEntry);
return response;
}
/**
* The VerifySignature function verifies a digital signature.
* See BSI-TR-03112-4, version 1.1.2, section 3.5.6.
*
* @param request VerifySignature
* @return VerifySignatureResponse
*/
@Override
public VerifySignatureResponse verifySignature(VerifySignature request) {
VerifySignatureResponse response = WSHelper.makeResponse(VerifySignatureResponse.class, WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
// CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false);
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
byte[] applicationID = cardStateEntry.getCurrentCardApplication().getApplicationIdentifier();
String didName = SALUtils.getDIDName(request);
byte[] signature = request.getSignature();
Assert.assertIncorrectParameter(signature, "The parameter Signature is empty.");
DIDScopeType didScope = request.getDIDScope();
if (didScope == null) {
didScope = DIDScopeType.LOCAL;
}
if (didScope.equals(DIDScopeType.LOCAL)) {
byte[] necessarySelectedApp = cardStateEntry.getCif().getApplicationIdByDidName(didName, didScope);
if (! Arrays.equals(necessarySelectedApp, applicationID)) {
String msg = "Wrong application selected for the execution of VerifySignature with the DID " +
didName + ".";
throw new SecurityConditionNotSatisfiedException(msg);
}
}
DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, didScope);
Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found.");
String protocolURI = didStructure.getDIDMarker().getProtocol();
SALProtocol protocol = getProtocol(connectionHandle, request.getDIDScope(), protocolURI);
if (protocol.hasNextStep(FunctionType.VerifySignature)) {
response = protocol.verifySignature(request);
removeFinishedProtocol(connectionHandle, protocolURI, protocol);
} else {
throw new InappropriateProtocolForActionException("VerifySignature", protocol.toString());
}
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
/**
* The VerifyCertificate function validates a given certificate.
* See BSI-TR-03112-4, version 1.1.2, section 3.5.7.
*
* @param request VerifyCertificate
* @return VerifyCertificateResponse
*/
@Override
public VerifyCertificateResponse verifyCertificate(VerifyCertificate request) {
VerifyCertificateResponse response = WSHelper.makeResponse(VerifyCertificateResponse.class,
WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
// CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false);
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
byte[] applicationID = cardStateEntry.getCurrentCardApplication().getApplicationIdentifier();
String didName = SALUtils.getDIDName(request);
byte[] certificate = request.getCertificate();
Assert.assertIncorrectParameter(certificate, "The parameter Certificate is empty.");
String certificateType = request.getCertificateType();
Assert.assertIncorrectParameter(certificateType, "The parameter CertificateType is empty.");
String rootCert = request.getRootCert();
Assert.assertIncorrectParameter(rootCert, "The parameter RootCert is empty.");
DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, applicationID);
Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found.");
DIDScopeType didScope = request.getDIDScope();
if (didScope == null) {
didScope = DIDScopeType.LOCAL;
}
if (didScope.equals(DIDScopeType.LOCAL)) {
byte[] necessarySelectedApp = cardStateEntry.getCif().getApplicationIdByDidName(didName, didScope);
if (! Arrays.equals(necessarySelectedApp, applicationID)) {
String msg = "Wrong application selected for the execution of VerifyCertificate with the DID " +
didName + ".";
throw new SecurityConditionNotSatisfiedException(msg);
}
}
String protocolURI = didStructure.getDIDMarker().getProtocol();
SALProtocol protocol = getProtocol(connectionHandle, request.getDIDScope(), protocolURI);
if (protocol.hasNextStep(FunctionType.VerifyCertificate)) {
response = protocol.verifyCertificate(request);
removeFinishedProtocol(connectionHandle, protocolURI, protocol);
} else {
throw new InappropriateProtocolForActionException("VerifyCertificate", protocol.toString());
}
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
/**
* The DIDList function returns a list of the existing DIDs in the card application addressed by the
* ConnectionHandle or the ApplicationIdentifier element within the Filter.
* See BSI-TR-03112-4, version 1.1.2, section 3.6.1.
*
* @param request DIDList
* @return DIDListResponse
*/
@Publish
@Override
public DIDListResponse didList(DIDList request) {
DIDListResponse response = WSHelper.makeResponse(DIDListResponse.class, WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
byte[] appId = connectionHandle.getCardApplication();
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
Assert.securityConditionApplication(cardStateEntry.getCif(), cardStateEntry.getAuthenticatedDIDs(), appId,
DifferentialIdentityServiceActionName.DID_LIST);
byte[] applicationIDFilter = null;
String objectIDFilter = null;
String applicationFunctionFilter = null;
DIDQualifierType didQualifier = request.getFilter();
if (didQualifier != null) {
applicationIDFilter = didQualifier.getApplicationIdentifier();
objectIDFilter = didQualifier.getObjectIdentifier();
applicationFunctionFilter = didQualifier.getApplicationFunction();
}
/*
* Filter by ApplicationIdentifier.
* [TR-03112-4] Allows specifying an application identifier. If this element is present all
* DIDs within the specified card application are returned no matter which card application
* is currently selected.
*/
CardApplicationWrapper cardApplication;
if (applicationIDFilter != null) {
cardApplication = cardStateEntry.getCif().getCardApplication(applicationIDFilter);
Assert.assertIncorrectParameter(cardApplication, "The given CardApplication cannot be found.");
} else {
cardApplication = cardStateEntry.getCurrentCardApplication();
}
List<DIDInfoType> didInfos = new ArrayList<>(cardApplication.getDIDInfoList());
/*
* Filter by ObjectIdentifier.
* [TR-03112-4] Allows specifying a protocol OID (cf. [TR-03112-7]) such that only DIDs
* which support a given protocol are listed.
*/
if (objectIDFilter != null) {
Iterator<DIDInfoType> it = didInfos.iterator();
while (it.hasNext()) {
DIDInfoType next = it.next();
if (!next.getDifferentialIdentity().getDIDProtocol().equals(objectIDFilter)) {
it.remove();
}
}
}
/*
* Filter by ApplicationFunction.
* [TR-03112-4] Allows filtering for DIDs, which support a specific cryptographic operation.
* The bit string is coded as the SupportedOperations-element in [ISO7816-15].
*/
if (applicationFunctionFilter != null) {
Iterator<DIDInfoType> it = didInfos.iterator();
while (it.hasNext()) {
DIDInfoType next = it.next();
if (next.getDifferentialIdentity().getDIDMarker().getCryptoMarker() == null) {
it.remove();
} else {
iso.std.iso_iec._24727.tech.schema.CryptoMarkerType rawMarker;
rawMarker = next.getDifferentialIdentity().getDIDMarker().getCryptoMarker();
CryptoMarkerType cryptoMarker = new CryptoMarkerType(rawMarker);
AlgorithmInfoType algInfo = cryptoMarker.getAlgorithmInfo();
if (! algInfo.getSupportedOperations().contains(applicationFunctionFilter)) {
it.remove();
}
}
}
}
DIDNameListType didNameList = new DIDNameListType();
for (DIDInfoType didInfo : didInfos) {
didNameList.getDIDName().add(didInfo.getDifferentialIdentity().getDIDName());
}
response.setDIDNameList(didNameList);
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
/**
* The DIDCreate function creates a new differential identity in the card application addressed with ConnectionHandle.
* See BSI-TR-03112-4, version 1.1.2, section 3.6.2.
*
* @param request DIDCreate
* @return DIDCreateResponse
*/
@Override
public DIDCreateResponse didCreate(DIDCreate request) {
return WSHelper.makeResponse(DIDCreateResponse.class, WSHelper.makeResultUnknownError("Not supported yet."));
}
/**
* The public information for a DID is read with the DIDGet function.
* See BSI-TR-03112-4, version 1.1.2, section 3.6.3.
*
* @param request DIDGet
* @return DIDGetResponse
*/
@Publish
@Override
public DIDGetResponse didGet(DIDGet request) {
DIDGetResponse response = WSHelper.makeResponse(DIDGetResponse.class, WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
// handle must be requested without application, as it is irrelevant for this call
// CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false);
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
String didName = SALUtils.getDIDName(request);
DIDStructureType didStructure = SALUtils.getDIDStructure(request, didName, cardStateEntry, connectionHandle);
response.setDIDStructure(didStructure);
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
/**
* The DIDUpdate function creates a new key (marker) for the DID addressed with DIDName.
* See BSI-TR-03112-4, version 1.1.2, section 3.6.4.
*
* @param request DIDUpdate
* @return DIDUpdateResponse
*/
// TODO: discuss whether we should publish this @Publish
@Override
public DIDUpdateResponse didUpdate(DIDUpdate request) {
DIDUpdateResponse response = WSHelper.makeResponse(DIDUpdateResponse.class, WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
byte[] cardApplicationID = connectionHandle.getCardApplication();
// CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false);
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
String didName = request.getDIDName();
Assert.assertIncorrectParameter(didName, "The parameter DIDName is empty.");
DIDUpdateDataType didUpdateData = request.getDIDUpdateData();
Assert.assertIncorrectParameter(didUpdateData, "The parameter DIDUpdateData is empty.");
DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, cardApplicationID);
Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found.");
Assert.securityConditionDID(cardStateEntry.getCif(), cardStateEntry.getAuthenticatedDIDs(), cardApplicationID,
didName, DifferentialIdentityServiceActionName.DID_UPDATE);
String protocolURI = didStructure.getDIDMarker().getProtocol();
SALProtocol protocol = getProtocol(connectionHandle, null, protocolURI);
if (protocol.hasNextStep(FunctionType.DIDUpdate)) {
response = protocol.didUpdate(request);
removeFinishedProtocol(connectionHandle, protocolURI, protocol);
} else {
throw new InappropriateProtocolForActionException("DIDUpdate", protocol.toString());
}
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
/**
* The DIDDelete function deletes the DID addressed with DIDName.
* See BSI-TR-03112-4, version 1.1.2, section 3.6.5.
*
* @param request DIDDelete
* @return DIDDeleteResponse
*/
@Override
public DIDDeleteResponse didDelete(DIDDelete request) {
DIDDeleteResponse response = WSHelper.makeResponse(DIDDeleteResponse.class, WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
byte[] cardApplicationID = connectionHandle.getCardApplication();
// CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false);
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
String didName = request.getDIDName();
Assert.assertIncorrectParameter(didName, "The parameter DIDName is empty.");
DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, cardApplicationID);
Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found.");
Assert.securityConditionDID(cardStateEntry.getCif(), cardStateEntry.getAuthenticatedDIDs(),
cardApplicationID, didName, DifferentialIdentityServiceActionName.DID_DELETE);
String protocolURI = didStructure.getDIDMarker().getProtocol();
SALProtocol protocol = getProtocol(connectionHandle, null, protocolURI);
if (protocol.hasNextStep(FunctionType.DIDDelete)) {
response = protocol.didDelete(request);
removeFinishedProtocol(connectionHandle, protocolURI, protocol);
} else {
throw new InappropriateProtocolForActionException("DIDDelete", protocol.toString());
}
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
/**
* The DIDAuthenticate function can be used to execute an authentication protocol using a DID addressed by DIDName.
* See BSI-TR-03112-4, version 1.1.2, section 3.6.6.
*
* @param request DIDAuthenticate
* @return DIDAuthenticateResponse
*/
@Publish
@Override
public DIDAuthenticateResponse didAuthenticate(DIDAuthenticate request) {
DIDAuthenticateResponse response = WSHelper.makeResponse(DIDAuthenticateResponse.class, WSHelper.makeResultOK());
String protocolURI = "";
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
DIDAuthenticationDataType didAuthenticationData = request.getAuthenticationProtocolData();
Assert.assertIncorrectParameter(didAuthenticationData, "The parameter AuthenticationProtocolData is empty.");
protocolURI = didAuthenticationData.getProtocol();
// FIXME: workaround for missing protocol URI from eID-Servers
if (protocolURI == null) {
LOG.warn("ProtocolURI was null");
protocolURI = ECardConstants.Protocol.EAC_GENERIC;
} else if (protocolURI.equals("urn:oid:1.0.24727.3.0.0.7.2")) {
LOG.warn("ProtocolURI was urn:oid:1.0.24727.3.0.0.7.2");
protocolURI = ECardConstants.Protocol.EAC_GENERIC;
}
didAuthenticationData.setProtocol(protocolURI);
SALProtocol protocol = getProtocol(connectionHandle, request.getDIDScope(), protocolURI);
if (protocol.hasNextStep(FunctionType.DIDAuthenticate)) {
response = protocol.didAuthenticate(request);
removeFinishedProtocol(connectionHandle, protocolURI, protocol);
} else {
throw new InappropriateProtocolForActionException("DIDAuthenticate", protocol.toString());
}
} catch (ECardException ex) {
LOG.debug("ECard error occurred during DIDAuthenticate execution.", ex);
response.setResult(ex.getResult());
} catch (Exception ex) {
LOG.error("General error occurred during DIDAuthenticate execution.", ex);
throwThreadKillException(ex);
response.setResult(WSHelper.makeResult(ex));
}
// add empty response data if none are present
if (response.getAuthenticationProtocolData() == null) {
EmptyResponseDataType data = new EmptyResponseDataType();
data.setProtocol(protocolURI);
response.setAuthenticationProtocolData(data);
}
return response;
}
/**
* The ACLList function returns the access control list for the stated target object (card application, data set, DID).
* See BSI-TR-03112-4, version 1.1.2, section 3.7.1.
*
* @param request ACLList
* @return ACLListResponse
*/
@Publish
@Override
public ACLListResponse aclList(ACLList request) {
ACLListResponse response = WSHelper.makeResponse(ACLListResponse.class, WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
// CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false);
StateEntry stateEntry = SALUtils.getStateBySession(request, salStates);
ConnectedCardEntry cardStateEntry = stateEntry.getCardEntry();
TargetNameType targetName = request.getTargetName();
Assert.assertIncorrectParameter(targetName, "The parameter TargetName is empty.");
// get the target values, according to the schema only one must exist, we pick the first existing ;-)
byte[] targetAppId = targetName.getCardApplicationName();
String targetDataSet = targetName.getDataSetName();
String targetDid = targetName.getDIDName();
CardInfoWrapper cardInfoWrapper = cardStateEntry.getCif();
byte[] handleAppId = connectionHandle.getCardApplication();
if (targetDataSet != null) {
DataSetInfoType dataSetInfo = cardInfoWrapper.getDataSet(targetDataSet, handleAppId);
Assert.assertNamedEntityNotFound(dataSetInfo, "The given DataSet cannot be found.");
response.setTargetACL(cardInfoWrapper.getDataSet(targetDataSet, handleAppId).getDataSetACL());
} else if (targetDid != null) {
DIDInfoType didInfo = cardInfoWrapper.getDIDInfo(targetDid, handleAppId);
Assert.assertNamedEntityNotFound(didInfo, "The given DIDInfo cannot be found.");
//TODO Check security condition ?
response.setTargetACL(cardInfoWrapper.getDIDInfo(targetDid, handleAppId).getDIDACL());
} else if (targetAppId != null) {
CardApplicationWrapper cardApplication = cardInfoWrapper.getCardApplication(targetAppId);
Assert.assertNamedEntityNotFound(cardApplication, "The given CardApplication cannot be found.");
Assert.securityConditionApplication(cardStateEntry.getCif(), cardStateEntry.getAuthenticatedDIDs(),
targetAppId, AuthorizationServiceActionName.ACL_LIST);
response.setTargetACL(cardInfoWrapper.getCardApplication(targetAppId).getCardApplicationACL());
} else {
throw new IncorrectParameterException("The given TargetName is invalid.");
}
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
/**
* An access rule in the access control list is modified with the ACLModify function.
* See BSI-TR-03112-4, version 1.1.2, section 3.7.2.
*
* @param request ACLModify
* @return ACLModifyResponse
*/
@Override
public ACLModifyResponse aclModify(ACLModify request) {
return WSHelper.makeResponse(ACLModifyResponse.class, WSHelper.makeResultUnknownError("Not supported yet."));
}
/**
* Sets the GUI.
*
* @param uc User consent
*/
public void setGUI(UserConsent uc) {
this.userConsent = uc;
}
/**
* Removes a finished protocol from the SAL instance.
*
* @param handle Connection Handle
* @param protocolURI Protocol URI
* @param protocol Protocol
* @throws UnknownConnectionHandleException
*/
private void removeFinishedProtocol(ConnectionHandleType handle, String protocolURI, SALProtocol protocol)
throws UnknownConnectionHandleException, IncorrectParameterException, NoSuchSession {
if (protocol.isFinished()) {
LOG.debug("SAL Protocol is finished, destroying protocol instance.");
try {
// CardStateEntry entry = SALUtils.getCardStateEntry(states, handle, false);
StateEntry stateEntry = SALUtils.getStateBySession(handle, salStates);
stateEntry.removeProtocol(protocolURI);
} finally {
protocolSelector.returnSALProtocol(protocol, false);
}
}
}
private SALProtocol getProtocol(@Nonnull ConnectionHandleType handle, @Nullable DIDScopeType scope,
@Nonnull String protocolURI) throws UnknownProtocolException, UnknownConnectionHandleException,
IncorrectParameterException, NoSuchSession {
// CardStateEntry entry = SALUtils.getCardStateEntry(states, handle, scope != DIDScopeType.GLOBAL);
StateEntry stateEntry = SALUtils.getStateBySession(handle, salStates);
SALProtocol protocol = stateEntry.getProtocol();
if (protocol == null) {
try {
protocol = protocolSelector.getSALProtocol(protocolURI);
stateEntry.setProtocol(protocol, protocolURI);
} catch (AddonNotFoundException ex) {
throw new UnknownProtocolException("The protocol URI '" + protocolURI + "' is not available.");
}
}
protocol.getInternalData().put("cardState", stateEntry);
return protocol;
}
private byte[] createFakeFCP(byte[] fid) {
try {
TLV fcp = new TLV();
fcp.setTagNumWithClass((byte) 0x62);
TLV fileID = new TLV();
fileID.setTagNumWithClass((byte) 0x83);
fileID.setValue(fid);
fcp.setChild(fileID);
return fcp.toBER();
} catch (TLVException ex) {
LOG.error(null, ex);
return null;
}
}
// TODO: remove function when state tracking is implemented
private void setPinNotAuth(@Nullable ConnectedCardEntry cardStateEntry) {
if (cardStateEntry != null) {
LOG.info("Unauthenticate Card PIN (state=false).");
// This method only works in a a very limited way. All PIN DIDs get status unauth here.
for (DIDInfoType didInfo : Collections.unmodifiableCollection(cardStateEntry.getAuthenticatedDIDs())) {
if ("urn:oid:1.3.162.15480.3.0.9".equals(didInfo.getDifferentialIdentity().getDIDProtocol())) {
cardStateEntry.removeAuthenticated(didInfo);
}
}
}
}
private void throwThreadKillException(Exception ex) {
Throwable cause;
if (ex instanceof InvocationTargetExceptionUnchecked) {
cause = ex.getCause();
} else {
cause = ex;
}
if (cause instanceof ThreadTerminateException) {
throw (ThreadTerminateException) cause;
} else if (cause instanceof InterruptedException) {
throw new ThreadTerminateException("Thread running inside SAL interrupted.", cause);
} else if (cause instanceof RuntimeException) {
throw (RuntimeException) ex;
}
}
}
|
package com.android.phone;
import com.android.internal.telephony.CommandException;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.util.Log;
import android.view.WindowManager;
import java.util.ArrayList;
interface TimeConsumingPreferenceListener {
public void onStarted(Preference preference, boolean reading);
public void onFinished(Preference preference, boolean reading);
public void onError(Preference preference, int error);
public void onException(Preference preference, CommandException exception);
}
public class TimeConsumingPreferenceActivity extends PreferenceActivity
implements TimeConsumingPreferenceListener,
DialogInterface.OnCancelListener {
private static final String LOG_TAG = "TimeConsumingPreferenceActivity";
private final boolean DBG = (PhoneGlobals.DBG_LEVEL >= 2);
private class DismissOnClickListener implements DialogInterface.OnClickListener {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}
private class DismissAndFinishOnClickListener implements DialogInterface.OnClickListener {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
}
private final DialogInterface.OnClickListener mDismiss = new DismissOnClickListener();
private final DialogInterface.OnClickListener mDismissAndFinish
= new DismissAndFinishOnClickListener();
private static final int BUSY_READING_DIALOG = 100;
private static final int BUSY_SAVING_DIALOG = 200;
static final int EXCEPTION_ERROR = 300;
static final int RESPONSE_ERROR = 400;
static final int RADIO_OFF_ERROR = 500;
static final int FDN_CHECK_FAILURE = 600;
private final ArrayList<String> mBusyList = new ArrayList<String>();
protected boolean mIsForeground = false;
@Override
protected Dialog onCreateDialog(int id) {
if (id == BUSY_READING_DIALOG || id == BUSY_SAVING_DIALOG) {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle(getText(R.string.updating_title));
dialog.setIndeterminate(true);
switch(id) {
case BUSY_READING_DIALOG:
dialog.setCancelable(true);
dialog.setOnCancelListener(this);
dialog.setMessage(getText(R.string.reading_settings));
return dialog;
case BUSY_SAVING_DIALOG:
dialog.setCancelable(false);
dialog.setMessage(getText(R.string.updating_settings));
return dialog;
}
return null;
}
if (id == RESPONSE_ERROR || id == RADIO_OFF_ERROR || id == EXCEPTION_ERROR
|| id == FDN_CHECK_FAILURE) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
int msgId;
int titleId = R.string.error_updating_title;
switch (id) {
case RESPONSE_ERROR:
msgId = R.string.response_error;
builder.setPositiveButton(R.string.close_dialog, mDismiss);
break;
case RADIO_OFF_ERROR:
msgId = R.string.radio_off_error;
// The error is not recoverable on dialog exit.
builder.setPositiveButton(R.string.close_dialog, mDismissAndFinish);
break;
case FDN_CHECK_FAILURE:
msgId = R.string.fdn_check_failure;
builder.setPositiveButton(R.string.close_dialog, mDismiss);
break;
case EXCEPTION_ERROR:
default:
msgId = R.string.exception_error;
// The error is not recoverable on dialog exit.
builder.setPositiveButton(R.string.close_dialog, mDismiss);
break;
}
builder.setTitle(getText(titleId));
builder.setMessage(getText(msgId));
builder.setCancelable(false);
AlertDialog dialog = builder.create();
// make the dialog more obvious by blurring the background.
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
return dialog;
}
return null;
}
@Override
public void onResume() {
super.onResume();
mIsForeground = true;
}
@Override
public void onPause() {
super.onPause();
mIsForeground = false;
}
@Override
public void onStarted(Preference preference, boolean reading) {
if (DBG) dumpState();
if (DBG) Log.d(LOG_TAG, "onStarted, preference=" + preference.getKey()
+ ", reading=" + reading);
mBusyList.add(preference.getKey());
if (mIsForeground) {
if (reading) {
showDialog(BUSY_READING_DIALOG);
} else {
showDialog(BUSY_SAVING_DIALOG);
}
}
}
@Override
public void onFinished(Preference preference, boolean reading) {
if (DBG) dumpState();
if (DBG) Log.d(LOG_TAG, "onFinished, preference=" + preference.getKey()
+ ", reading=" + reading);
mBusyList.remove(preference.getKey());
if (mBusyList.isEmpty()) {
if (reading) {
dismissDialogSafely(BUSY_READING_DIALOG);
} else {
dismissDialogSafely(BUSY_SAVING_DIALOG);
}
}
preference.setEnabled(true);
}
@Override
public void onError(Preference preference, int error) {
if (DBG) dumpState();
if (DBG) Log.d(LOG_TAG, "onError, preference=" + preference.getKey() + ", error=" + error);
if (mIsForeground) {
showDialog(error);
}
preference.setEnabled(false);
}
@Override
public void onException(Preference preference, CommandException exception) {
if (exception.getCommandError() == CommandException.Error.FDN_CHECK_FAILURE) {
onError(preference, FDN_CHECK_FAILURE);
} else {
preference.setEnabled(false);
onError(preference, EXCEPTION_ERROR);
}
}
@Override
public void onCancel(DialogInterface dialog) {
if (DBG) dumpState();
finish();
}
private void dismissDialogSafely(int id) {
try {
dismissDialog(id);
} catch (IllegalArgumentException e) {
// This is expected in the case where we were in the background
// at the time we would normally have shown the dialog, so we didn't
// show it.
}
}
/* package */ void dumpState() {
Log.d(LOG_TAG, "dumpState begin");
for (String key : mBusyList) {
Log.d(LOG_TAG, "mBusyList: key=" + key);
}
Log.d(LOG_TAG, "dumpState end");
}
}
|
package com.fluidops.rdb2rdfbench.eval;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openrdf.model.BNode;
import org.openrdf.model.Value;
/**
* Compares to query results (in terms of {@link QueryResultSet}s) according to
* the equivalence metric defined in the paper. Also calculates precision and
* recall and provides helper methods for result debugging.
*
* @author cp
*
*/
public class QueryResultChecker {
private String title;
private SparqlResultSet result;
private QueryResultSet reference;
private QueryMapping qm;
private Map<Integer, Integer> establishedMatches;
private float precision;
private float recall;
private Set<String> categories;
/**
* Constructor. Matches any {@link QueryResultSet} against some reference
* result set.
*
* @param title
* Sets a title of the evaluation (e.g., query name or run
* identifier)
* @param result
* Tested query result set.
* @param reference
* Reference result set.
* @param qm
* Mapping of query columns/variables.
* @param categories
* Category IDs ("group tags") from {@link QueryPair}
* specification.
*/
public QueryResultChecker(String title, SparqlResultSet result,
QueryResultSet reference, QueryMapping qm, Set<String> categories) {
this.title = title;
this.result = result;
this.reference = reference;
this.qm = qm;
this.categories = categories;
if (this.qm == null) {
if (reference.size() > 0)
this.qm = new QueryMapping(reference.get(0).length);
else
this.qm = new QueryMapping(0);
}
establishedMatches = equivalenceTests(this.qm);
if (result.size() == 0)
precision = 0;
else
precision = (float) establishedMatches.size()
/ (float) result.size();
if (reference.size() == 0)
recall = 1;
else
recall = (float) establishedMatches.size()
/ (float) reference.size();
}
/**
* Returns the title of the evaluated {@link QueryPair}.
*
* @return Title.
*/
public String getTitle() {
return title;
}
/**
* Returns all category IDs (group tags) of this report.
*
* @return Categories.
*/
public Set<String> getCategories() {
return categories;
}
private Set<Integer> getLiteralMatchCandidates(
Map<String, Set<Integer>>[] index, String refValue, int varCol) {
if (index[varCol] == null) {
// create column index
index[varCol] = new HashMap<String, Set<Integer>>();
for (int i = 0; i < result.size(); i++) {
// nulls are non-results, no need to compare
if (result.get(i)[varCol] != null) {
String colVal = result.get(i)[varCol].stringValue();
if (index[varCol].containsKey(colVal))
index[varCol].get(colVal).add(i);
else {
Set<Integer> set = new HashSet<Integer>();
set.add(i);
index[varCol].put(colVal, set);
}
}
}
}
if (index[varCol].containsKey(refValue))
return index[varCol].get(refValue);
else
return new HashSet<Integer>();
}
private Set<Integer> intersectCandidates(Set<Integer> matchCandidates,
Set<Integer> literalMatchCandidates) {
Set<Integer> ret = new HashSet<Integer>();
if (literalMatchCandidates == null) {
// add all possible tuples/no restrictions
literalMatchCandidates = new HashSet<Integer>();
for (int i = 0; i < result.size(); i++)
literalMatchCandidates.add(i);
}
for (Integer candi : literalMatchCandidates)
if (matchCandidates == null || matchCandidates.contains(candi))
ret.add(candi);
return ret;
}
private boolean confirmMatch(Value[] tuple1, Value[] tuple2, QueryMapping qm) {
for (Integer col : qm.keySet()) {
Integer matchVar = qm.get(col);
if (tuple1[col] != null && tuple2[matchVar] == null)
return false;
if (tuple1[col] != null
&& !(tuple1[col] instanceof BNode)
&& !tuple1[col].stringValue().equals(
tuple2[matchVar].stringValue()))
return false;
}
return true;
}
private Map<Integer, Integer> equivalenceTests(QueryMapping qm) {
Map<Integer, Integer> ret = new HashMap<Integer, Integer>();
Set<Integer> processedTuples = new HashSet<Integer>();
Set<Integer> processedMatches = new HashSet<Integer>();
if (result.size() == 0 || reference.size() == 0)
return ret;
@SuppressWarnings("unchecked")
Map<String, Set<Integer>>[] perColLiteralIndex = new HashMap[result
.get(0).length];
for (int i = 0; i < reference.size(); i++) {
// already matched?
if (processedTuples.contains(i))
continue;
// building candidate set
Value[] tuple = reference.get(i);
Set<Integer> matchCandidates = null;
Set<Integer> localDependencies = new HashSet<Integer>();
// check each mapped column
for (Integer col : qm.keySet()) {
Integer matchVar = qm.get(col);
if (tuple[col] instanceof BNode) {
// placeholder matching dependencies (resolve later)
localDependencies.addAll(reference
.getDependencies(tuple[col]));
} else {
// literal matching
if (matchCandidates != null && matchCandidates.size() < 10)
continue; // need no more filtering
String refVal = null;
if (tuple[col] != null)
refVal = tuple[col].stringValue();
matchCandidates = intersectCandidates(
matchCandidates,
getLiteralMatchCandidates(perColLiteralIndex,
refVal, matchVar));
}
}
if (matchCandidates.size() == 0) {
processedTuples.add(i);
continue; // no can do
}
for (Integer ci : matchCandidates) {
if (confirmMatch(tuple, result.get(ci), qm)) {
ret.put(i, ci);
processedTuples.add(i);
processedMatches.add(ci);
break;
}
}
// check & resolve cross-dependencies
// TODO: ... really check ...
if (localDependencies.size() > 1)
System.err
.println("warning: ignoring intra-result set dependencies");
}
return ret;
}
/**
* Returns the precision of the result set as compared to the reference
* result set (under query result set equivalence).
*
* @return Precision.
*/
public float getPrecision() {
return precision;
}
/**
* Returns the recall of the result set as compared to the reference result
* set (under query result set equivalence).
*
* @return Recall.
*/
public float getRecall() {
return recall;
}
/**
* Returns the F-measure (F1 measure) of the result set as compared to the
* reference result set (under query result set equivalence).
*
* @return F measure.
*/
public float getFMeasure() {
return 2 * (precision * recall) / (precision + recall);
}
/**
* Builds and returns a standard {@link EvaluationReport}, containing
* precision, recall and F-measure as well as some auxiliary numbers.
*
* @return Evaluation report.
*/
public EvaluationReport getReport() {
return new EvaluationReport(title, precision, recall, getFMeasure(),
categories);
}
/**
* Helper method for result set debugging. Returns the list of correctly
* matched tuples, i.e., tuples in the result set that have a unique
* equivalent tuple in the reference result set.
*
* @return List of correct tuples in result set. Note that URIs/keys have
* been replaced by arbitrary blank nodes in tuple positions where
* ID equivalence matching has been performed.
*/
public List<Value[]> getMatchedTuples() {
List<Value[]> ret = new ArrayList<Value[]>();
for (Integer tupleNum : establishedMatches.keySet())
ret.add(result.get(establishedMatches.get(tupleNum)));
return ret;
}
/**
* Helper method for result set debugging. Returns a list of unmatched
* tuples in the result set, i.e., tuples that are wrong (have no unique
* equivalent in the reference set) and contribute to lowering precision.
*
* @return List of incorrect tuples in result set. Note that URIs/keys have
* been replaced by arbitrary blank nodes in tuple positions where
* ID equivalence matching has been performed.
*/
public List<Value[]> getUnmatchedTuples() {
List<Value[]> ret = new ArrayList<Value[]>();
Collection<Integer> matched = establishedMatches.values();
for (int i = 0; i < result.size(); i++)
if (!matched.contains(i))
ret.add(result.get(i));
return ret;
}
/**
* Helper method for result set debugging. Returns a list of tuples that are
* expected by the reference result but have no equivalent in the actual
* result set. Those tuples contribute to lowering recall.
*
* @return List of reference tuples missing in result set. Note that
* URIs/keys have been replaced by arbitrary blank nodes in tuple
* positions where ID equivalence matching has been performed.
*/
public List<Value[]> getMissingTuples() {
List<Value[]> ret = new ArrayList<Value[]>();
for (int i = 0; i < reference.size(); i++)
if (!establishedMatches.containsKey(i))
ret.add(reference.get(i));
return ret;
}
private List<Float> getLocalPrecisionRecall(boolean isPrecision) {
if (result.size() == 0)
throw new RuntimeException(
"Cannot calculate local precision/recall values "
+ "on empty result set.");
List<Float> ret = new ArrayList<Float>();
for (int i = 0; i < result.get(0).length; i++) {
if (qm.values().contains(i)) {
int var = i;
Integer col = null;
for (Integer c : qm.keySet())
if (qm.get(c) == var) {
col = c;
break;
}
if (col == null) {
ret.add(null);
continue;
}
Map<Integer, Integer> col2Var = new HashMap<Integer, Integer>();
col2Var.put(col, var);
QueryMapping localQm = new QueryMapping(col2Var);
Map<Integer, Integer> localMatches = equivalenceTests(localQm);
if (isPrecision)
ret.add((float) localMatches.size() / (float) result.size());
else
ret.add((float) localMatches.size()
/ (float) reference.size());
}
}
return ret;
}
/**
* Helper method for result set debugging. Calculates a list of local
* per-variable precisions. Variable precision is the precision that would
* result if equality was checked on one particular result variable only
* (rather than on complete tuples). Works on mapped variables only, local
* precisions for all other variables is null.
*
* @return List of local precisions.
*/
public List<Float> getLocalPrecisions() {
return getLocalPrecisionRecall(true);
}
/**
* Helper method for result set debugging. Calculates a list of local
* per-variable recall values. Variable recall is the recall value that
* would result if equality was checked on one particular result variable
* only (rather than on complete tuples). Works on mapped variables only,
* local recall for all other variables is null.
*
* @return List of local recall values.
*/
public List<Float> getLocalRecalls() {
return getLocalPrecisionRecall(false);
}
}
|
package com.group5.android.fd.activity;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnDismissListener;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegrator;
import com.group5.android.fd.FdConfig;
import com.group5.android.fd.Main;
import com.group5.android.fd.R;
import com.group5.android.fd.activity.dialog.Alerts;
import com.group5.android.fd.activity.dialog.QuantityRemoverDialog;
import com.group5.android.fd.adapter.ConfirmAdapter;
import com.group5.android.fd.entity.AbstractEntity;
import com.group5.android.fd.entity.CategoryEntity;
import com.group5.android.fd.entity.ItemEntity;
import com.group5.android.fd.entity.OrderEntity;
import com.group5.android.fd.entity.OrderItemEntity;
import com.group5.android.fd.entity.TableEntity;
import com.group5.android.fd.entity.UserEntity;
import com.group5.android.fd.entity.AbstractEntity.OnUpdatedListener;
import com.group5.android.fd.helper.HttpRequestAsyncTask;
import com.group5.android.fd.helper.ScanHelper;
public class NewSessionActivity extends Activity implements OnDismissListener,
OnClickListener, OnUpdatedListener,
HttpRequestAsyncTask.OnHttpRequestAsyncTaskCaller {
final public static String EXTRA_DATA_NAME_TABLE_OBJ = "tableObj";
final public static String EXTRA_DATA_NAME_USE_SCANNER = "useScanner";
final public static int REQUEST_CODE_TABLE = 1;
final public static int REQUEST_CODE_CATEGORY = 2;
final public static int REQUEST_CODE_ITEM = 3;
final public static int REQUEST_CODE_CONFIRM = 4;
public static final String POST_ORDER_STRING = "Go";
public static final String CHANGE_ORDER_STRING = "Change";
public static final int REMOVE_ITEM_MENU = Menu.FIRST;
public static final String REMOVE_ITEM_MENU_STRING = "Remove";
protected OrderEntity m_order = new OrderEntity();
protected UserEntity m_user = null;
protected boolean m_useScanner = false;
protected HttpRequestAsyncTask m_hrat = null;
// For display confirm View
protected ConfirmAdapter m_confirmAdapter;
protected ListView m_vwListView;
protected Button m_vwConfirm;
protected Button m_vwContinue;
protected TextView m_vwTableName;
protected TextView m_vwTotal;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get intent from Main
Intent intent = getIntent();
m_user = (UserEntity) intent
.getSerializableExtra(Main.INSTANCE_STATE_KEY_USER_OBJ);
m_useScanner = intent.getBooleanExtra(
NewSessionActivity.EXTRA_DATA_NAME_USE_SCANNER, false);
Object tmpObj = intent
.getSerializableExtra(NewSessionActivity.EXTRA_DATA_NAME_TABLE_OBJ);
if (tmpObj != null && tmpObj instanceof TableEntity) {
TableEntity table = (TableEntity) tmpObj;
m_order.setTable(table);
}
boolean isRecovered = false;
Object lastNonConfigurationInstance = getLastNonConfigurationInstance();
if (lastNonConfigurationInstance != null
&& lastNonConfigurationInstance instanceof OrderEntity) {
// found our long lost order, yay!
m_order = (OrderEntity) lastNonConfigurationInstance;
isRecovered = true;
Log.i(FdConfig.DEBUG_TAG, "OrderEntity has been recovered");
}
initLayout();
initListeners();
if (!isRecovered) {
// this method should take care of the table for us
// the additional check is used to prevent the category list to
// display when orientation changes
startCategoryList();
}
}
@Override
public Object onRetainNonConfigurationInstance() {
// we want to preserve our order information when configuration is
// change, say.. orientation change?
return m_order;
}
@Override
protected void onResume() {
super.onResume();
m_order.setOnUpdatedListener(this);
}
@Override
protected void onPause() {
super.onPause();
if (m_hrat != null) {
m_hrat.dismissProgressDialog();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
CategoryEntity pendingCategory = null;
if (resultCode == Activity.RESULT_OK && data != null) {
switch (requestCode) {
case REQUEST_CODE_TABLE:
TableEntity table = (TableEntity) data
.getSerializableExtra(TableListActivity.ACTIVITY_RESULT_NAME_TABLE_OBJ);
m_order.setTable(table);
startCategoryList();
break;
case REQUEST_CODE_CATEGORY:
pendingCategory = (CategoryEntity) data
.getSerializableExtra(CategoryListActivity.ACTIVITY_RESULT_NAME_CATEGORY_OBJ);
startItemList(pendingCategory);
break;
case REQUEST_CODE_ITEM:
OrderItemEntity orderItem = (OrderItemEntity) data
.getSerializableExtra(ItemListActivity.ACTIVITY_RESULT_NAME_ORDER_ITEM_OBJ);
m_order.addOrderItem(orderItem);
startCategoryList();
break;
case IntentIntegrator.REQUEST_CODE:
new ScanHelper(this, requestCode, resultCode, data,
new Class[] { ItemEntity.class }) {
@Override
protected void onMatched(AbstractEntity entity) {
m_order.addItem((ItemEntity) entity);
startCategoryList();
}
@Override
protected void onMismatched(AbstractEntity entity) {
// we don't want ti fallback to onInvalid
// because we want to let user try again :)
startCategoryList();
}
@Override
protected void onInvalid() {
m_useScanner = false;
startCategoryList();
}
};
break;
}
} else if (resultCode == Activity.RESULT_CANCELED) {
// xu ly khi activity bi huy boi back
switch (requestCode) {
case REQUEST_CODE_TABLE:
finish();
break;
case REQUEST_CODE_CATEGORY:
startTableList();
break;
case REQUEST_CODE_ITEM:
startCategoryList();
break;
case IntentIntegrator.REQUEST_CODE:
m_useScanner = false;
break;
}
}
}
protected void startTableList() {
Intent tableIntent = new Intent(this, TableListActivity.class);
startActivityForResult(tableIntent,
NewSessionActivity.REQUEST_CODE_TABLE);
}
protected void startCategoryList() {
if (m_order.getTableId() == 0) {
// before display the category list
// we should have a valid table set
startTableList();
} else if (m_useScanner) {
startScanner();
} else {
Intent categoryIntent = new Intent(this, CategoryListActivity.class);
startActivityForResult(categoryIntent,
NewSessionActivity.REQUEST_CODE_CATEGORY);
}
}
protected void startItemList(CategoryEntity category) {
Intent itemIntent = new Intent(this, ItemListActivity.class);
itemIntent.putExtra(ItemListActivity.EXTRA_DATA_NAME_CATEGORY_ID,
category.categoryId);
startActivityForResult(itemIntent, NewSessionActivity.REQUEST_CODE_ITEM);
}
protected void startScanner() {
IntentIntegrator.initiateScan(this);
}
protected void startConfirmList() {
m_confirmAdapter.notifyDataSetChanged();
m_vwConfirm.setText(NewSessionActivity.POST_ORDER_STRING);
m_vwContinue.setText(NewSessionActivity.CHANGE_ORDER_STRING);
m_vwTableName.setText(m_order.getTableName());
m_vwTotal.setText(String.format("%s", m_order.getPriceTotal()));
}
protected void postOrder() {
m_order.submit(this, m_user.csrfToken);
}
/*
* Cai dat danh cho confirm list Bao gom cac thiet lap lay out, listener va
* ham post du lieu order toi server
*/
public void initLayout() {
setContentView(R.layout.activity_confirm);
m_vwListView = (ListView) findViewById(R.id.m_vwListView);
m_vwConfirm = (Button) findViewById(R.id.btnConfirm);
m_vwContinue = (Button) findViewById(R.id.btnContinue);
m_vwTableName = (TextView) findViewById(R.id.tblName);
m_vwTotal = (TextView) findViewById(R.id.totalPaid);
m_confirmAdapter = new ConfirmAdapter(this, m_order);
m_vwListView.setAdapter(m_confirmAdapter);
}
public void initListeners() {
m_vwConfirm.setOnClickListener(this);
m_vwContinue.setOnClickListener(this);
registerForContextMenu(m_vwListView);
m_vwListView.setOnItemLongClickListener(m_confirmAdapter);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
OrderItemEntity orderItem = m_order.getOrder(m_confirmAdapter
.getSelectedPosition());
Bundle args = new Bundle();
args.putSerializable(
ItemListActivity.DIALOG_QUANTITY_SELECTOR_DUNBLE_NAME_ITEM_OBJ,
orderItem);
showDialog(ItemListActivity.DIALOG_QUANTITY_SELECTOR, args);
}
@Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch (id) {
case ItemListActivity.DIALOG_QUANTITY_SELECTOR:
dialog = new QuantityRemoverDialog(this);
dialog.setOnDismissListener(this);
break;
}
return dialog;
}
@Override
protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
switch (id) {
case ItemListActivity.DIALOG_QUANTITY_SELECTOR:
OrderItemEntity item = (OrderItemEntity) args
.getSerializable(ItemListActivity.DIALOG_QUANTITY_SELECTOR_DUNBLE_NAME_ITEM_OBJ);
((QuantityRemoverDialog) dialog).setItem(item);
break;
}
}
@Override
public void onDismiss(DialogInterface arg0) {
if (arg0 instanceof QuantityRemoverDialog) {
int selectedPosition = m_confirmAdapter.getSelectedPosition();
m_order.removeOrderItem(selectedPosition,
((QuantityRemoverDialog) arg0).getQuantity());
}
}
@Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.btnConfirm:
postOrder();
break;
case R.id.btnContinue:
startCategoryList();
break;
}
}
@Override
public void onEntityUpdated(AbstractEntity entity, int target) {
if (m_order == entity) {
startConfirmList();
if (m_order.isSynced(AbstractEntity.TARGET_REMOTE_SERVER)
&& m_order.orderId > 0) {
// order is submitted
Toast.makeText(this,
R.string.newsessionactivity_order_has_been_submitted,
Toast.LENGTH_SHORT).show();
finish();
}
}
}
@Override
public void addHttpRequestAsyncTask(HttpRequestAsyncTask hrat) {
if (m_hrat != null && m_hrat != hrat) {
m_hrat.dismissProgressDialog();
}
m_hrat = hrat;
}
@Override
public void removeHttpRequestAsyncTask(HttpRequestAsyncTask hrat) {
if (m_hrat == hrat) {
m_hrat = null;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
new Alerts(this).showAlert();
}
return true;
}
}
|
package com.haxademic.demo.audio;
import com.haxademic.core.app.PAppletHax;
import com.haxademic.core.constants.AppSettings;
import com.haxademic.core.file.FileUtil;
public class Demo_WaveformAudioRender
extends PAppletHax {
public static void main(String args[]) { PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); }
protected void overridePropsFile() {
p.appConfig.setProperty( AppSettings.FPS, 30 );
p.appConfig.setProperty( AppSettings.WIDTH, 1280 );
p.appConfig.setProperty( AppSettings.HEIGHT, 720 );
p.appConfig.setProperty( AppSettings.RENDERING_MOVIE, true );
p.appConfig.setProperty( AppSettings.RENDER_AUDIO, true );
p.appConfig.setProperty( AppSettings.RENDER_AUDIO_FILE, FileUtil.getFile("audio/cacheflowe_bigger_loop.wav") );
}
public void drawApp() {
p.background(0);
// draw waveform
p.stroke(255);
p.strokeWeight(3);
p.noFill();
float startX = 0;
float spacing = p.width / 512f;
p.beginShape();
for (int i = 0; i < _waveformData._waveform.length; i++ ) {
float curY = p.height * 0.5f + _waveformData._waveform[i] * 300f;
p.vertex(startX + i * spacing, curY);
}
p.endShape();
}
}
|
package com.hp.hpl.jena.graph.impl;
import com.hp.hpl.jena.graph.*;
import com.hp.hpl.jena.shared.*;
/**
@author kers
A base for transaction handlers - all it does is provide the canonical
implementation of executeInTransaction.
*/
public abstract class TransactionHandlerBase implements TransactionHandler
{
public TransactionHandlerBase()
{ super(); }
/**
Execute the command <code>c</code> within a transaction. If it
completes normally, commit the transaction and return the result.
Otherwise abort the transaction and throw a wrapped exception.
*/
public Object executeInTransaction( Command c )
{
begin();
try { Object result = c.execute(); commit(); return result; }
catch (Throwable e) { abort(); throw new JenaException( e ); }
}
}
|
package com.opengamma.engine.view;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.fudgemsg.FudgeContext;
import org.fudgemsg.FudgeMsg;
import org.fudgemsg.FudgeMsgEnvelope;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.opengamma.engine.ComputationTargetType;
import com.opengamma.engine.depgraph.DependencyGraph;
import com.opengamma.engine.depgraph.DependencyNode;
import com.opengamma.engine.function.LiveDataSourcingFunction;
import com.opengamma.engine.position.Position;
import com.opengamma.engine.position.PositionReference;
import com.opengamma.engine.security.Security;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.engine.view.calcnode.CalculationJob;
import com.opengamma.engine.view.calcnode.CalculationJobResult;
import com.opengamma.engine.view.calcnode.CalculationJobSpecification;
import com.opengamma.engine.view.calcnode.InvocationResult;
import com.opengamma.transport.FudgeMessageReceiver;
import com.opengamma.util.ArgumentChecker;
/**
* Will walk through a particular {@link SecurityDependencyGraph} and execute
* the required nodes.
*
* @author kirk
*/
public class DependencyGraphExecutor {
private static final Logger s_logger = LoggerFactory.getLogger(DependencyGraphExecutor.class);
// Injected Inputs:
private final String _viewName;
private Security _security; // compiler too stupid to let us make these final.
private Position _position;
private Collection<Position> _positions;
private ComputationTargetType _computationTargetType;
private final DependencyGraph _dependencyGraph;
private final ViewProcessingContext _processingContext;
// Running State:
private final Set<DependencyNode> _nodesToExecute = new HashSet<DependencyNode>();
private final Set<DependencyNode> _executingNodes = new HashSet<DependencyNode>();
private final Map<CalculationJobSpecification, DependencyNode> _executingSpecifications =
new HashMap<CalculationJobSpecification, DependencyNode>();
private final Set<DependencyNode> _executedNodes = new HashSet<DependencyNode>();
private final Set<DependencyNode> _failedNodes = new HashSet<DependencyNode>();
private final BlockingQueue<CalculationJobResult> _pendingResults = new LinkedBlockingQueue<CalculationJobResult>();
public DependencyGraphExecutor(
String viewName,
Security security,
DependencyGraph dependencyGraph,
ViewProcessingContext processingContext) {
this(viewName, dependencyGraph, processingContext);
ArgumentChecker.checkNotNull(security, "Security");
_computationTargetType = ComputationTargetType.SECURITY;
_security = security;
_position = null;
_positions = null;
}
public DependencyGraphExecutor(
String viewName,
Position position,
DependencyGraph dependencyGraph,
ViewProcessingContext processingContext) {
this(viewName, dependencyGraph, processingContext);
ArgumentChecker.checkNotNull(position, "Position");
_computationTargetType = ComputationTargetType.POSITION;
_security = null;
_position = position;
_positions = null;
}
public DependencyGraphExecutor(
String viewName,
Collection<Position> positions,
DependencyGraph dependencyGraph,
ViewProcessingContext processingContext) {
this(viewName, dependencyGraph, processingContext);
ArgumentChecker.checkNotNull(positions, "Positions");
_computationTargetType = ComputationTargetType.MULTIPLE_POSITIONS;
_security = null;
_position = null;
_positions = positions;
}
public DependencyGraphExecutor(
String viewName,
DependencyGraph dependencyGraph,
ViewProcessingContext processingContext) {
ArgumentChecker.checkNotNull(viewName, "View Name");
ArgumentChecker.checkNotNull(dependencyGraph, "Dependency Graph");
ArgumentChecker.checkNotNull(processingContext, "View Processing Context");
_computationTargetType = ComputationTargetType.PRIMITIVE;
_viewName = viewName;
_dependencyGraph = dependencyGraph;
_processingContext = processingContext;
}
/**
* @return the viewName
*/
public String getViewName() {
return _viewName;
}
/**
* @return the security
*/
public Security getSecurity() {
return _security;
}
/**
* @return the position
*/
public Position getPosition() {
return _position;
}
/**
* @return the positions
*/
public Collection<Position> getPositions() {
return _positions;
}
/**
* @return the dependencyGraph
*/
public DependencyGraph getDependencyGraph() {
return _dependencyGraph;
}
/**
* @return the processingContext
*/
public ViewProcessingContext getProcessingContext() {
return _processingContext;
}
/**
* @return the computationTargetType
*/
public ComputationTargetType getComputationTargetType() {
return _computationTargetType;
}
public synchronized void executeGraph(long iterationTimestamp, AtomicLong jobIdSource) {
addAllNodesToExecute(getDependencyGraph().getNodes());
markLiveDataSourcingFunctionsCompleted();
while(!_nodesToExecute.isEmpty()) {
enqueueAllAvailableNodes(iterationTimestamp, jobIdSource);
// REVIEW kirk 2009-10-20 -- I'm not happy with this check here.
// The rationale is that if we get a failed node, the next time we attempt to enqueue we may
// mark everything above it as done, and then we'll be done, but we'll wait for the timeout
// before determining that. There's almost certainly a better way to do this, but I needed
// to resolve this one quickly.
/*if(_executedNodes.size() >= getDependencyGraph().getNodeCount()) {
break;
}*/
assert !_executingSpecifications.isEmpty() : "Graph problem found. Nodes available, but none enqueued. Breaks execution contract";
// Suck everything available off the retrieval source.
// First time we're willing to wait for some period, but after that we pull
// off as fast as we can.
CalculationJobResult jobResult = null;
try {
jobResult = _pendingResults.poll(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.interrupted();
// REVIEW kirk 2009-11-04 -- Anything else here to do?
}
while(jobResult != null) {
DependencyNode completedNode = _executingSpecifications.remove(jobResult.getSpecification());
assert completedNode != null : "Got result " + jobResult.getSpecification() + " for job we didn't enqueue. No node to remove.";
_executingNodes.remove(completedNode);
_executedNodes.add(completedNode);
if(jobResult.getResult() != InvocationResult.SUCCESS) {
_failedNodes.add(completedNode);
failNodesAbove(completedNode);
}
jobResult = _pendingResults.poll();
}
}
}
/**
* @param nodes
*/
protected void addAllNodesToExecute(Collection<DependencyNode> nodes) {
for(DependencyNode node : nodes) {
addAllNodesToExecute(node);
}
}
protected void addAllNodesToExecute(DependencyNode node) {
// TODO kirk 2009-11-02 -- Handle optimization for where computation
// targets don't match. We don't have to enqueue the node at all.
for(DependencyNode inputNode : node.getInputNodes()) {
addAllNodesToExecute(inputNode);
}
_nodesToExecute.add(node);
}
/**
* @param completedNode
*/
protected void failNodesAbove(DependencyNode failedNode) {
// TODO kirk 2009-11-02 -- Have to figure out how to do this now.
/*
for(DependencyNode node : getDependencyGraph().getTopLevelNodes()) {
failNodesAbove(failedNode, node);
}
*/
}
/**
* @param failedNode
* @param node
*/
protected boolean failNodesAbove(DependencyNode failedNode, DependencyNode node) {
if(node == failedNode) {
return true;
}
boolean wasFailing = false;
for(DependencyNode inputNode : node.getInputNodes()) {
if(failNodesAbove(failedNode, inputNode)) {
_executedNodes.add(node);
_failedNodes.add(node);
// NOTE kirk 2009-10-20 -- Because of the diamond nature of the DAG,
// DO NOT just break or return early here. You have to evaluate all the siblings under
// this node because multiple might reach the failed node independently.
wasFailing = true;
}
}
return wasFailing;
}
protected void markLiveDataSourcingFunctionsCompleted() {
Iterator<DependencyNode> depNodeIter = _nodesToExecute.iterator();
while(depNodeIter.hasNext()) {
DependencyNode depNode = depNodeIter.next();
if(depNode.getFunctionDefinition() instanceof LiveDataSourcingFunction) {
depNodeIter.remove();
_executedNodes.add(depNode);
}
}
}
/**
* @param completionService
*/
protected synchronized void enqueueAllAvailableNodes(
long iterationTimestamp,
AtomicLong jobIdSource) {
Iterator<DependencyNode> depNodeIter = _nodesToExecute.iterator();
while(depNodeIter.hasNext()) {
DependencyNode depNode = depNodeIter.next();
if(canExecute(depNode)) {
depNodeIter.remove();
_executingNodes.add(depNode);
CalculationJobSpecification jobSpec = submitNodeInvocationJob(iterationTimestamp, jobIdSource, depNode);
_executingSpecifications.put(jobSpec, depNode);
}
}
}
/**
* @param depNode
* @return
*/
private boolean canExecute(DependencyNode node) {
assert !_executingNodes.contains(node);
assert !_executedNodes.contains(node);
// Are all inputs done?
boolean allInputsExecuted = true;
for(DependencyNode inputNode : node.getInputNodes()) {
if(!_executedNodes.contains(inputNode)) {
allInputsExecuted = false;
break;
}
}
return allInputsExecuted;
}
protected static Collection<PositionReference> convertToPositionReferences(Collection<Position> positions) {
Collection<PositionReference> resultReferences = new ArrayList<PositionReference>(positions.size());
for (Position position : positions) {
resultReferences.add(new PositionReference(position));
}
return resultReferences;
}
/**
* @param depNode
*/
protected CalculationJobSpecification submitNodeInvocationJob(
long iterationTimestamp,
AtomicLong jobIdSource,
DependencyNode depNode) {
assert !(depNode.getFunctionDefinition() instanceof LiveDataSourcingFunction);
long jobId = jobIdSource.addAndGet(1l);
CalculationJobSpecification jobSpec = new CalculationJobSpecification(getViewName(), iterationTimestamp, jobId);
s_logger.info("Enqueuing job {} to invoke {} on {}",
new Object[]{jobId, depNode.getFunctionDefinition().getShortName(), depNode.getComputationTarget()});
// Have to package up the required data
Set<ValueSpecification> resolvedInputs = new HashSet<ValueSpecification>();
for(ValueRequirement requirement : depNode.getInputRequirements()) {
resolvedInputs.add(depNode.getMappedRequirement(requirement));
}
CalculationJob job = new CalculationJob(
getViewName(),
iterationTimestamp,
jobId,
depNode.getFunctionDefinition().getUniqueIdentifier(),
depNode.getComputationTarget().getSpecification(),
resolvedInputs);
s_logger.debug("Enqueuing job with specification {}", jobSpec);
invokeJob(job);
return jobSpec;
}
/**
* @param job
*/
protected void invokeJob(CalculationJob job) {
FudgeMsg jobMsg = job.toFudgeMsg(getProcessingContext().getComputationJobRequestSender().getFudgeContext());
getProcessingContext().getComputationJobRequestSender().sendRequest(jobMsg, new FudgeMessageReceiver() {
@Override
public void messageReceived(
FudgeContext fudgeContext,
FudgeMsgEnvelope msgEnvelope) {
CalculationJobResult jobResult = CalculationJobResult.fromFudgeMsg(msgEnvelope);
jobResultReceived(jobResult);
}
});
}
protected void jobResultReceived(CalculationJobResult jobResult) {
_pendingResults.add(jobResult);
}
}
|
package com.runetooncraft.warpigeon.engine.entity.mob;
import com.runetooncraft.warpigeon.engine.entity.Entity;
import com.runetooncraft.warpigeon.engine.graphics.Sprite;
import com.runetooncraft.warpigeon.engine.level.TileCoordinate;
public abstract class Mob extends Entity {
protected Sprite sprite;
protected int dir = 0;
protected int AnimationLocation = 0;
protected boolean moving = false;
protected boolean animate = false;
protected Sprite[] ForwardAnims;
protected Sprite[] BackwardAnims;
protected Sprite[] LeftAnims;
protected Sprite[] RightAnims;
protected int AnimationCooldown = 10;
private int AnimationCooldownToggle = 0;
public int xas,yas;
protected boolean Sideways = false;
//Don't worry about this unless the game is a sidescroller
public int weight = 0;
public Mob(Sprite[] ForwardAnims, Sprite[] BackwardAnims, Sprite[] LeftAnims, Sprite[] RightAnims) {
this.ForwardAnims = ForwardAnims;
this.BackwardAnims = BackwardAnims;
this.LeftAnims = LeftAnims;
this.RightAnims = RightAnims;
animate = true;
}
public Mob() {
animate = false;
}
public void update() {
}
public void render() {
}
public void moveNoAnimate(int xa, int ya) {
boolean Collide = true;
if(xa != 0 && ya != 0) {
move(xa,0);
move(0,ya);
return;
}
xas = xa;
yas = ya;
int LastDir = dir;
if (xa < 0) dir = 1; // 0 - north| 1- east | 2 - south | 3 - west |
if (xa > 0) dir = 3;
if (ya < 0) dir = 2;
if (ya > 0) dir = 0;
if (!collision(xa,ya)) {
Collide = false;
x += xa;
y += ya;
}
}
public void move(int xa, int ya) {
if(!animate) {
moveNoAnimate(xa,ya);
return;
}
boolean Collide = true;
// if(xa != 0 && ya == 0 || xa == 0 && ya != 0) {
// move(xa,0);
// move(0,ya);
// return;
xas = xa;
yas = ya;
int LastDir = dir;
if (xa < 0) dir = 1; // 0 - north| 1- east | 2 - south | 3 - west |
if (xa > 0) dir = 3;
if (ya < 0) dir = 2;
if (ya > 0) dir = 0;
if (ya > 0 && xa < 0) dir = 4;
if (ya > 0 && xa > 0) dir = 5;
if (ya < 0 && xa > 0) dir = 6;
if (ya < 0 && xa < 0) dir = 7;
// System.out.println("Dir: " + dir);
if (!collision(xa,ya)) {
Collide = false;
x += xa;
y += ya;
}
if(Collide == false) {
if(dir != LastDir) {
DirDoesNotEqualLastDir(LastDir);
} else {
if(dir == 0 && (AnimationLocation + 1) < ForwardAnims.length ||
dir == 1 && (AnimationLocation + 1) < LeftAnims.length ||
dir == 2 && (AnimationLocation + 1) < BackwardAnims.length ||
dir == 3 && (AnimationLocation + 1) < RightAnims.length ||
dir == 4 && (AnimationLocation + 1) < ForwardAnims.length ||
dir == 5 && (AnimationLocation + 1) < ForwardAnims.length ||
dir == 6 && (AnimationLocation + 1) < ForwardAnims.length ||
dir == 7 && (AnimationLocation + 1) < ForwardAnims.length) {
AnimationLocation++;
} else {
AnimationLocation = 0;
}
}
if(AnimationCooldownToggle == AnimationCooldown) {
AnimationCooldownToggle = 0;
if(dir == 0 || dir == 4 || dir == 5) {
sprite = ForwardAnims[AnimationLocation];
} else if(dir == 1) {
sprite = LeftAnims[AnimationLocation];
} else if(dir == 2 || dir == 6 || dir == 7) {
sprite = BackwardAnims[AnimationLocation];
} else if(dir == 3) {
sprite = RightAnims[AnimationLocation];
}
}else{
if(AnimationCooldownToggle < AnimationCooldown) {
AnimationCooldownToggle++;
}else{
AnimationCooldownToggle = 0;
}
}
}
}
public void DirDoesNotEqualLastDir(int LastDir) {
AnimationLocation = 0;
if(dir == 0) {
sprite = ForwardAnims[0];
}else if(dir == 1) {
sprite = LeftAnims[0];
}else if(dir == 2) {
sprite = BackwardAnims[0];
}else if(dir == 3) {
sprite = RightAnims[0];
}
}
public boolean collision(int xa, int ya) {
boolean solid = false;
for(int i = 0; i < 4; i++) {
int xp = ((x + xa) + i % 2 * 12 - 7) / engine.getScreenEngine2D().PixelWidth;
int yp = ((y + ya) + i / 2 * 12 + 7) / engine.getScreenEngine2D().PixelHeight;
if (level.getTile(xp, yp).collide(i)) solid = true;
}
return solid;
}
public boolean checkCollideBelow() {
return collision(xas, (yas - engine.getScreenEngine2D().PixelHeight));
}
public Sprite getSprite() {
return sprite;
}
}
|
package com.db.autoupdater.basic;
import java.net.URL;
import java.net.URLClassLoader;
import com.db.autoupdater.AutoUpdateable;
import com.db.autoupdater.AutoUpdater;
import com.db.event.EventDelegate;
import com.db.event.EventObject;
import com.db.logging.Logger;
import com.db.logging.LoggerManager;
import com.db.util.ConfigFile;
import com.db.util.ConfigOptions;
import com.db.util.MethodInvoker;
import com.db.util.JobDispatcher;
public abstract class AbstractAutoUpdater implements AutoUpdater
{
/**
* A JobDispatcher for sending arguments to the running
* AutoUpdateable application.
*/
protected JobDispatcher mArgumentDispatcher;
/**
* The currently running AutoUpdateable application.
*/
protected AutoUpdateable mRunningAutoUpdateable;
/**
* Gets the configuration options used to load the current
* AutoUpdateable application.
*/
protected ConfigOptions mAutoUpdateableConfig;
/**
* Set to true when this AutoUpdater requires a reload, false otherwise.
*/
protected boolean mRequiresReload;
/**
* Set to true when this AutoUpdater requires a new loader, false otherwise.
*/
protected boolean mRequiresNewLoader;
/**
* True while processing an update, false otherwise.
*/
protected boolean mProcessingUpdate;
/**
* True when this AutoUpdater should automatically check for updates, false
* when it should not.
*/
protected boolean mAutoCheckForUpdate;
/**
* The number of milliseconds to sleep in between automatic update checks.
*/
protected long mAutoCheckForUpdateInterval;
/**
* A reference to the auto update checker thread.
*/
protected Thread mAutoCheckThread;
/**
* An event delegate for check for update started events.
*/
protected EventDelegate mCheckForUpdateStartedEventDelegate;
/**
* An event delegate for update script found events.
*/
protected EventDelegate mUpdateScriptFoundEventDelegate;
/**
* An event delegate for update script not found events.
*/
protected EventDelegate mUpdateScriptNotFoundEventDelegate;
/**
* An event delegate for update script completed events.
*/
protected EventDelegate mUpdateScriptCompletedEventDelegate;
/**
* An event delegate for update script cancelled events.
*/
protected EventDelegate mUpdateScriptCancelledEventDelegate;
/**
* An event delegate for update script failed events.
*/
protected EventDelegate mUpdateScriptFailedEventDelegate;
/**
* An event delegate for update script reverted events.
*/
protected EventDelegate mUpdateScriptRevertedEventDelegate;
/**
* An event delegate for update script revert failed events.
*/
protected EventDelegate mUpdateScriptRevertFailedEventDelegate;
/**
* An event delegate for update script processed events.
*/
protected EventDelegate mUpdateScriptProcessedEventDelegate;
/**
* An event delegate for execute application events.
*/
protected EventDelegate mExecuteApplicationEventDelegate;
/**
* An event delegate for shutdown application events.
*/
protected EventDelegate mShutdownApplicationEventDelegate;
/**
* An event delegate for application shutdown events.
*/
protected EventDelegate mApplicationShutdownEventDelegate;
/**
* Creates a new AutoUpdater.
*/
public AbstractAutoUpdater()
{
// create the argument dispatcher
mArgumentDispatcher = new JobDispatcher();
// no auto-updateable application is presently running
setRunningAutoUpdateable(null);
// no configuration for the auto-updateable application yet
setAutoUpdateableConfig(null);
// no reload required by default
setRequiresReload(false);
// no new loader required by default
setRequiresNewLoader(false);
// not processing an update by default
setProcessingUpdate(false);
// do not auto check for updates by default
setAutoCheckForUpdate(false);
// default the auto check interval to 30 seconds
setAutoCheckForUpdateInterval(30000);
// create check for update started event delegate
mCheckForUpdateStartedEventDelegate = new EventDelegate();
// create update script found event delegate
mUpdateScriptFoundEventDelegate = new EventDelegate();
// create update script not found event delegate
mUpdateScriptNotFoundEventDelegate = new EventDelegate();
// create update script completed delegate
mUpdateScriptCompletedEventDelegate = new EventDelegate();
// create update script cancelled delegate
mUpdateScriptCancelledEventDelegate = new EventDelegate();
// create update script failed delegate
mUpdateScriptFailedEventDelegate = new EventDelegate();
// create update script reverted delegate
mUpdateScriptRevertedEventDelegate = new EventDelegate();
// create update script revert failed delegate
mUpdateScriptRevertFailedEventDelegate = new EventDelegate();
// create update script processed delegate
mUpdateScriptProcessedEventDelegate = new EventDelegate();
// create execute application event delegate
mExecuteApplicationEventDelegate = new EventDelegate();
// create shutdown application event delegate
mShutdownApplicationEventDelegate = new EventDelegate();
// create application shutdown delegate
mApplicationShutdownEventDelegate = new EventDelegate();
}
/**
* Fires a check for update started event.
*
* @param event the event to fire.
*/
protected void fireCheckForUpdateStartedEvent(EventObject event)
{
mCheckForUpdateStartedEventDelegate.fireEvent(event);
}
/**
* Fires an update script found event.
*
* @param event the event to fire.
*/
protected void fireUpdateScriptFoundEvent(EventObject event)
{
mUpdateScriptFoundEventDelegate.fireEvent(event);
}
/**
* Fires an update script not found event.
*
* @param event the event to fire.
*/
protected void fireUpdateScriptNotFoundEvent(EventObject event)
{
mUpdateScriptNotFoundEventDelegate.fireEvent(event);
}
/**
* Fires an update script completed event.
*
* @param event the event to fire.
*/
protected void fireUpdateScriptCompletedEvent(EventObject event)
{
mUpdateScriptCompletedEventDelegate.fireEvent(event);
}
/**
* Fires an update script cancelled event.
*
* @param event the event to fire.
*/
protected void fireUpdateScriptCancelledEvent(EventObject event)
{
mUpdateScriptCancelledEventDelegate.fireEvent(event);
}
/**
* Fires an update script failed event.
*
* @param event the event to fire.
*/
protected void fireUpdateScriptFailedEvent(EventObject event)
{
mUpdateScriptFailedEventDelegate.fireEvent(event);
}
/**
* Fires an update script reverted event.
*
* @param event the event to fire.
*/
protected void fireUpdateScriptRevertedEvent(EventObject event)
{
mUpdateScriptRevertedEventDelegate.fireEvent(event);
}
/**
* Fires an update script revert failed event.
*
* @param event the event to fire.
*/
protected void fireUpdateScriptRevertFailedEvent(EventObject event)
{
mUpdateScriptRevertFailedEventDelegate.fireEvent(event);
}
/**
* Fires an update script processed event.
*
* @param event the event to fire.
*/
protected void fireUpdateScriptProcessedEvent(EventObject event)
{
mUpdateScriptProcessedEventDelegate.fireEvent(event);
}
/**
* Fires an execute application event.
*
* @param event the event to fire.
*/
protected void fireExecuteApplicationEvent(EventObject event)
{
mExecuteApplicationEventDelegate.fireEvent(event);
}
/**
* Fires a shutdown application event.
*
* @param event the event to fire.
*/
protected void fireShutdownApplicationEvent(EventObject event)
{
mShutdownApplicationEventDelegate.fireEvent(event);
}
/**
* Fires an application shutdown event.
*
* @param event the event to fire.
*/
protected void fireApplicationShutdownEvent(EventObject event)
{
mApplicationShutdownEventDelegate.fireEvent(event);
}
/**
* Sets the currently running AutoUpdateable application.
*
* @param application the auto-updateable application that is currently
* running.
*/
protected synchronized void setRunningAutoUpdateable(
AutoUpdateable application)
{
mRunningAutoUpdateable = application;
if(application != null)
{
// start dispatching arguments
getArgumentDispatcher().startDispatching();
}
else
{
// stop dispatching arguments
getArgumentDispatcher().stopDispatching();
}
}
/**
* Gets the currently running AutoUpdateable application.
*
* @return the currently running auto-updateable application, or null
* if none is running.
*/
protected synchronized AutoUpdateable getRunningAutoUpdateable()
{
return mRunningAutoUpdateable;
}
/**
* Sets the configuration options for the current AutoUpdateable application.
*
* @param config the configuration options for the current AutoUpdateable
* application.
*/
protected synchronized void setAutoUpdateableConfig(ConfigOptions config)
{
mAutoUpdateableConfig = config;
}
/**
* Gets the configuration options for the current AutoUpdateable application.
*
* @return the configuration options for the current AutoUpdateable
* application.
*/
protected synchronized ConfigOptions getAutoUpdateableConfig()
{
return mAutoUpdateableConfig;
}
/**
* Gets the version of the current AutoUpdateable application.
*
* @return the version of the current AutoUpdateable application.
*/
protected synchronized String getAutoUpdateableVersion()
{
String version = "";
if(getAutoUpdateableConfig() != null)
{
version = getAutoUpdateableConfig().getString(
"autoupdateable-version");
}
return version;
}
/**
* Gets the argument dispatcher for sending arguments to the
* running AutoUpdateable.
*
* @return the argument dispatcher.
*/
protected JobDispatcher getArgumentDispatcher()
{
return mArgumentDispatcher;
}
/**
* Sets whether or not this AutoUpdater requires a reload.
*
* @param reload true if this AutoUpdater requires a reload, false if not.
*/
protected synchronized void setRequiresReload(boolean reload)
{
mRequiresReload = reload;
}
/**
* Sets whether or not this AutoUpdater requires a new AutoUpdaterLoader.
*
* @param newLoader true if this AutoUpdater requires a
* new AutoUpdaterLoader, false if not.
*/
protected synchronized void setRequiresNewLoader(boolean newLoader)
{
mRequiresNewLoader = newLoader;
}
/**
* Sets whether or not this AutoUpdater is processing an update.
*
* @param processing true if this AutoUpdater is processing an update,
* false if not.
*/
protected synchronized void setProcessingUpdate(boolean processing)
{
mProcessingUpdate = processing;
}
/**
* Sets whether or not this AutoUpdater should automatically check
* for updates.
*
* @param check true if this AutoUpdater should automatically check for
* updates, false if not.
*/
protected void setAutoCheckForUpdate(boolean check)
{
mAutoCheckForUpdate = check;
}
/**
* Gets whether or not this AutoUpdater should automatically check
* for updates.
*
* @return true if this AutoUpdater should automatically check for
* updates, false if not.
*/
protected boolean shouldAutoCheckForUpdate()
{
return mAutoCheckForUpdate;
}
/**
* Checks for an update for the given application.
*
* @param application the application to check for updates of.
*
* @return true if an update was processed, false if not.
*/
protected synchronized boolean checkForUpdate(AutoUpdateable application)
{
boolean rval = false;
// fire a check for update started event
EventObject event = new EventObject("checkForUpdateStarted");
fireCheckForUpdateStartedEvent(event);
// get the update script source
UpdateScriptSource source = getUpdateScriptSource();
// check for an update script
if(source.hasUpdateScript(application))
{
// get the update script
UpdateScript script = source.getUpdateScript(application);
// validate the script
if(script.validate())
{
// fire event indicating that an update script has been found
event = new EventObject("updateScriptFound");
event.setData("updateScript", script);
event.setDataKeyMessage("updateScript",
"The update script, class=" + script.getClass().getName());
event.setData("processUpdate", false);
event.setDataKeyMessage("processUpdate",
"A boolean if set to true tells the AutoUpdater to " +
"process the update script.");
fireUpdateScriptFoundEvent(event);
// see if the update should be processed
if(event.getDataBooleanValue("processUpdate"))
{
// process update script
rval = true;
processUpdateScript(application, script);
}
}
else
{
// fire event indicating that an update script has not been found
event = new EventObject("updateScriptNotFound");
fireUpdateScriptNotFoundEvent(event);
}
}
else
{
// fire event indicating that an update script has not been found
event = new EventObject("updateScriptNotFound");
fireUpdateScriptNotFoundEvent(event);
}
return rval;
}
/**
* Shutsdown any running application and processes an update script.
*
* @param application the application that is running.
* @param script the update script to process.
*/
protected synchronized void processUpdateScript(
AutoUpdateable application, UpdateScript script)
{
// ensure this thread is not interrupted
if(!Thread.currentThread().isInterrupted())
{
// now processing an update
setProcessingUpdate(true);
// fire event indicating the auto-updateable application is
// getting shutdown
EventObject event = new EventObject("shutdownApplication");
event.setData("cancel", false);
event.setDataKeyMessage("cancel",
"A boolean if set to true cancels application shutdown.");
fireShutdownApplicationEvent(event);
// make sure shutdown was not cancelled
if(!event.getDataBooleanValue("cancel"))
{
// shutdown the application
application.shutdown();
// fire event indicating the auto-updateable application has been
// shutdown
event = new EventObject("applicationShutdown");
fireApplicationShutdownEvent(event);
// process the script
boolean success = script.process();
// set whether or not this AutoUpdater requires a reload
setRequiresReload(script.autoUpdaterRequiresReload());
if(success)
{
// script processing was successful
// fire event indicating an update script was completed
event = new EventObject("updateScriptCompleted");
event.setData("updateScript", script);
event.setDataKeyMessage("updateScript",
"The update script, class=" + script.getClass().getName());
fireUpdateScriptCompletedEvent(event);
}
else
{
// script processing was cancelled or there was an error
// create a new event to fire
event = new EventObject();
event.setData("updateScript", script);
event.setDataKeyMessage("updateScript",
"The update script, class=" + script.getClass().getName());
event.setData("revert", true);
event.setDataKeyMessage("revert",
"A boolean if set true will tell the AutoUpdater to" +
"revert the update script.");
// fire event indicating an update script was cancelled or
// failed and will now be reverted unless cancelled
if(script.cancelled())
{
event.setName("updateScriptCancelled");
fireUpdateScriptCancelledEvent(event);
}
else
{
event.setName("updateScriptFailed");
fireUpdateScriptFailedEvent(event);
}
if(event.getDataBooleanValue("revert"))
{
// attempt to revert script
if(script.revert())
{
// fire event indicating an update script was reverted
event = new EventObject("updateScriptReverted");
event.setData("updateScript", script);
event.setDataKeyMessage("updateScript",
"The update script, class=" +
script.getClass().getName());
fireUpdateScriptRevertedEvent(event);
}
else
{
// fire event indicating an update script revert failed
event = new EventObject("updateScriptRevertFailed");
event.setData("updateScript", script);
event.setDataKeyMessage("updateScript",
"The update script, class=" +
script.getClass().getName());
fireUpdateScriptRevertFailedEvent(event);
}
// set whether or not this AutoUpdater requires a reload
setRequiresReload(script.autoUpdaterRequiresReload());
}
}
// no longer processing an update
setProcessingUpdate(false);
// fire event indicating an update script was processed
event = new EventObject("updateScriptProcessed");
event.setData("updateScript", script);
event.setDataKeyMessage("updateScript",
"The update script, class=" + script.getClass().getName());
fireUpdateScriptProcessedEvent(event);
}
}
}
/**
* Loads an AutoUpdateable application from the passed configuration.
*
* @param config the configuration to load an AutoUpdateable application
* from.
*
* @return the AutoUpdateable application or null if one could not be loaded.
*/
protected synchronized AutoUpdateable loadAutoUpdateable(
ConfigOptions config)
{
AutoUpdateable rval = null;
try
{
// get the jars necessary to load the AutoUpdateable interface
String classPath = config.getString("autoupdateable-classpath");
String[] split = classPath.split(",");
URL[] urls = new URL[split.length];
for(int i = 0; i < urls.length; i++)
{
urls[i] = new URL(split[i]);
}
// create a class loader for the AutoUpdateable
ClassLoader classLoader = new URLClassLoader(urls);
// load the AutoUpdateable
Class c = classLoader.loadClass(
config.getString("autoupdateable-class"));
rval = (AutoUpdateable)c.newInstance();
// set the auto-updateable configuration
setAutoUpdateableConfig(config);
}
catch(Throwable t)
{
getLogger().error(getClass(), Logger.getStackTrace(t));
}
return rval;
}
/**
* Runs an application while monitoring for updates in a background process.
*
* This method returns true if the application has finished executing and
* should be run again once updates have been installed, and false if
* the application has finished executing and should not be run again, even
* after updates have been installed.
*
* @param application the auto-updateable application to execute.
*/
protected void run(AutoUpdateable application)
{
// check for an update, start the application if there isn't one
if(!checkForUpdate(application))
{
// set automatic check flag to true
setAutoCheckForUpdate(true);
// start the update checker thread
Object[] params = new Object[]{application};
MethodInvoker updateChecker =
new MethodInvoker(this, "continuouslyCheckForUpdate", params);
mAutoCheckThread = updateChecker;
updateChecker.backgroundExecute();
// fire event indicating that the auto-updateable application
// is being executed
EventObject event = new EventObject("executeApplication");
event.setData("cancel", false);
event.setDataKeyMessage("cancel",
"A boolean if set to true cancels application execution.");
fireExecuteApplicationEvent(event);
// see if application execution should be cancelled
if(!event.getDataBooleanValue("cancel"))
{
// execute application
application.execute();
}
try
{
// sleep while the application is running
while(application.isRunning())
{
Thread.sleep(1);
}
// interrupt update checker thread if not processing an update
if(!isProcessingUpdate())
{
updateChecker.interrupt();
}
// join the update checker thread
updateChecker.join();
}
catch(InterruptedException e)
{
// interrupt threads
updateChecker.interrupt();
Thread.currentThread().interrupt();
}
// set automatic check flag to false
setAutoCheckForUpdate(false);
}
}
/**
* Overridden to terminate the auto update checker thread.
*/
public void finalize()
{
setAutoCheckForUpdate(false);
if(mAutoCheckThread != null)
{
// make sure to interrupt the auto check thread
mAutoCheckThread.interrupt();
}
}
/**
* This method is provided for convenience. It can be overloaded to
* pause the current thread for some period of time. Another way to
* pause between update checks is to handle the checkForUpdateStarted
* event by pausing.
*
* Causes the update checker thread to pause for some period of time
* before checking for an update. The default period of time is
* 30 seconds.
*
* Throws an InterruptedException if the thread is interrupted while
* sleeping.
*
* @exception InterruptedException
*/
public void pauseUpdateCheckerThread() throws InterruptedException
{
if(getAutoCheckForUpdateInterval() > 0)
{
Thread.sleep(getAutoCheckForUpdateInterval());
}
}
/**
* Continuously checks for an update for the given application.
*
* @param application the application to check for updates of.
*/
public void continuouslyCheckForUpdate(AutoUpdateable application)
{
try
{
while(shouldAutoCheckForUpdate())
{
// pause this thread
pauseUpdateCheckerThread();
// check for an update for the application
if(shouldAutoCheckForUpdate() &&
!Thread.currentThread().isInterrupted())
{
// check for an update if the auto check interval is positive
if(getAutoCheckForUpdateInterval() > 0)
{
checkForUpdate(application);
}
}
}
}
catch(InterruptedException e)
{
// interrupt thread
Thread.currentThread().interrupt();
}
}
/**
* Runs the AutoUpdateable application specified the in the passed
* AutoUpdateable configuration.
*
* @param configFilename the name of the configuration file used to
* load an AutoUpdateable application.
* @param args the arguments to start the application with.
*
* @return true if the AutoUpdateable application should be restarted,
* false if not.
*/
public boolean runAutoUpdateable(String configFilename, String[] args)
{
boolean rval = false;
// get the AutoUpdateable application's config file
ConfigFile configFile = new ConfigFile(configFilename);
if(configFile.read())
{
rval = runAutoUpdateable(configFile, args);
}
else
{
getLogger().error(getClass(),
"Could not read AutoUpdateable configuration file!");
}
return rval;
}
/**
* Runs the AutoUpdateable application specified the in the AutoUpdateable
* configuration found in the file with the passed name.
*
* @param config the configuration to load an AutoUpdateable
* application from.
* @param args the arguments to start the application with.
*
* @return true if the AutoUpdateable application should be restarted,
* false if not.
*/
public boolean runAutoUpdateable(ConfigOptions config, String[] args)
{
boolean rval = true;
// keep running the AutoUpdateable application while it should
// restart and a reload of this AutoUpdater is not required
while(rval && !requiresReload())
{
// load the AutoUpdateable application
AutoUpdateable application = loadAutoUpdateable(config);
if(application != null)
{
// process the arguments
application.processArguments(args);
// set running AutoUpdateable
setRunningAutoUpdateable(application);
// run the application
run(application);
// AutoUpdateable no longer running
setRunningAutoUpdateable(null);
// see if the application should not restart
if(!application.shouldRestart())
{
// application should not restart
rval = false;
}
// clean up AutoUpdateable application
application = null;
System.gc();
}
else
{
// do not run application -- it can't be loaded
rval = false;
getLogger().error(getClass(),
"Could not load AutoUpdateable application!");
}
}
return rval;
}
/**
* Dispatches arguments to the currently running AutoUpdateable application.
*
* This method is called from by the argument dispatcher.
*
* @param args the arguments to dispatch.
*/
public void dispatchArguments(String[] args)
{
// get the currently running AutoUpdateable
AutoUpdateable application = getRunningAutoUpdateable();
if(application != null)
{
// process the arguments
application.processArguments(args);
}
}
/**
* Passes arguments to a running AutoUpdateable application.
*
* @param args the arguments to pass to a running AutoUpdateable application.
*/
public void passArguments(String[] args)
{
// create a runnable job for dispatching the arguments
MethodInvoker job = new MethodInvoker(
this, "dispatchArguments", new Object[]{args});
// queue the job
getArgumentDispatcher().queueJob(job);
}
/**
* Gets the check for update started event delegate.
*
* @return the check for update started event delegate.
*/
public EventDelegate getCheckForUpdateStartedEventDelegate()
{
return mCheckForUpdateStartedEventDelegate;
}
/**
* Gets the update script found event delegate.
*
* @return the update script found event delegate.
*/
public EventDelegate getUpdateScriptFoundEventDelegate()
{
return mUpdateScriptFoundEventDelegate;
}
/**
* Gets the update script not found event delegate.
*
* @return the update script not found event delegate.
*/
public EventDelegate getUpdateScriptNotFoundEventDelegate()
{
return mUpdateScriptNotFoundEventDelegate;
}
/**
* Gets the update script completed event delegate.
*
* @return the update script completed event delegate.
*/
public EventDelegate getUpdateScriptCompletedEventDelegate()
{
return mUpdateScriptCompletedEventDelegate;
}
/**
* Gets the update script cancelled event delegate.
*
* @return the update script cancelled event delegate.
*/
public EventDelegate getUpdateScriptCancelledEventDelegate()
{
return mUpdateScriptCancelledEventDelegate;
}
/**
* Gets the update script failed event delegate.
*
* @return the update script failed event delegate.
*/
public EventDelegate getUpdateScriptFailedEventDelegate()
{
return mUpdateScriptFailedEventDelegate;
}
/**
* Gets the update script reverted event delegate.
*
* @return the update script reverted event delegate.
*/
public EventDelegate getUpdateScriptRevertedEventDelegate()
{
return mUpdateScriptRevertedEventDelegate;
}
/**
* Gets the update script revert failed event delegate.
*
* @return the update script revert failed event delegate.
*/
public EventDelegate getUpdateScriptRevertFailedEventDelegate()
{
return mUpdateScriptRevertFailedEventDelegate;
}
/**
* Gets the update script processed event delegate.
*
* @return the update script processed event delegate.
*/
public EventDelegate getUpdateScriptProcessedEventDelegate()
{
return mUpdateScriptProcessedEventDelegate;
}
/**
* Gets the execute application event delegate.
*
* @return the execute application event delegate.
*/
public EventDelegate getExecuteApplicationEventDelegate()
{
return mExecuteApplicationEventDelegate;
}
/**
* Gets the shutdown application event delegate.
*
* @return the shutdown application event delegate.
*/
public EventDelegate getShutdownApplicationEventDelegate()
{
return mShutdownApplicationEventDelegate;
}
/**
* Gets the application shutdown event delegate.
*
* @return the application shutdown event delegate.
*/
public EventDelegate getApplicationShutdownEventDelegate()
{
return mApplicationShutdownEventDelegate;
}
/**
* Gets whether or not this AutoUpdater requires a reload.
*
* This method should return true whenever this AutoUpdater must
* be reloaded because its core libraries (i.e. classes/jars
* necessary to load this AutoUpdater) have changed via an update but the
* AutoUpdater can be reloaded.
*
* @return true if this AutoUpdater requires a reload, false if not.
*/
public synchronized boolean requiresReload()
{
return mRequiresReload;
}
/**
* Gets whether or not this AutoUpdater requires a shutdown.
*
* This method should return true whenever an update has changed this
* AutoUpdater in such a way that it requires a new AutoUpdaterLoader
* to be loaded again.
*
* @return true if this AutoUpdater requires a new loader, false if not.
*/
public synchronized boolean requiresNewLoader()
{
return mRequiresNewLoader;
}
/**
* Gets whether or not this AutoUpdater is processing an update.
*
* @return true if this AutoUpdater is processing an update, false if not.
*/
public synchronized boolean isProcessingUpdate()
{
return mProcessingUpdate;
}
/**
* Sets the number of milliseconds to wait in between automatic update
* checks.
*
* A non-positive return value indicates that no automatic update checks
* will be made.
*
* @param interval the number of milliseconds to wait in between automatic
* update checks.
*/
public void setAutoCheckForUpdateInterval(long interval)
{
mAutoCheckForUpdateInterval = interval;
}
/**
* Sets the number of milliseconds to wait in between automatic update
* checks.
*
* A non-positive return value indicates that no automatic update checks
* will be made.
*
* @return the number of milliseconds to wait in between automatic
* update checks.
*/
public long getAutoCheckForUpdateInterval()
{
return mAutoCheckForUpdateInterval;
}
/**
* Gets the UpdateScriptSource for this AutoUpdater.
*
* @return the UpdateScriptSource for this AutoUpdater.
*/
public abstract UpdateScriptSource getUpdateScriptSource();
/**
* Gets the logger for this AutoUpdater.
*
* @return the logger for this AutoUpdater.
*/
public Logger getLogger()
{
return LoggerManager.getLogger("dbautoupdater");
}
}
|
package com.dmdirc.ui.messages;
import com.dmdirc.FrameContainer;
import com.dmdirc.actions.ActionManager;
import com.dmdirc.actions.CoreActionType;
import com.dmdirc.interfaces.ConfigChangeListener;
import com.dmdirc.logger.ErrorLevel;
import com.dmdirc.logger.Logger;
import java.awt.Color;
import java.util.Locale;
import javax.swing.UIManager;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
/**
* The styliser applies IRC styles to text. Styles are indicated by various
* control codes which are a de-facto IRC standard.
* @author chris
*/
public class Styliser implements ConfigChangeListener {
/** The character used for marking up bold text. */
public static final char CODE_BOLD = 2;
/** The character used for marking up coloured text. */
public static final char CODE_COLOUR = 3;
/** The character used for marking up coloured text (using hex). */
public static final char CODE_HEXCOLOUR = 4;
/** Character used to indicate hyperlinks. */
public static final char CODE_HYPERLINK = 5;
/** Character used to indicate channel links. */
public static final char CODE_CHANNEL = 6;
/** Character used to indicate smilies. */
public static final char CODE_SMILIE = 7;
/** The character used for stopping all formatting. */
public static final char CODE_STOP = 15;
/** Character used to indicate nickname links. */
public static final char CODE_NICKNAME = 16;
/** The character used for marking up fixed pitch text. */
public static final char CODE_FIXED = 17;
/** The character used for negating control codes. */
public static final char CODE_NEGATE = 18;
/** The character used for tooltips. */
public static final char CODE_TOOLTIP = 19;
/** The character used for marking up italic text. */
public static final char CODE_ITALIC = 29;
/** The character used for marking up underlined text. */
public static final char CODE_UNDERLINE = 31;
/** Internal chars. */
private static final String INTERNAL_CHARS = String.valueOf(CODE_HYPERLINK)
+ CODE_NICKNAME + CODE_CHANNEL + CODE_SMILIE + CODE_TOOLTIP;
/** Characters used for hyperlinks. */
private static final String HYPERLINK_CHARS = CODE_HYPERLINK + "" + CODE_CHANNEL;
/** Regexp to match characters which shouldn't be used in channel links. */
private static final String RESERVED_CHARS = "[^\\s" + CODE_BOLD + CODE_COLOUR
+ CODE_STOP + CODE_HEXCOLOUR + CODE_FIXED + CODE_ITALIC
+ CODE_UNDERLINE + CODE_CHANNEL + CODE_NICKNAME + CODE_NEGATE + "\",]";
private static final String URL_PUNCT_ILLEGAL = "\"";
private static final String URL_PUNCT_LEGAL = "';:!,\\.\\?";
/** Defines all trailing punctuation. */
private static final String URL_PUNCT = URL_PUNCT_ILLEGAL + URL_PUNCT_LEGAL;
/** Defines all characters allowed in URLs that aren't treated as trailing punct. */
private static final String URL_NOPUNCT = "a-z0-9$\\-_@&\\+\\*\\(\\)=/
/** Defines all characters allowed in URLs per W3C specs. */
private static final String URL_CHARS = "[" + URL_PUNCT_LEGAL + URL_NOPUNCT
+ "]*[" + URL_NOPUNCT + "]+[" + URL_PUNCT_LEGAL + URL_NOPUNCT + "]*";
/** The regular expression to use for marking up URLs. */
private static final String URL_REGEXP = "(?i)([a-z+]+://" + URL_CHARS
+ "|(?<![a-z0-9:/])www\\." + URL_CHARS + ")";
/** Regular expression for intelligent handling of closing brackets. */
private static final String URL_INT1 = "(\\([^\\)" + HYPERLINK_CHARS
+ "]*(?:[" + HYPERLINK_CHARS + "][^" + HYPERLINK_CHARS + "]*["
+ HYPERLINK_CHARS + "])?[^\\)" + HYPERLINK_CHARS + "]*[" + HYPERLINK_CHARS
+ "][^" + HYPERLINK_CHARS + "]+)(\\)['\";:!,\\.\\)]*)([" + HYPERLINK_CHARS + "])";
/** Regular expression for intelligent handling of trailing single and double quotes. */
private static final String URL_INT2 = "(^(?:[^" + HYPERLINK_CHARS + "]+|["
+ HYPERLINK_CHARS + "][^" + HYPERLINK_CHARS + "][" + HYPERLINK_CHARS
+ "]))(['\"])([^" + HYPERLINK_CHARS + "]*?[" + HYPERLINK_CHARS + "][^"
+ HYPERLINK_CHARS + "]+)(\\1[" + URL_PUNCT + "]*)([" + HYPERLINK_CHARS + "])";
/** Regular expression for intelligent handling of surrounding quotes. */
private static final String URL_INT3 = "(['\"])([" + HYPERLINK_CHARS
+ "][^" + HYPERLINK_CHARS + "]+?)(\\1[^" + HYPERLINK_CHARS + "]*)(["
+ HYPERLINK_CHARS + "])";
/** Regular expression for intelligent handling of trailing punctuation. */
private static final String URL_INT4 = "([" + HYPERLINK_CHARS + "][^"
+ HYPERLINK_CHARS + "]+?)([" + URL_PUNCT + "]?)([" + HYPERLINK_CHARS + "])";
/** The regular expression to use for marking up channels. */
private static final String URL_CHANNEL = "(?i)(?<![^\\s\\+@\\-<>\\(\"',])([\\Q%s\\E]"
+ RESERVED_CHARS + "+)";
/** Whether or not we should style links. */
private boolean styleURIs, styleChannels;
/** Colours to use for URI and channel links. */
private Color uriColour, channelColour;
/** The container that owns this styliser. */
private final FrameContainer owner;
/**
* Creates a new instance of Styliser.
*
* @param owner The {@link FrameContainer} that owns this styliser.
* @since 0.6.3
*/
public Styliser(final FrameContainer owner) {
this.owner = owner;
owner.getConfigManager().addChangeListener("ui", "linkcolour", this);
owner.getConfigManager().addChangeListener("ui", "channelcolour", this);
owner.getConfigManager().addChangeListener("ui", "stylelinks", this);
owner.getConfigManager().addChangeListener("ui", "stylechannels", this);
styleURIs = owner.getConfigManager().getOptionBool("ui", "stylelinks");
styleChannels = owner.getConfigManager().getOptionBool("ui", "stylechannels");
uriColour = owner.getConfigManager().getOptionColour("ui", "linkcolour");
channelColour = owner.getConfigManager().getOptionColour("ui", "channelcolour");
}
/**
* Stylises the specified strings and adds them to the specified document.
*
* @param styledDoc Document to add the styled strings to
* @param strings The lines to be stylised
*/
public void addStyledString(final StyledDocument styledDoc, final String[] strings) {
addStyledString(styledDoc, strings, new SimpleAttributeSet());
}
/**
* Stylises the specified strings and adds them to the specified document.
*
* @param styledDoc Document to add the styled strings to
* @param strings The lines to be stylised
* @param attribs Base attribute set
*/
public void addStyledString(final StyledDocument styledDoc,
final String[] strings, final SimpleAttributeSet attribs) {
resetAttributes(attribs);
for (int i = 0; i < strings.length; i++) {
final char[] chars = strings[i].toCharArray();
for (int j = 0; j < chars.length; j++) {
if (chars[j] == 65533) {
chars[j] = '?';
}
}
try {
final int ooffset = styledDoc.getLength();
int offset = ooffset;
int position = 0;
final String target = doSmilies(doLinks(new String(chars)
.replaceAll(INTERNAL_CHARS, "")));
attribs.addAttribute("DefaultFontFamily", UIManager.getFont("TextPane.font"));
while (position < target.length()) {
final String next = readUntilControl(target.substring(position));
styledDoc.insertString(offset, next, attribs);
position += next.length();
offset += next.length();
if (position < target.length()) {
position += readControlChars(target.substring(position),
attribs, position == 0);
}
}
ActionManager.processEvent(CoreActionType.CLIENT_STRING_STYLED,
null, styledDoc, ooffset, styledDoc.getLength() - ooffset);
} catch (BadLocationException ex) {
Logger.userError(ErrorLevel.MEDIUM,
"Unable to insert styled string: " + ex.getMessage());
}
}
}
/**
* Stylises the specified string.
*
* @param strings The line to be stylised
*
* @return StyledDocument for the inputted strings
*/
public StyledDocument getStyledString(final String[] strings) {
final StyledDocument styledDoc = new DefaultStyledDocument();
addStyledString(styledDoc, strings);
return styledDoc;
}
/**
* Retrieves the styled String contained within the unstyled offsets
* specified. That is, the <code>from</code> and <code>to</code> arguments
* correspond to indexes in an unstyled version of the <code>styled</code>
* string. The unstyled indices are translated to offsets within the
* styled String, and the return value includes all text and control codes
* between those indices.
* <p>
* The index translation is left-biased; that is, the indices are translated
* to be as far left as they possibly can be. This means that the start of
* the string will include any control codes immediately preceeding the
* desired text, and the end will not include any trailing codes.
*
* @param styled The styled String to be operated on
* @param from The starting index in the unstyled string
* @param to The ending index in the unstyled string
* @return The corresponding text between the two indices
* @since 0.6.3
*/
public static String getStyledText(final String styled, final int from, final int to) {
final String unstyled = stipControlCodes(styled);
final String startBit = unstyled.substring(0, from);
final String middleBit = unstyled.substring(from, to);
int start = from;
while (!stipControlCodes(styled.substring(0, start)).equals(startBit)) {
start++;
}
int end = to + start - from;
while (!stipControlCodes(styled.substring(start, end)).equals(middleBit)) {
end++;
}
return styled.substring(start, end);
}
/**
* Applies the hyperlink styles and intelligent linking regexps to the
* target.
*
* @param string The string to be linked
* @return A copy of the string with hyperlinks marked up
*/
public String doLinks(final String string) {
String target = string;
final String prefixes = owner.getServer() == null ? null
: owner.getServer().getChannelPrefixes();
String target2 = target;
target = target.replaceAll(URL_REGEXP, CODE_HYPERLINK + "$0" + CODE_HYPERLINK);
if (prefixes != null) {
target = target.replaceAll(String.format(URL_CHANNEL, prefixes),
CODE_CHANNEL + "$0" + CODE_CHANNEL);
}
for (int j = 0; j < 5 && !target.equals(target2); j++) {
target2 = target;
target = target
.replaceAll(URL_INT1, "$1$3$2")
.replaceAll(URL_INT2, "$1$2$3$5$4")
.replaceAll(URL_INT3, "$1$2$4$3")
.replaceAll(URL_INT4, "$1$3$2");
}
return target;
}
/**
* Applies the smilie styles to the target.
*
* @param string The string to be smilified
* @return A copy of the string with smilies marked up
* @since 0.6.3m1
*/
public static String doSmilies(final String string) {
// TODO: read types from config. Check if they're enabled.
return string.replaceAll("(\\s|^):[\\\\/](?=\\s|$)", "$1" + CODE_SMILIE + ":/"
+ CODE_SMILIE);
}
/**
* Strips all recognised control codes from the input string.
* @param input the String to be stripped
* @return a copy of the input with control codes removed
*/
public static String stipControlCodes(final String input) {
return input.replaceAll("[" + CODE_BOLD + CODE_CHANNEL + CODE_FIXED
+ CODE_HYPERLINK + CODE_ITALIC + CODE_NEGATE + CODE_NICKNAME
+ CODE_SMILIE + CODE_STOP + CODE_UNDERLINE + "]|"
+ CODE_HEXCOLOUR + "([A-Za-z0-9]{6}(,[A-Za-z0-9]{6})?)?|"
+ CODE_COLOUR + "([0-9]{1,2}(,[0-9]{1,2})?)?", "")
.replaceAll(CODE_TOOLTIP + ".*?" + CODE_TOOLTIP + "(.*?)"
+ CODE_TOOLTIP, "$1");
}
/**
* Returns a substring of the input string such that no control codes are present
* in the output. If the returned value isn't the same as the input, then the
* character immediately after is a control character.
* @param input The string to read from
* @return A substring of the input containing no control characters
*/
public static String readUntilControl(final String input) {
int pos = input.length();
pos = checkChar(pos, input.indexOf(CODE_BOLD));
pos = checkChar(pos, input.indexOf(CODE_UNDERLINE));
pos = checkChar(pos, input.indexOf(CODE_STOP));
pos = checkChar(pos, input.indexOf(CODE_COLOUR));
pos = checkChar(pos, input.indexOf(CODE_HEXCOLOUR));
pos = checkChar(pos, input.indexOf(CODE_ITALIC));
pos = checkChar(pos, input.indexOf(CODE_FIXED));
pos = checkChar(pos, input.indexOf(CODE_HYPERLINK));
pos = checkChar(pos, input.indexOf(CODE_NICKNAME));
pos = checkChar(pos, input.indexOf(CODE_CHANNEL));
pos = checkChar(pos, input.indexOf(CODE_SMILIE));
pos = checkChar(pos, input.indexOf(CODE_NEGATE));
pos = checkChar(pos, input.indexOf(CODE_TOOLTIP));
return input.substring(0, pos);
}
/**
* Helper function used in readUntilControl. Checks if i is a valid index of
* the string (i.e., it's not -1), and then returns the minimum of pos and i.
* @param pos The current position in the string
* @param i The index of the first occurance of some character
* @return The new position (see implementation)
*/
private static int checkChar(final int pos, final int i) {
if (i < pos && i != -1) { return i; }
return pos;
}
/**
* Reads the first control character from the input string (and any arguments
* it takes), and applies it to the specified attribute set.
* @return The number of characters read as control characters
* @param string The string to read from
* @param attribs The attribute set that new attributes will be applied to
* @param isStart Whether this is at the start of the string or not
*/
private int readControlChars(final String string,
final SimpleAttributeSet attribs, final boolean isStart) {
final boolean isNegated = attribs.containsAttribute("NegateControl", Boolean.TRUE);
// Bold
if (string.charAt(0) == CODE_BOLD) {
if (!isNegated) {
toggleAttribute(attribs, StyleConstants.FontConstants.Bold);
}
return 1;
}
// Underline
if (string.charAt(0) == CODE_UNDERLINE) {
if (!isNegated) {
toggleAttribute(attribs, StyleConstants.FontConstants.Underline);
}
return 1;
}
// Italic
if (string.charAt(0) == CODE_ITALIC) {
if (!isNegated) {
toggleAttribute(attribs, StyleConstants.FontConstants.Italic);
}
return 1;
}
// Hyperlinks
if (string.charAt(0) == CODE_HYPERLINK) {
if (!isNegated) {
toggleURI(attribs);
}
if (attribs.getAttribute(IRCTextAttribute.HYPERLINK) == null) {
attribs.addAttribute(IRCTextAttribute.HYPERLINK,
readUntilControl(string.substring(1)));
} else {
attribs.removeAttribute(IRCTextAttribute.HYPERLINK);
}
return 1;
}
// Channel links
if (string.charAt(0) == CODE_CHANNEL) {
if (!isNegated) {
toggleChannel(attribs);
}
if (attribs.getAttribute(IRCTextAttribute.CHANNEL) == null) {
attribs.addAttribute(IRCTextAttribute.CHANNEL,
readUntilControl(string.substring(1)));
} else {
attribs.removeAttribute(IRCTextAttribute.CHANNEL);
}
return 1;
}
// Nickname links
if (string.charAt(0) == CODE_NICKNAME) {
if (attribs.getAttribute(IRCTextAttribute.NICKNAME) == null) {
attribs.addAttribute(IRCTextAttribute.NICKNAME,
readUntilControl(string.substring(1)));
} else {
attribs.removeAttribute(IRCTextAttribute.NICKNAME);
}
return 1;
}
// Fixed pitch
if (string.charAt(0) == CODE_FIXED) {
if (!isNegated) {
if (attribs.containsAttribute(StyleConstants.FontConstants.FontFamily, "monospaced")) {
attribs.removeAttribute(StyleConstants.FontConstants.FontFamily);
} else {
attribs.removeAttribute(StyleConstants.FontConstants.FontFamily);
attribs.addAttribute(StyleConstants.FontConstants.FontFamily, "monospaced");
}
}
return 1;
}
// Stop formatting
if (string.charAt(0) == CODE_STOP) {
if (!isNegated) {
resetAttributes(attribs);
}
return 1;
}
// Colours
if (string.charAt(0) == CODE_COLOUR) {
int count = 1;
// This isn't too nice!
if (string.length() > count && isInt(string.charAt(count))) {
int foreground = string.charAt(count) - '0';
count++;
if (string.length() > count && isInt(string.charAt(count))) {
foreground = foreground * 10 + (string.charAt(count) - '0');
count++;
}
foreground = foreground % 16;
if (!isNegated) {
setForeground(attribs, String.valueOf(foreground));
if (isStart) {
setDefaultForeground(attribs, String.valueOf(foreground));
}
}
// Now background
if (string.length() > count && string.charAt(count) == ','
&& string.length() > count + 1
&& isInt(string.charAt(count + 1))) {
int background = string.charAt(count + 1) - '0';
count += 2; // Comma and first digit
if (string.length() > count && isInt(string.charAt(count))) {
background = background * 10 + (string.charAt(count) - '0');
count++;
}
background = background % 16;
if (!isNegated) {
setBackground(attribs, String.valueOf(background));
if (isStart) {
setDefaultBackground(attribs, String.valueOf(background));
}
}
}
} else if (!isNegated) {
resetColour(attribs);
}
return count;
}
// Hex colours
if (string.charAt(0) == CODE_HEXCOLOUR) {
int count = 1;
if (hasHexString(string, 1)) {
if (!isNegated) {
setForeground(attribs, string.substring(1, 7).toUpperCase());
if (isStart) {
setDefaultForeground(attribs, string.substring(1, 7).toUpperCase());
}
}
count = count + 6;
if (string.length() == count) {
return count;
}
// Now for background
if (string.charAt(count) == ',' && hasHexString(string, count + 1)) {
count++;
if (!isNegated) {
setBackground(attribs, string.substring(count, count + 6).toUpperCase());
if (isStart) {
setDefaultBackground(attribs,
string.substring(count, count + 6).toUpperCase());
}
}
count += 6;
}
} else if (!isNegated) {
resetColour(attribs);
}
return count;
}
// Control code negation
if (string.charAt(0) == CODE_NEGATE) {
toggleAttribute(attribs, "NegateControl");
return 1;
}
// Smilies!!
if (string.charAt(0) == CODE_SMILIE) {
if (attribs.getAttribute(IRCTextAttribute.SMILEY) == null) {
final String smilie = readUntilControl(string.substring(1));
attribs.addAttribute(IRCTextAttribute.SMILEY, "smilie-" + smilie);
} else {
attribs.removeAttribute(IRCTextAttribute.SMILEY);
}
return 1;
}
// Tooltips
if (string.charAt(0) == CODE_TOOLTIP) {
if (attribs.getAttribute(IRCTextAttribute.TOOLTIP) == null) {
final int index = string.indexOf(CODE_TOOLTIP, 1);
if (index == -1) {
// Doesn't make much sense, let's ignore it!
return 1;
}
final String tooltip = string.substring(1, index);
attribs.addAttribute(IRCTextAttribute.TOOLTIP, tooltip);
return tooltip.length() + 2;
} else {
attribs.removeAttribute(IRCTextAttribute.TOOLTIP);
}
return 1;
}
return 0;
}
/**
* Determines if the specified character represents a single integer (i.e. 0-9).
* @param c The character to check
* @return True iff the character is in the range [0-9], false otherwise
*/
private static boolean isInt(final char c) {
return c >= '0' && c <= '9';
}
/**
* Determines if the specified character represents a single hex digit
* (i.e., 0-F).
* @param c The character to check
* @return True iff the character is in the range [0-F], false otherwise
*/
private static boolean isHex(final char c) {
return isInt(c) || (c >= 'A' && c <= 'F');
}
/**
* Determines if the specified string has a 6-digit hex string starting at
* the specified offset.
* @param input The string to check
* @param offset The offset to start at
* @return True iff there is a hex string preset at the offset
*/
private static boolean hasHexString(final String input, final int offset) {
// If the string's too short, it can't have a hex string
if (input.length() < offset + 6) {
return false;
}
boolean res = true;
for (int i = offset; i < 6 + offset; i++) {
res = res && isHex(input.toUpperCase(Locale.getDefault()).charAt(i));
}
return res;
}
/**
* Toggles the various channel link-related attributes.
*
* @param attribs The attributes to be modified.
*/
private void toggleChannel(final SimpleAttributeSet attribs) {
if (styleChannels) {
toggleLink(attribs, IRCTextAttribute.CHANNEL, channelColour);
}
}
/**
* Toggles the various hyperlink-related attributes.
*
* @param attribs The attributes to be modified.
*/
private void toggleURI(final SimpleAttributeSet attribs) {
if (styleURIs) {
toggleLink(attribs, IRCTextAttribute.HYPERLINK, uriColour);
}
}
/**
* Toggles the attributes for a link.
*
* @since 0.6.4
* @param attribs The attributes to modify
* @param attribute The attribute indicating whether the link is open or closed
* @param colour The colour to colour the link
*/
private void toggleLink(final SimpleAttributeSet attribs,
final IRCTextAttribute attribute, final Color colour) {
if (attribs.getAttribute(attribute) == null) {
// Add the hyperlink style
if (attribs.containsAttribute(StyleConstants.FontConstants.Underline, Boolean.TRUE)) {
attribs.addAttribute("restoreUnderline", Boolean.TRUE);
} else {
attribs.addAttribute(StyleConstants.FontConstants.Underline, Boolean.TRUE);
}
final Object foreground = attribs.getAttribute(StyleConstants.FontConstants.Foreground);
if (foreground != null) {
attribs.addAttribute("restoreColour", foreground);
attribs.removeAttribute(StyleConstants.FontConstants.Foreground);
}
attribs.addAttribute(StyleConstants.FontConstants.Foreground, colour);
} else {
// Remove the hyperlink style
if (attribs.containsAttribute("restoreUnderline", Boolean.TRUE)) {
attribs.removeAttribute("restoreUnderline");
} else {
attribs.removeAttribute(StyleConstants.FontConstants.Underline);
}
attribs.removeAttribute(StyleConstants.FontConstants.Foreground);
final Object foreground = attribs.getAttribute("restoreColour");
if (foreground != null) {
attribs.addAttribute(StyleConstants.FontConstants.Foreground, foreground);
attribs.removeAttribute("restoreColour");
}
}
}
/**
* Toggles the specified attribute. If the attribute exists in the attribute
* set, it is removed. Otherwise, it is added with a value of Boolean.True.
* @param attribs The attribute set to check
* @param attrib The attribute to toggle
*/
private static void toggleAttribute(final SimpleAttributeSet attribs,
final Object attrib) {
if (attribs.containsAttribute(attrib, Boolean.TRUE)) {
attribs.removeAttribute(attrib);
} else {
attribs.addAttribute(attrib, Boolean.TRUE);
}
}
/**
* Resets all attributes in the specified attribute list.
* @param attribs The attribute list whose attributes should be reset
*/
private static void resetAttributes(final SimpleAttributeSet attribs) {
if (attribs.containsAttribute(StyleConstants.FontConstants.Bold, Boolean.TRUE)) {
attribs.removeAttribute(StyleConstants.FontConstants.Bold);
}
if (attribs.containsAttribute(StyleConstants.FontConstants.Underline, Boolean.TRUE)) {
attribs.removeAttribute(StyleConstants.FontConstants.Underline);
}
if (attribs.containsAttribute(StyleConstants.FontConstants.Italic, Boolean.TRUE)) {
attribs.removeAttribute(StyleConstants.FontConstants.Italic);
}
if (attribs.containsAttribute(StyleConstants.FontConstants.FontFamily, "monospaced")) {
final Object defaultFont = attribs.getAttribute("DefaultFontFamily");
attribs.removeAttribute(StyleConstants.FontConstants.FontFamily);
attribs.addAttribute(StyleConstants.FontConstants.FontFamily, defaultFont);
}
resetColour(attribs);
}
/**
* Resets the colour attributes in the specified attribute set.
* @param attribs The attribute set whose colour attributes should be reset
*/
private static void resetColour(final SimpleAttributeSet attribs) {
if (attribs.isDefined(StyleConstants.Foreground)) {
attribs.removeAttribute(StyleConstants.Foreground);
}
if (attribs.isDefined("DefaultForeground")) {
attribs.addAttribute(StyleConstants.Foreground,
attribs.getAttribute("DefaultForeground"));
}
if (attribs.isDefined(StyleConstants.Background)) {
attribs.removeAttribute(StyleConstants.Background);
}
if (attribs.isDefined("DefaultBackground")) {
attribs.addAttribute(StyleConstants.Background,
attribs.getAttribute("DefaultBackground"));
}
}
/**
* Sets the foreground colour in the specified attribute set to the colour
* corresponding to the specified colour code or hex.
* @param attribs The attribute set to modify
* @param foreground The colour code/hex of the new foreground colour
*/
private static void setForeground(final SimpleAttributeSet attribs,
final String foreground) {
if (attribs.isDefined(StyleConstants.Foreground)) {
attribs.removeAttribute(StyleConstants.Foreground);
}
attribs.addAttribute(StyleConstants.Foreground, ColourManager.parseColour(foreground));
}
/**
* Sets the background colour in the specified attribute set to the colour
* corresponding to the specified colour code or hex.
* @param attribs The attribute set to modify
* @param background The colour code/hex of the new background colour
*/
private static void setBackground(final SimpleAttributeSet attribs,
final String background) {
if (attribs.isDefined(StyleConstants.Background)) {
attribs.removeAttribute(StyleConstants.Background);
}
attribs.addAttribute(StyleConstants.Background, ColourManager.parseColour(background));
}
/**
* Sets the default foreground colour (used after an empty ctrl+k or a ctrl+o).
* @param attribs The attribute set to apply this default on
* @param foreground The default foreground colour
*/
private static void setDefaultForeground(final SimpleAttributeSet attribs,
final String foreground) {
attribs.addAttribute("DefaultForeground", ColourManager.parseColour(foreground));
}
/**
* Sets the default background colour (used after an empty ctrl+k or a ctrl+o).
* @param attribs The attribute set to apply this default on
* @param background The default background colour
*/
private static void setDefaultBackground(final SimpleAttributeSet attribs,
final String background) {
attribs.addAttribute("DefaultBackground", ColourManager.parseColour(background));
}
/** {@inheritDoc} */
@Override
public void configChanged(final String domain, final String key) {
if ("stylelinks".equals(key)) {
styleURIs = owner.getConfigManager().getOptionBool("ui", "stylelinks");
} else if ("stylechannels".equals(key)) {
styleChannels = owner.getConfigManager().getOptionBool("ui", "stylechannels");
} else if ("linkcolour".equals(key)) {
uriColour = owner.getConfigManager().getOptionColour("ui", "linkcolour");
} else if ("channelcolour".equals(key)) {
channelColour = owner.getConfigManager().getOptionColour("ui", "channelcolour");
}
}
}
|
package com.ecyrd.jspwiki.plugin;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import org.apache.ecs.xhtml.*;
import org.apache.log4j.Logger;
import com.ecyrd.jspwiki.SearchResult;
import com.ecyrd.jspwiki.WikiContext;
import com.ecyrd.jspwiki.WikiEngine;
/**
* @author jalkanen
*
* @since
*/
public class Search implements WikiPlugin
{
static Logger log = Logger.getLogger(Search.class);
public static final String PARAM_QUERY = "query";
public static final String PARAM_SET = "set";
public static final String DEFAULT_SETNAME = "_defaultSet";
public static final String PARAM_MAX = "max";
/* (non-Javadoc)
* @see com.ecyrd.jspwiki.plugin.WikiPlugin#execute(com.ecyrd.jspwiki.WikiContext, java.util.Map)
*/
public String execute( WikiContext context, Map params ) throws PluginException
{
int maxItems = Integer.MAX_VALUE;
Collection results = null;
String queryString = (String)params.get( PARAM_QUERY );
String set = (String)params.get( PARAM_SET );
String max = (String)params.get( PARAM_MAX );
if( set == null ) set = DEFAULT_SETNAME;
if( max != null ) maxItems = Integer.parseInt( max );
if( queryString == null )
{
results = (Collection)context.getVariable( set );
}
else
{
results = doBasicQuery( context, queryString );
context.setVariable( set, results );
}
String res = "";
if( results != null )
{
res = renderResults( results, context, maxItems );
}
return res;
}
private Collection doBasicQuery( WikiContext context, String query )
{
log.info("Searching for string "+query);
Collection list = context.getEngine().findPages( query );
return list;
}
private String renderResults( Collection results, WikiContext context, int maxItems )
{
WikiEngine engine = context.getEngine();
table t = new table();
t.setBorder(0);
t.setCellPadding(4);
tr row = new tr();
t.addElement( row );
row.addElement( new th().setWidth("30%").setAlign("left").addElement("Page") );
row.addElement( new th().setAlign("left").addElement("Score"));
int idx = 0;
for( Iterator i = results.iterator(); i.hasNext() && idx++ <= maxItems; )
{
SearchResult sr = (SearchResult) i.next();
row = new tr();
td name = new td().setWidth("30%");
name.addElement( "<a href=\""+
context.getURL( WikiContext.VIEW, sr.getPage().getName() )+
"\">"+engine.beautifyTitle(sr.getPage().getName())+"</a>");
row.addElement( name );
row.addElement( new td().addElement(""+sr.getScore()));
t.addElement( row );
}
if( results.isEmpty() )
{
row = new tr();
row.addElement( new td().setColSpan(2).addElement( new b().addElement("No results")));
t.addElement(row);
}
return t.toString();
}
}
|
package com.googlecode.ant_deb_task;
import org.apache.tools.ant.*;
import org.apache.tools.ant.taskdefs.Tar;
import org.apache.tools.ant.types.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import java.security.MessageDigest;
public class Deb extends Task
{
private static final Pattern PACKAGE_NAME_PATTERN = Pattern.compile("[a-z0-9][a-z0-9+\\-.]+");
public static class Description extends ProjectComponent
{
private String _synopsis;
private String _extended = "";
public String getSynopsis ()
{
return _synopsis;
}
public void setSynopsis (String synopsis)
{
_synopsis = synopsis.trim ();
}
public void addText (String text)
{
_extended += text;
}
public String getExtended ()
{
return _extended;
}
public String getExtendedFormatted ()
{
StringBuffer buffer = new StringBuffer (_extended.length ());
String lines[] = _extended.split ("\n");
int start = 0;
for (int i = 0; i < lines.length; i++)
{
String line = lines[i].trim ();
if (line.length () > 0)
break;
start++;
}
int end = lines.length;
for (int i = lines.length - 1; i >= 0; i
{
String line = lines[i].trim ();
if (line.length () > 0)
break;
end
}
for (int i = start; i < end; i++)
{
String line = lines[i].trim ();
buffer.append (' ');
buffer.append (line.length () == 0 ? "." : line);
buffer.append ('\n');
}
buffer.deleteCharAt (buffer.length () - 1);
return buffer.toString ();
}
}
public static class Version extends ProjectComponent
{
private static final Pattern UPSTREAM_VERSION_PATTERN = Pattern.compile("[0-9][A-Za-z0-9+\\-.:]*");
private static final Pattern DEBIAN_VERSION_PATTERN = Pattern.compile("[A-Za-z0-9+\\-]+");
private int _epoch = 0;
private String _upstream;
private String _debian = "1";
public void setEpoch(int epoch)
{
_epoch = epoch;
}
public void setUpstream(String upstream)
{
_upstream = upstream.trim ();
if (!UPSTREAM_VERSION_PATTERN.matcher (_upstream).matches ())
throw new BuildException("Invalid upstream version number!");
}
public void setDebian(String debian)
{
_debian = debian.trim ();
if (!DEBIAN_VERSION_PATTERN.matcher (_debian).matches ())
throw new BuildException("Invalid debian version number!");
}
public String toString()
{
StringBuffer version = new StringBuffer();
if (_epoch > 0)
{
version.append(_epoch);
version.append(':');
}
else if (_upstream.indexOf(':') > -1)
throw new BuildException("Upstream version can contain colons only if epoch is specified!");
version.append(_upstream);
if (_debian.length() > 0)
{
version.append('-');
version.append(_debian);
}
else if (_upstream.indexOf('-') > -1)
throw new BuildException("Upstream version can contain hyphens only if debian version is specified!");
return version.toString();
}
}
public static class Maintainer extends ProjectComponent
{
private String _name;
private String _email;
public void setName (String name)
{
_name = name.trim ();
}
public void setEmail (String email)
{
_email = email.trim ();
}
public String toString()
{
if (_name == null || _name.length () == 0)
return _email;
StringBuffer buffer = new StringBuffer (_name);
buffer.append (" <");
buffer.append (_email);
buffer.append (">");
return buffer.toString ();
}
}
public static class Section extends EnumeratedAttribute
{
private static final String[] PREFIXES = new String[] {"", "contrib/", "non-free/"};
private static final String[] BASIC_SECTIONS = new String[] {"admin", "base", "comm", "devel", "doc", "editors", "electronics", "embedded", "games", "gnome", "graphics", "hamradio", "interpreters", "kde", "libs", "libdevel", "mail", "math", "misc", "net", "news", "oldlibs", "otherosfs", "perl", "python", "science", "shells", "sound", "tex", "text", "utils", "web", "x11"};
private List sections = new ArrayList (PREFIXES.length * BASIC_SECTIONS.length);
public Section ()
{
for (int i = 0; i < PREFIXES.length; i++)
{
String prefix = PREFIXES[i];
for (int j = 0; j < BASIC_SECTIONS.length; j++)
{
String basicSection = BASIC_SECTIONS[j];
sections.add (prefix + basicSection);
}
}
}
public String[] getValues ()
{
return (String[]) sections.toArray (new String[]{});
}
}
public static class Priority extends EnumeratedAttribute
{
public String[] getValues ()
{
return new String[] {"required", "important", "standard", "optional", "extra"};
}
}
private File _toDir;
private String _package;
private String _version;
private Deb.Version _versionObj;
private String _section;
private String _priority = "extra";
private String _architecture = "all";
private String _depends;
private String _preDepends;
private String _recommends;
private String _suggests;
private String _enhances;
private String _conflicts;
private String _maintainer;
private Deb.Maintainer _maintainerObj;
private Deb.Description _description;
private List _data = new ArrayList();
private File _tempFolder;
private long _installedSize = 0;
private SortedSet _dataFolders;
private static final Tar.TarCompressionMethod GZIP_COMPRESSION_METHOD = new Tar.TarCompressionMethod ();
static
{
GZIP_COMPRESSION_METHOD.setValue ("gzip");
}
public void setToDir (File toDir)
{
_toDir = toDir;
}
public void setPackage (String packageName)
{
if (!PACKAGE_NAME_PATTERN.matcher(packageName).matches())
throw new BuildException("Invalid package name!");
_package = packageName;
}
public void setVersion (String version)
{
_version = version;
}
public void setSection (Section section)
{
_section = section.getValue();
}
public void setPriority (Priority priority)
{
_priority = priority.getValue();
}
public void setArchitecture (String architecture)
{
_architecture = architecture;
}
public void setDepends (String depends)
{
_depends = depends;
}
public void setPreDepends (String preDepends)
{
_preDepends = preDepends;
}
public void setRecommends (String recommends)
{
_recommends = recommends;
}
public void setSuggests (String suggests)
{
_suggests = suggests;
}
public void setEnhances (String enhances)
{
_enhances = enhances;
}
public void setConflicts (String conflicts)
{
_conflicts = conflicts;
}
public void setMaintainer (String maintainer)
{
_maintainer = maintainer;
}
public void addDescription (Deb.Description description)
{
_description = description;
}
public void add (TarFileSet resourceCollection)
{
_data.add(resourceCollection);
}
public void addVersion(Deb.Version version)
{
_versionObj = version;
}
public void addMaintainer(Deb.Maintainer maintainer)
{
_maintainerObj = maintainer;
}
private void writeControlFile (File controlFile, long installedSize) throws FileNotFoundException
{
log ("Generating control file to: " + controlFile.getAbsolutePath (), Project.MSG_VERBOSE);
PrintWriter control = new PrintWriter (controlFile);
control.print ("Package: ");
control.println (_package);
control.print ("Version: ");
control.println (_version);
if (_section != null)
{
control.print ("Section: ");
control.println (_section);
}
if (_priority != null)
{
control.print ("Priority: ");
control.println (_priority);
}
control.print ("Architecture: ");
control.println (_architecture);
if (_depends != null)
{
control.print ("Depends: ");
control.println (_depends);
}
if (_preDepends != null)
{
control.print ("Pre-Depends: ");
control.println (_preDepends);
}
if (_recommends != null)
{
control.print ("Recommends: ");
control.println (_recommends);
}
if (_suggests != null)
{
control.print ("Suggests: ");
control.println (_suggests);
}
if (_enhances != null)
{
control.print ("Enhances: ");
control.println (_enhances);
}
if (_conflicts != null)
{
control.print ("Conflicts: ");
control.println (_conflicts);
}
if (installedSize > 0)
{
control.print ("Installed-Size: ");
control.println (installedSize / 1024L);
}
control.print ("Maintainer: ");
control.println (_maintainer);
control.print ("Description: ");
control.println (_description.getSynopsis ());
control.println (_description.getExtendedFormatted ());
control.close ();
}
private File createMasterControlFile () throws IOException
{
File controlFile = new File (_tempFolder, "control");
writeControlFile (controlFile, _installedSize);
File md5sumsFile = new File (_tempFolder, "md5sums");
File masterControlFile = new File (_tempFolder, "control.tar.gz");
Tar controlTar = new Tar ();
controlTar.setProject (getProject ());
controlTar.setTaskName (getTaskName ());
controlTar.setDestFile (masterControlFile);
controlTar.setCompression (GZIP_COMPRESSION_METHOD);
addFileToTar (controlTar, controlFile, "control");
addFileToTar (controlTar, md5sumsFile, "md5sums");
controlTar.perform ();
controlFile.delete ();
return masterControlFile;
}
private void addFileToTar(Tar tar, File file, String fullpath)
{
TarFileSet controlFileSet = tar.createTarFileSet ();
controlFileSet.setFile (file);
controlFileSet.setFullpath (fullpath);
}
public void execute () throws BuildException
{
try
{
if (_versionObj != null)
_version = _versionObj.toString ();
if (_maintainerObj != null)
_maintainer = _maintainerObj.toString ();
_tempFolder = createTempFolder();
scanData ();
File debFile = new File (_toDir, _package + "_" + _version + "_" + _architecture + ".deb");
File dataFile = createDataFile ();
File masterControlFile = createMasterControlFile ();
log ("Writing deb file to: " + debFile.getAbsolutePath());
BuildDeb.buildDeb (debFile, masterControlFile, dataFile);
masterControlFile.delete ();
dataFile.delete ();
}
catch (IOException e)
{
throw new BuildException (e);
}
}
private File createDataFile () throws IOException
{
File dataFile = new File (_tempFolder, "data.tar.gz");
Tar dataTar = new Tar ();
dataTar.setProject (getProject ());
dataTar.setTaskName (getTaskName ());
dataTar.setDestFile (dataFile);
dataTar.setCompression (GZIP_COMPRESSION_METHOD);
// add folders
for (Iterator dataFoldersIter = _dataFolders.iterator (); dataFoldersIter.hasNext ();)
{
String targetFolder = (String) dataFoldersIter.next ();
TarFileSet targetFolderSet = dataTar.createTarFileSet ();
targetFolderSet.setFile (_tempFolder);
targetFolderSet.setFullpath (targetFolder);
}
// add actual data
for (int i = 0; i < _data.size (); i++)
dataTar.add ((TarFileSet) _data.get (i));
dataTar.execute ();
return dataFile;
}
private File createTempFolder() throws IOException
{
File tempFile = File.createTempFile ("deb", ".dir");
String tempFolderName = tempFile.getAbsolutePath ();
tempFile.delete ();
tempFile = new File (tempFolderName, "removeme");
tempFile.mkdirs ();
tempFile.delete ();
log ("Temp folder: " + tempFolderName, Project.MSG_VERBOSE);
return new File (tempFolderName);
}
private void scanData()
{
try
{
Set existingDirs = new HashSet ();
_installedSize = 0;
PrintStream md5sums = new PrintStream (new FileOutputStream (new File (_tempFolder, "md5sums")));
_dataFolders = new TreeSet ();
Iterator filesets = _data.iterator();
while (filesets.hasNext())
{
TarFileSet fileset = (TarFileSet) filesets.next();
String fullPath = fileset.getFullpath (getProject ());
String prefix = fileset.getPrefix (getProject ());
if (prefix.length () > 0 && !prefix.endsWith ("/"))
prefix += '/';
String [] fileNames = getFileNames(fileset);
for (int i = 0; i < fileNames.length; i++)
{
String targetName;
String fileName = fileNames[i];
File file = new File (fileset.getDir (getProject ()), fileName);
if (fullPath.length () > 0)
targetName = fullPath;
else
targetName = prefix + fileName;
if (file.isDirectory ())
{
log ("existing dir: " + targetName, Project.MSG_DEBUG);
existingDirs.add (targetName);
}
else
{
// calculate installed size in bytes
_installedSize += file.length ();
// calculate and collect md5 sums
md5sums.print (getFileMd5 (file));
md5sums.print (' ');
md5sums.println (targetName.replace (File.separatorChar, '/'));
// get target folder names, and collect them (to be added to _data)
File targetFile = new File(targetName);
File parentFolder = targetFile.getParentFile () ;
while (parentFolder != null)
{
String parentFolderPath = parentFolder.getPath ();
if (!existingDirs.contains (parentFolderPath) && !_dataFolders.contains (parentFolderPath))
{
log ("adding dir: " + parentFolderPath + " for " + targetName, Project.MSG_DEBUG);
_dataFolders.add (parentFolderPath);
}
parentFolder = parentFolder.getParentFile ();
}
}
}
}
for (Iterator iterator = existingDirs.iterator (); iterator.hasNext ();)
{
String existingDir = (String) iterator.next ();
if (_dataFolders.contains (existingDir))
{
log ("removing existing dir " + existingDir, Project.MSG_DEBUG);
_dataFolders.remove (existingDir);
}
}
md5sums.close ();
}
catch (Exception e)
{
throw new BuildException (e);
}
}
private String[] getFileNames(FileSet fs)
{
DirectoryScanner ds = fs.getDirectoryScanner(fs.getProject());
String[] directories = ds.getIncludedDirectories();
String[] filesPerSe = ds.getIncludedFiles();
String[] files = new String [directories.length + filesPerSe.length];
System.arraycopy(directories, 0, files, 0, directories.length);
System.arraycopy(filesPerSe, 0, files, directories.length, filesPerSe.length);
return files;
}
private String getFileMd5(File file)
{
try
{
MessageDigest md5 = MessageDigest.getInstance ("MD5");
FileInputStream inputStream = new FileInputStream (file);
byte[] buffer = new byte[1024];
while (true)
{
int read = inputStream.read (buffer);
if (read == -1)
break;
md5.update (buffer, 0, read);
}
byte[] md5Bytes = md5.digest ();
StringBuffer md5Buffer = new StringBuffer (md5Bytes.length * 2);
for (int i = 0; i < md5Bytes.length; i++)
{
String hex = Integer.toHexString (md5Bytes[i] & 0x00ff);
if (hex.length () == 1)
md5Buffer.append ('0');
md5Buffer.append (hex);
}
return md5Buffer.toString ();
}
catch (Exception e)
{
throw new BuildException(e);
}
}
}
|
package com.googlecode.ant_deb_task;
import org.apache.tools.ant.*;
import org.apache.tools.ant.taskdefs.Tar;
import org.apache.tools.ant.types.*;
import org.apache.tools.tar.TarOutputStream;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import java.util.zip.*;
import java.security.MessageDigest;
import java.net.URL;
import java.net.MalformedURLException;
/**
* Task that creates a Debian package.
*
* @antTaskName deb
*/
public class Deb extends Task
{
private static final Pattern PACKAGE_NAME_PATTERN = Pattern.compile("[a-z0-9][a-z0-9+\\-.]+");
public static class Description extends ProjectComponent
{
private String _synopsis;
private String _extended = "";
public String getSynopsis ()
{
return _synopsis;
}
public void setSynopsis (String synopsis)
{
_synopsis = synopsis.trim ();
}
public void addText (String text)
{
_extended += getProject ().replaceProperties (text);
}
public String getExtended ()
{
return _extended;
}
public String getExtendedFormatted ()
{
StringBuffer buffer = new StringBuffer (_extended.length ());
String lines[] = _extended.split ("\n");
int start = 0;
for (int i = 0; i < lines.length; i++)
{
String line = lines[i].trim ();
if (line.length () > 0)
break;
start++;
}
int end = lines.length;
for (int i = lines.length - 1; i >= 0; i
{
String line = lines[i].trim ();
if (line.length () > 0)
break;
end
}
for (int i = start; i < end; i++)
{
String line = lines[i].trim ();
buffer.append (' ');
buffer.append (line.length () == 0 ? "." : line);
buffer.append ('\n');
}
buffer.deleteCharAt (buffer.length () - 1);
return buffer.toString ();
}
}
public static class Version extends ProjectComponent
{
private static final Pattern UPSTREAM_VERSION_PATTERN = Pattern.compile("[0-9][A-Za-z0-9+\\-.:]*");
private static final Pattern DEBIAN_VERSION_PATTERN = Pattern.compile("[A-Za-z0-9+\\-]+");
private int _epoch = 0;
private String _upstream;
private String _debian = "1";
public void setEpoch(int epoch)
{
_epoch = epoch;
}
public void setUpstream(String upstream)
{
_upstream = upstream.trim ();
if (!UPSTREAM_VERSION_PATTERN.matcher (_upstream).matches ())
throw new BuildException("Invalid upstream version number!");
}
public void setDebian(String debian)
{
_debian = debian.trim ();
if (!DEBIAN_VERSION_PATTERN.matcher (_debian).matches ())
throw new BuildException("Invalid debian version number!");
}
public String toString()
{
StringBuffer version = new StringBuffer();
if (_epoch > 0)
{
version.append(_epoch);
version.append(':');
}
else if (_upstream.indexOf(':') > -1)
throw new BuildException("Upstream version can contain colons only if epoch is specified!");
version.append(_upstream);
if (_debian.length() > 0)
{
version.append('-');
version.append(_debian);
}
else if (_upstream.indexOf('-') > -1)
throw new BuildException("Upstream version can contain hyphens only if debian version is specified!");
return version.toString();
}
}
public static class Maintainer extends ProjectComponent
{
private String _name;
private String _email;
public void setName (String name)
{
_name = name.trim ();
}
public void setEmail (String email)
{
_email = email.trim ();
}
public String toString()
{
if (_name == null || _name.length () == 0)
return _email;
StringBuffer buffer = new StringBuffer (_name);
buffer.append (" <");
buffer.append (_email);
buffer.append (">");
return buffer.toString ();
}
}
public static class Changelog extends ProjectComponent
{
public static class Format extends EnumeratedAttribute
{
public String[] getValues ()
{
// XML format will be added when supported
return new String[] {"plain" /* , "xml" */};
}
}
private static final String STANDARD_FILENAME = "changelog.gz";
private static final String DEBIAN_FILENAME = "changelog.Debian.gz";
private String _file;
private Changelog.Format _format;
private boolean _debian;
public Changelog()
{
_debian = false;
_format = new Changelog.Format();
_format.setValue("plain");
}
public void setFile (String file)
{
_file = file.trim ();
}
public String getFile()
{
return _file;
}
public void setFormat (Changelog.Format format)
{
_format = format;
}
public Changelog.Format getFormat()
{
return _format;
}
public void setDebian (boolean debian)
{
_debian = debian;
}
public boolean isDebian ()
{
return _debian;
}
public String getTargetFilename ()
{
return _debian ? DEBIAN_FILENAME : STANDARD_FILENAME;
}
}
public static class Section extends EnumeratedAttribute
{
private static final String[] PREFIXES = new String[] {"", "contrib/", "non-free/"};
private static final String[] BASIC_SECTIONS = new String[] {"admin", "base", "comm", "devel", "doc", "editors", "electronics", "embedded", "games", "gnome", "graphics", "hamradio", "interpreters", "kde", "libs", "libdevel", "mail", "math", "misc", "net", "news", "oldlibs", "otherosfs", "perl", "python", "science", "shells", "sound", "tex", "text", "utils", "web", "x11"};
private List sections = new ArrayList (PREFIXES.length * BASIC_SECTIONS.length);
public Section ()
{
for (int i = 0; i < PREFIXES.length; i++)
{
String prefix = PREFIXES[i];
for (int j = 0; j < BASIC_SECTIONS.length; j++)
{
String basicSection = BASIC_SECTIONS[j];
sections.add (prefix + basicSection);
}
}
}
public String[] getValues ()
{
return (String[]) sections.toArray (new String[sections.size()]);
}
}
public static class Priority extends EnumeratedAttribute
{
public String[] getValues ()
{
return new String[] {"required", "important", "standard", "optional", "extra"};
}
}
private File _toDir;
private String _debFilenameProperty = "";
private String _package;
private String _version;
private Deb.Version _versionObj;
private String _section;
private String _priority = "extra";
private String _architecture = "all";
private String _depends;
private String _preDepends;
private String _recommends;
private String _suggests;
private String _enhances;
private String _conflicts;
private String _provides;
private String _maintainer;
private URL _homepage;
private Deb.Maintainer _maintainerObj;
private Deb.Description _description;
private Set _conffiles = new HashSet ();
private Set _changelogs = new HashSet ();
private List _data = new ArrayList();
private File _preinst;
private File _postinst;
private File _prerm;
private File _postrm;
private File _config;
private File _templates;
private File _tempFolder;
private long _installedSize = 0;
private SortedSet _dataFolders;
private static final Tar.TarCompressionMethod GZIP_COMPRESSION_METHOD = new Tar.TarCompressionMethod ();
private static final Tar.TarLongFileMode GNU_LONGFILE_MODE = new Tar.TarLongFileMode ();
static
{
GZIP_COMPRESSION_METHOD.setValue ("gzip");
GNU_LONGFILE_MODE.setValue(Tar.TarLongFileMode.GNU);
}
public void setToDir (File toDir)
{
_toDir = toDir;
}
public void setDebFilenameProperty(String debFilenameProperty)
{
_debFilenameProperty = debFilenameProperty.trim();
}
public void setPackage (String packageName)
{
if (!PACKAGE_NAME_PATTERN.matcher(packageName).matches())
throw new BuildException("Invalid package name!");
_package = packageName;
}
public void setVersion (String version)
{
_version = version;
}
public void setSection (Section section)
{
_section = section.getValue();
}
public void setPriority (Priority priority)
{
_priority = priority.getValue();
}
public void setArchitecture (String architecture)
{
_architecture = architecture;
}
public void setDepends (String depends)
{
_depends = depends;
}
public void setPreDepends (String preDepends)
{
_preDepends = preDepends;
}
public void setRecommends (String recommends)
{
_recommends = recommends;
}
public void setSuggests (String suggests)
{
_suggests = suggests;
}
public void setEnhances (String enhances)
{
_enhances = enhances;
}
public void setConflicts (String conflicts)
{
_conflicts = conflicts;
}
public void setProvides (String provides)
{
_provides = provides;
}
public void setMaintainer (String maintainer)
{
_maintainer = maintainer;
}
public void setHomepage (String homepage)
{
try
{
_homepage = new URL (homepage);
}
catch (MalformedURLException e)
{
throw new BuildException ("Invalid homepage, must be a URL: " + homepage, e);
}
}
public void setPreinst (File preinst)
{
_preinst = preinst;
}
public void setPostinst (File postinst)
{
_postinst = postinst;
}
public void setPrerm (File prerm)
{
_prerm = prerm;
}
public void setPostrm (File postrm)
{
_postrm = postrm;
}
public void setConfig (File config)
{
_config = config;
}
public void setTemplates (File templates)
{
_templates = templates;
}
public void addConfFiles (TarFileSet conffiles)
{
_conffiles.add (conffiles);
_data.add (conffiles);
}
public void addChangelog(Deb.Changelog changelog)
{
_changelogs.add (changelog);
}
public void addDescription (Deb.Description description)
{
_description = description;
}
public void add (TarFileSet resourceCollection)
{
_data.add(resourceCollection);
}
public void addVersion(Deb.Version version)
{
_versionObj = version;
}
public void addMaintainer(Deb.Maintainer maintainer)
{
_maintainerObj = maintainer;
}
private void writeControlFile (File controlFile, long installedSize) throws FileNotFoundException
{
log ("Generating control file to: " + controlFile.getAbsolutePath (), Project.MSG_VERBOSE);
PrintWriter control = new UnixPrintWriter (controlFile);
control.print ("Package: ");
control.println (_package);
control.print ("Version: ");
control.println (_version);
if (_section != null)
{
control.print ("Section: ");
control.println (_section);
}
if (_priority != null)
{
control.print ("Priority: ");
control.println (_priority);
}
control.print ("Architecture: ");
control.println (_architecture);
if (_depends != null)
{
control.print ("Depends: ");
control.println (_depends);
}
if (_preDepends != null)
{
control.print ("Pre-Depends: ");
control.println (_preDepends);
}
if (_recommends != null)
{
control.print ("Recommends: ");
control.println (_recommends);
}
if (_suggests != null)
{
control.print ("Suggests: ");
control.println (_suggests);
}
if (_enhances != null)
{
control.print ("Enhances: ");
control.println (_enhances);
}
if (_conflicts != null)
{
control.print ("Conflicts: ");
control.println (_conflicts);
}
if (_provides != null)
{
control.print ("Provides: ");
control.println (_provides);
}
if (installedSize > 0)
{
control.print ("Installed-Size: ");
control.println (installedSize / 1024L);
}
control.print ("Maintainer: ");
control.println (_maintainer);
if (_homepage != null)
{
control.print ("Homepage: ");
control.println(_homepage.toExternalForm());
}
control.print ("Description: ");
control.println (_description.getSynopsis ());
control.println (_description.getExtendedFormatted ());
control.close ();
}
private File createMasterControlFile () throws IOException
{
File controlFile = new File (_tempFolder, "control");
writeControlFile (controlFile, _installedSize);
File md5sumsFile = new File (_tempFolder, "md5sums");
File conffilesFile = new File (_tempFolder, "conffiles");
File masterControlFile = new File (_tempFolder, "control.tar.gz");
Tar controlTar = new Tar ();
controlTar.setProject (getProject ());
controlTar.setTaskName (getTaskName ());
controlTar.setDestFile (masterControlFile);
controlTar.setCompression (GZIP_COMPRESSION_METHOD);
addFileToTar (controlTar, controlFile, "control", "644");
addFileToTar (controlTar, md5sumsFile, "md5sums", "644");
if (conffilesFile.length () > 0)
addFileToTar (controlTar, conffilesFile, "conffiles", "644");
if (_preinst != null)
addFileToTar (controlTar, _preinst, "preinst", "755");
if (_postinst != null)
addFileToTar (controlTar, _postinst, "postinst", "755");
if (_prerm != null)
addFileToTar (controlTar, _prerm, "prerm", "755");
if (_postrm != null)
addFileToTar (controlTar, _postrm, "postrm", "755");
if (_config != null)
addFileToTar (controlTar, _config, "config", "755");
if (_templates != null)
addFileToTar (controlTar, _templates, "templates", "644");
controlTar.perform ();
controlFile.delete ();
return masterControlFile;
}
private void addFileToTar(Tar tar, File file, String fullpath, String fileMode)
{
TarFileSet controlFileSet = tar.createTarFileSet ();
controlFileSet.setFile (file);
controlFileSet.setFullpath ("./" + fullpath);
controlFileSet.setFileMode (fileMode);
controlFileSet.setUserName ("root");
controlFileSet.setGroup ("root");
}
public void execute () throws BuildException
{
try
{
if (_versionObj != null)
_version = _versionObj.toString ();
if (_maintainerObj != null)
_maintainer = _maintainerObj.toString ();
_tempFolder = createTempFolder();
processChangelogs ();
scanData ();
File debFile = new File (_toDir, _package + "_" + _version + "_" + _architecture + ".deb");
File dataFile = createDataFile ();
File masterControlFile = createMasterControlFile ();
log ("Writing deb file to: " + debFile.getAbsolutePath());
BuildDeb.buildDeb (debFile, masterControlFile, dataFile);
if (_debFilenameProperty.length() > 0)
getProject().setProperty(_debFilenameProperty, debFile.getAbsolutePath());
masterControlFile.delete ();
dataFile.delete ();
}
catch (IOException e)
{
throw new BuildException (e);
}
}
private File createDataFile () throws IOException
{
File dataFile = new File (_tempFolder, "data.tar.gz");
Tar dataTar = new Tar ();
dataTar.setProject (getProject ());
dataTar.setTaskName (getTaskName ());
dataTar.setDestFile (dataFile);
dataTar.setCompression (GZIP_COMPRESSION_METHOD);
dataTar.setLongfile(GNU_LONGFILE_MODE);
if ( _data.size () > 0 )
{
// add folders
for (Iterator dataFoldersIter = _dataFolders.iterator (); dataFoldersIter.hasNext ();)
{
String targetFolder = (String) dataFoldersIter.next ();
TarFileSet targetFolderSet = dataTar.createTarFileSet ();
targetFolderSet.setFile (_tempFolder);
targetFolderSet.setFullpath (targetFolder);
targetFolderSet.setUserName ("root");
targetFolderSet.setGroup ("root");
}
// add actual data
for (int i = 0; i < _data.size (); i++)
{
TarFileSet data = (TarFileSet) _data.get (i);
if (data.getUserName() == null || data.getUserName().trim().length() == 0)
data.setUserName ("root");
if (data.getGroup() == null || data.getGroup().trim().length() == 0)
data.setGroup ("root");
dataTar.add (data);
}
dataTar.execute ();
}
else
{
// create an empty data.tar.gz file which is still a valid tar
TarOutputStream tarStream = new TarOutputStream(
new GZipOutputStream(
new BufferedOutputStream(new FileOutputStream(dataFile)),
Deflater.BEST_COMPRESSION
)
);
tarStream.close();
}
return dataFile;
}
private File createTempFolder() throws IOException
{
File tempFile = File.createTempFile ("deb", ".dir");
String tempFolderName = tempFile.getAbsolutePath ();
tempFile.delete ();
tempFile = new File (tempFolderName, "removeme");
tempFile.mkdirs ();
tempFile.delete ();
log ("Temp folder: " + tempFolderName, Project.MSG_VERBOSE);
return new File (tempFolderName);
}
private void scanData()
{
try
{
Set existingDirs = new HashSet ();
_installedSize = 0;
PrintWriter md5sums = new UnixPrintWriter (new File (_tempFolder, "md5sums"));
PrintWriter conffiles = new UnixPrintWriter (new File (_tempFolder, "conffiles"));
_dataFolders = new TreeSet ();
Iterator filesets = _data.iterator();
while (filesets.hasNext())
{
TarFileSet fileset = (TarFileSet) filesets.next();
normalizeTargetFolder(fileset);
String fullPath = fileset.getFullpath (getProject ());
String prefix = fileset.getPrefix (getProject ());
String [] fileNames = getFileNames(fileset);
for (int i = 0; i < fileNames.length; i++)
{
String targetName;
String fileName = fileNames[i];
File file = new File (fileset.getDir (getProject ()), fileName);
if (fullPath.length () > 0)
targetName = fullPath;
else
targetName = prefix + fileName;
if (file.isDirectory ())
{
log ("existing dir: " + targetName, Project.MSG_DEBUG);
existingDirs.add (targetName);
}
else
{
// calculate installed size in bytes
_installedSize += file.length ();
// calculate and collect md5 sums
md5sums.print (getFileMd5 (file));
md5sums.print (' ');
md5sums.println (targetName.substring(2));
// get target folder names, and collect them (to be added to _data)
File targetFile = new File(targetName);
File parentFolder = targetFile.getParentFile ();
while (parentFolder != null)
{
String parentFolderPath = parentFolder.getPath ();
if (".".equals(parentFolderPath))
parentFolderPath = "./";
if (!existingDirs.contains (parentFolderPath) && !_dataFolders.contains (parentFolderPath))
{
log ("adding dir: " + parentFolderPath + " for " + targetName, Project.MSG_DEBUG);
_dataFolders.add (parentFolderPath);
}
parentFolder = parentFolder.getParentFile ();
}
// write conffiles
if (_conffiles.contains (fileset))
conffiles.println (targetName.substring(2));
}
}
}
for (Iterator iterator = existingDirs.iterator (); iterator.hasNext ();)
{
String existingDir = (String) iterator.next ();
if (_dataFolders.contains (existingDir))
{
log ("removing existing dir " + existingDir, Project.MSG_DEBUG);
_dataFolders.remove (existingDir);
}
}
md5sums.close ();
conffiles.close ();
}
catch (Exception e)
{
throw new BuildException (e);
}
}
private void normalizeTargetFolder(TarFileSet fileset)
{
String fullPath = fileset.getFullpath (getProject ());
String prefix = fileset.getPrefix (getProject ());
if (fullPath.length() > 0)
{
if (fullPath.startsWith("/"))
fullPath = "." + fullPath;
else if (!fullPath.startsWith("./"))
fullPath = "./" + fullPath;
fileset.setFullpath(fullPath.replace('\\', '/'));
}
if (prefix.length() > 0)
{
if (!prefix.endsWith ("/"))
prefix += '/';
if (prefix.startsWith("/"))
prefix = "." + prefix;
else if (!prefix.startsWith("./"))
prefix = "./" + prefix;
fileset.setPrefix(prefix.replace('\\', '/'));
}
}
private String[] getFileNames(FileSet fs)
{
DirectoryScanner ds = fs.getDirectoryScanner(fs.getProject());
String[] directories = ds.getIncludedDirectories();
String[] filesPerSe = ds.getIncludedFiles();
String[] files = new String [directories.length + filesPerSe.length];
System.arraycopy(directories, 0, files, 0, directories.length);
System.arraycopy(filesPerSe, 0, files, directories.length, filesPerSe.length);
return files;
}
private String getFileMd5(File file)
{
try
{
MessageDigest md5 = MessageDigest.getInstance ("MD5");
FileInputStream inputStream = new FileInputStream (file);
byte[] buffer = new byte[1024];
while (true)
{
int read = inputStream.read (buffer);
if (read == -1)
break;
md5.update (buffer, 0, read);
}
inputStream.close();
byte[] md5Bytes = md5.digest ();
StringBuffer md5Buffer = new StringBuffer (md5Bytes.length * 2);
for (int i = 0; i < md5Bytes.length; i++)
{
String hex = Integer.toHexString (md5Bytes[i] & 0x00ff);
if (hex.length () == 1)
md5Buffer.append ('0');
md5Buffer.append (hex);
}
return md5Buffer.toString ();
}
catch (Exception e)
{
throw new BuildException(e);
}
}
private void processChangelogs() throws IOException
{
for (Iterator iter = _changelogs.iterator (); iter.hasNext (); )
{
processChangelog ((Deb.Changelog) iter.next ());
}
}
private void processChangelog (Deb.Changelog changelog) throws IOException
{
// Compress file
File file = new File(changelog.getFile ());
File temp = File.createTempFile ("changelog", ".gz");
gzip(file, temp, Deflater.BEST_COMPRESSION, GZipOutputStream.FS_UNIX);
// Determine path
StringBuffer path = new StringBuffer ("usr/share/doc/");
path.append (_package).append ('/');
path.append (changelog.getTargetFilename ());
// Add file to data
TarFileSet fileSet = new TarFileSet ();
fileSet.setProject (getProject ());
fileSet.setFullpath (path.toString ());
fileSet.setFile (temp);
fileSet.setFileMode ("0644");
_data.add (fileSet);
}
private static void gzip (File input, File output, int level, byte fileSystem)
throws IOException
{
GZipOutputStream out = null;
InputStream in = null;
try
{
out = new GZipOutputStream (new FileOutputStream (output), level);
out.setFileSystem (fileSystem);
in = new FileInputStream(input);
byte[] buffer = new byte[8 * 1024];
int len;
while ((len = in.read (buffer, 0, buffer.length)) > 0)
{
out.write(buffer, 0, len);
}
out.finish ();
}
finally
{
if (in != null)
{
in.close ();
}
if (out != null)
{
out.close ();
}
}
}
}
|
// vim: et sw=4 sts=4 tabstop=4
package com.issc.ui;
import com.issc.Bluebit;
import com.issc.data.BLEDevice;
import com.issc.R;
import com.issc.util.Log;
import com.issc.util.Util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.samsung.android.sdk.bt.gatt.BluetoothGatt;
import com.samsung.android.sdk.bt.gatt.BluetoothGattAdapter;
import com.samsung.android.sdk.bt.gatt.BluetoothGattCallback;
public class ActivityDevicesList extends Activity implements
BluetoothProfile.ServiceListener {
private ListView mListView;
private Button mBtnScan;
private BroadcastReceiver mReceiver;
private ProgressDialog mScanningDialog;
private BaseAdapter mAdapter;
private List<Map<String, Object>> mRecords;
private List<BLEDevice> mDevices;
private final static String sName = "_name";
private final static String sAddr = "_address";
private final static String sSavedDevices = "_devices_info_in_bundle";
private final static int SCAN_DIALOG = 1;
private final static int MENU_DETAIL = 0;
private final static int MENU_CHOOSE = 1;
private BluetoothGatt mGatt;
private BluetoothGattCallback mCallback;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_devices_list);
mBtnScan = (Button) findViewById(R.id.btn_scan);
mListView = (ListView) findViewById(R.id.devices_list);
mReceiver = new ActionReceiver();
mListView.setOnItemClickListener(new ItemClickListener());
registerForContextMenu(mListView);
mCallback = new GattCallback();
initAdapter();
}
private void initAdapter() {
String[] from = {sName, sAddr};
int[] to = {R.id.row_title, R.id.row_description};
mRecords = new ArrayList<Map<String, Object>>();
mDevices = new ArrayList<BLEDevice>();
mAdapter = new SimpleAdapter(
this,
mRecords,
R.layout.row_device,
from,
to
);
mListView.setAdapter(mAdapter);
mListView.setEmptyView(findViewById(R.id.empty));
}
@Override
public void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
this.registerReceiver(mReceiver, filter);
}
@Override
public void onStop() {
super.onStop();
unregisterReceiver(mReceiver);
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
protected void onResume() {
super.onResume();
BluetoothGattAdapter.getProfileProxy(this, this,
BluetoothGattAdapter.GATT);
}
@Override
protected void onPause() {
super.onPause();
BluetoothGattAdapter.closeProfileProxy(BluetoothGattAdapter.GATT,
mGatt);
}
@Override
protected void onSaveInstanceState(Bundle b) {
super.onSaveInstanceState(b);
ArrayList<BLEDevice> devices;
/* cache scanned results if Activity being rotated */
if (mDevices.size() > 0) {
devices = new ArrayList<BLEDevice>(mDevices);
b.putParcelableArrayList(sSavedDevices, devices);
}
}
@Override
protected void onRestoreInstanceState(Bundle b) {
super.onRestoreInstanceState(b);
ArrayList<BLEDevice> devices;
/* restore scanned results if any */
devices = b.getParcelableArrayList(sSavedDevices);
if (devices != null) {
for (int i = 0; i < devices.size(); i++) {
appendDevice(devices.get(i).getDevice());
}
}
}
public void onClickBtnScan(View v) {
if (Util.isBluetoothEnabled()) {
startDiscovery();
} else {
Log.d("Trying to enable Bluetooth");
Util.enableBluetooth(this, 0);
}
}
@Override
protected Dialog onCreateDialog(int id, Bundle args) {
if (id == SCAN_DIALOG) {
mScanningDialog = new ProgressDialog(this);
mScanningDialog.setMessage(this.getString(R.string.scanning));
mScanningDialog.setOnCancelListener(new Dialog.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
stopDiscovery();
}
});
return mScanningDialog;
}
return null;
}
@Override
protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
if (id == SCAN_DIALOG) {
}
}
@Override
public void onCreateContextMenu(ContextMenu menu,
View v,
ContextMenuInfo info) {
super.onCreateContextMenu(menu, v, info);
if (v == mListView) {
menu.setHeaderTitle(R.string.device_menu_title);
menu.add(0, MENU_DETAIL, Menu.NONE, R.string.device_menu_detail);
menu.add(0, MENU_CHOOSE, Menu.NONE, R.string.device_menu_choose);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int pos = info.position;
int id = item.getItemId();
if (id == MENU_DETAIL) {
Intent i = new Intent(this, ActivityDeviceDetail.class);
i.putExtra(Bluebit.CHOSEN_DEVICE, mDevices.get(pos));
startActivity(i);
} else if (id == MENU_CHOOSE) {
Intent i = new Intent(this, ActivityFunctionPicker.class);
i.putExtra(Bluebit.CHOSEN_DEVICE, mDevices.get(pos));
startActivity(i);
}
return true;
}
private void startDiscovery() {
Log.d("Scanning Devices");
mRecords.clear();
mDevices.clear();
showDialog(SCAN_DIALOG);
mAdapter.notifyDataSetChanged();
if (mGatt != null) {
mGatt.startScan();
} else {
Log.e("No Gatt instance");
}
}
private void stopDiscovery() {
Log.d("Stop scanning");
if (mGatt != null) {
mGatt.stopScan();
} else {
Log.e("No Gatt instance");
}
}
private void onFoundDevice(BluetoothDevice device) {
if (isInList(mRecords, device)) {
Log.d(device.getName() + " already be in list, skip it");
} else {
appendDevice(device);
}
}
private boolean isInList(List<Map<String, Object>> list, BluetoothDevice device) {
synchronized(list) {
Iterator<Map<String, Object>> it = list.iterator();
while(it.hasNext()) {
Map<String, Object> item = it.next();
if (item.get(sAddr).toString().equals(device.getAddress())) {
return true;
}
}
return false;
}
}
private void appendDevice(BluetoothDevice device) {
Map<String, Object> record = new HashMap<String, Object>();
record.put(sName, device.getName());
record.put(sAddr, device.getAddress());
mRecords.add(record);
mDevices.add(new BLEDevice(device));
this.runOnUiThread(new Runnable() {
public void run() {
mAdapter.notifyDataSetChanged();
}
});
}
class ItemClickListener implements OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent,
View view,
int position,
long id) {
view.showContextMenu();
}
}
class ActionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
onFoundDevice(device);
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
mScanningDialog.cancel();
}
}
}
@Override
public void onServiceConnected(int profile, BluetoothProfile proxy) {
Log.d("service connected");
if (profile == BluetoothGattAdapter.GATT) {
mGatt = (BluetoothGatt) proxy;
mGatt.registerApp(mCallback);
}
}
@Override
public void onServiceDisconnected(int profile) {
Log.d("service disconnected");
if (profile == BluetoothGattAdapter.GATT) {
mGatt.unregisterApp();
mGatt = null;
}
}
class GattCallback extends BluetoothGattCallback {
@Override
public void onScanResult(BluetoothDevice device, int rssi, byte[] scanRecord) {
onFoundDevice(device);
}
}
}
|
package com.tpcstld.jetris;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(this);
setTheme(Constants.getTheme(settings));
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
default:
return super.onOptionsItemSelected(item);
}
}
// Opens the main game activity when the new game button is pressed
public void newMarathonGame(View view) {
Intent intent = new Intent(this, StartGameActivity.class);
intent.putExtra("startNewGame", true);
intent.putExtra("gameMode", Constants.MARATHON_MODE);
startActivity(intent);
}
public void newTimeAttackGame(View view) {
Intent intent = new Intent(this, StartGameActivity.class);
intent.putExtra("startNewGame", true);
intent.putExtra("gameMode", Constants.TIME_ATTACK_MODE);
startActivity(intent);
}
public void loadGame(View view) {
if (!MainGame.gameMode.equals("")) {
Intent intent = new Intent(this, StartGameActivity.class);
intent.putExtra("startNewGame", false);
startActivity(intent);
}
}
// Opens the Settings activity when the settings button is pressed
public void openSettings(View view) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}
public void openInstructions(View view) {
Intent intent = new Intent(this, InstructionsActivity.class);
startActivity(intent);
}
public void openAbout(View view) {
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
}
protected void onResume()
{
super.onResume();
Button button = (Button)findViewById(R.id.loadgame);
if (MainGame.gameMode.equals("")) {
button.setEnabled(false);
} else {
button.setEnabled(true);
}
}
}
|
package com.updater.ota;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
@SuppressWarnings("deprecation")
public class UpdaterSettings extends PreferenceActivity {
private CheckBoxPreference show_notif;
private SharedPreferences prefs;
private String SHOW_NOTIF_KEY = "show_notifications";
private SharedPreferences.Editor editor;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings_main);
show_notif = (CheckBoxPreference) findPreference("show_notif");
prefs = getPreferences(MODE_PRIVATE);
editor = prefs.edit();
prefs.getBoolean(SHOW_NOTIF_KEY, true);
if (SHOW_NOTIF_KEY == null) {
editor.putBoolean(SHOW_NOTIF_KEY, true);
}
show_notif.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
// TODO Auto-generated method stub
if (show_notif.isChecked()) {
editor.putBoolean(SHOW_NOTIF_KEY, true);
} else {
editor.putBoolean(SHOW_NOTIF_KEY, false);
}
return false;
}
});
}
}
|
package com.valkryst.VTerminal;
import lombok.NonNull;
import java.awt.Dimension;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public final class TileGrid {
/** An empty array of tiles. */
private final static Tile[] EMPTY_ARRAY = new Tile[0];
/** An empty 2D array of tiles. */
private final static Tile[][] EMPTY_2D_ARRAY = new Tile[0][0];
/** The position of the grid within it's parent. */
private final Point position;
/** A grid of tiles. */
private final Tile[][] tiles;
/** The child grids that reside on the grid. */
private final List<TileGrid> childGrids = new ArrayList<>();
/** The lock used to control access to the children. */
private final ReentrantReadWriteLock childLock = new ReentrantReadWriteLock();
/**
* Constructs a new TileGrid.
*
* @param dimensions
* The dimensions of the grid.
*
* @throws NullPointerException
* If the dimensions is null.
*/
public TileGrid(final @NonNull Dimension dimensions) {
if (dimensions.width < 1) {
dimensions.width = 1;
}
if (dimensions.height < 1) {
dimensions.height = 1;
}
position = new Point(0, 0);
tiles = new Tile[dimensions.height][dimensions.width];
for (int y = 0 ; y < tiles.length ; y++) {
tiles[y] = new Tile[dimensions.width];
for (int x = 0 ; x < tiles[0].length ; x++) {
tiles[y][x] = new Tile(' ');
}
}
}
/**
* Constructs a new TileGrid.
*
* @param dimensions
* The dimensions of the grid.
*
* @param position
* The position of the grid within it's parent.
*
* @throws NullPointerException
* If the dimensions or position is null.
*/
public TileGrid(final @NonNull Dimension dimensions, final @NonNull Point position) {
this(dimensions);
if (position == null) {
return;
}
if (position.x < 0) {
this.position.x = 0;
} else {
this.position.x = position.x;
}
if (position.y < 0) {
this.position.y = 0;
} else {
this.position.y = position.y;
}
}
/**
* Copies the tiles of this grid's children onto this grid, then copies
* this grid's tiles onto another grid.
*
* @param grid
* The grid to draw this grid onto.
*/
public void copyOnto(final TileGrid grid) {
if (grid == null) {
return;
}
// Draw all children onto this grid.
childLock.readLock().lock();
for (final TileGrid child : childGrids) {
child.copyOnto(this);
}
childLock.readLock().unlock();
// Draw this grid onto the input grid.
final int xOffset = position.x;
final int yOffset = position.y;
for (int y = 0 ; y < tiles.length ; y++) {
final int yPosition = yOffset + y;
for (int x = 0 ; x < tiles[0].length ; x++) {
final int xPosition = xOffset + x;
final Tile componentTile = tiles[y][x];
final Tile screenTile = grid.getTileAt(xPosition, yPosition);
if (componentTile != null && screenTile != null) {
screenTile.copy(componentTile);
}
}
}
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
for (final Tile[] tileRow : tiles) {
for (final Tile tile : tileRow) {
sb.append(tile.getCharacter());
}
sb.append("\n");
}
return sb.toString();
}
/**
* Converts this TileGrid and all of it's children to use GraphicTiles,
* rather than regular Tiles.
*/
public void convertToGraphicTileGrid() {
for (int y = 0 ; y < tiles.length ; y++) {
for (int x = 0 ; x < tiles[0].length ; x++) {
if (tiles[y][x] instanceof GraphicTile == false) {
tiles[y][x] = new GraphicTile(tiles[y][x]);
}
}
}
childLock.readLock().lock();
for (final TileGrid child : childGrids) {
child.convertToGraphicTileGrid();
}
childLock.readLock().unlock();
}
/**
* Converts this TileGrid and all of it's children to use Tiles, rather
* than GraphicTiles.
*/
public void convertToTileGrid() {
for (int y = 0 ; y < tiles.length ; y++) {
for (int x = 0 ; x < tiles[0].length ; x++) {
if (tiles[y][x] instanceof GraphicTile) {
tiles[y][x] = new Tile(tiles[y][x]);
}
}
}
childLock.readLock().lock();
for (final TileGrid child : childGrids) {
child.convertToTileGrid();
}
childLock.readLock().unlock();
}
/**
* Adds a child grid to the grid, so that it renders before all other
* children.
*
* The child is ignored if it's null.
*
* @param child
* The child.
*/
public void addChild(final TileGrid child) {
if (child == null) {
return;
}
childLock.writeLock().lock();
childGrids.add(child);
childLock.writeLock().unlock();
}
/**
* Adds a child grid to the grid, so that it renders before an existing
* child in the grid.
*
* The new child is ignored if it's null.
*
* If the existing child is null, or if it's not in the grid, then the
* function falls back to the addChlld function.
*
* @param newChild
* The new child.
*
* @param existingChild
* The existing child.
*/
public void addChildAfter(final TileGrid newChild, final TileGrid existingChild) {
if (newChild == null) {
return;
}
childLock.writeLock().lock();
if (existingChild == null || ! childGrids.contains(existingChild)) {
childLock.writeLock().unlock();
addChild(newChild);
return;
}
int indexOfExisting = childGrids.indexOf(existingChild);
childGrids.add(indexOfExisting + 1, newChild);
childLock.writeLock().unlock();
}
/**
* Adds a child grid to the grid, so that it renders after an existing
* child in the grid.
*
* The child is ignored if it's null.
*
* If the existing child is null, of if it's not in the grid, then the
* function falls back to the addChild function.
*
* @param newChild
* The new child.
*
* @param existingChild
* The existing child.
*/
public void addChildBefore(final TileGrid newChild, final TileGrid existingChild) {
if (newChild == null) {
return;
}
childLock.writeLock().lock();
if (existingChild == null || ! childGrids.contains(existingChild)) {
childLock.writeLock().unlock();
addChild(newChild);
return;
}
int indexOfExisting = childGrids.indexOf(existingChild);
childGrids.add(indexOfExisting, newChild);
childLock.writeLock().unlock();
}
/**
* Removes a child grid from the grid.
*
* The child is ignored if it's null.
*
* @param child
* The child.
*/
public void removeChild(final TileGrid child) {
if (child == null) {
return;
}
childLock.writeLock().lock();
// Reset the tiles on which the child may have been drawn.
final int startY = child.getYPosition();
final int endY = Math.min(startY + child.getHeight(), tiles.length);
final int startX = child.getXPosition();
final int endX = Math.min(startX + child.getWidth(), tiles[0].length);
for (int y = startY ; y < endY ; y++) {
for (int x = startX ; x < endX ; x++) {
if (y < tiles.length && x < tiles[0].length) {
tiles[y][x].reset();
}
}
}
// Remove the child.
childGrids.remove(child);
childLock.writeLock().unlock();
}
/**
* Determines whether or not the grid contains a specific child.
*
* @param child
* The child.
*
* @return
* Whether or not the grid contains the child.
*/
public boolean containsChild(final TileGrid child) {
if (child == null) {
return false;
}
childLock.readLock().lock();
final boolean containsChild = childGrids.contains(child);
childLock.readLock().unlock();
return containsChild;
}
/**
* Retrieves a row of tiles.
*
* If the index is less than 0, then an empty array is returned.
* If the index exceeds the grid's height, then an empty array is returned.
*
* @param index
* The index of the row.
*
* @return
* The row of tiles.
*/
public Tile[] getRow(final int index) {
if (index >= tiles.length || index < 0) {
return EMPTY_ARRAY;
}
return tiles[index];
}
/**
* Retrieves a column of tiles.
*
* If the index is less than 0, then an empty array is returned.
* If the index exceeds the grid's width, then an empty array is returned.
*
* @param columnIndex
* The index of the column.
*
* @return
* The column of tiles.
*/
public Tile[] getColumn(final int columnIndex) {
if (columnIndex >= tiles[0].length || columnIndex < 0) {
return EMPTY_ARRAY;
}
final Tile[] columnTiles = new Tile[tiles.length];
for (int rowIndex = 0 ; rowIndex < tiles.length ; rowIndex++) {
columnTiles[rowIndex] = tiles[rowIndex][columnIndex];
}
return columnTiles;
}
/**
* Retrieves a subset of tiles from a row.
*
* If the row or column indices are negative, then an empty array is returned.
*
* If the length is less than 1, then an empty array is returned.
*
* If the row index exceeds the grid's width, then an empty array is returned.
*
* If the column index exceeds the grid's width, then an empty array is returned.
*
* @param rowIndex
* The index of the row.
*
* @param columnIndex
* The index of the column to begin the subset at.
*
* @param length
* The number of columns to retrieve.
*
* @return
* The subset.
*/
public Tile[] getRowSubset(final int rowIndex, final int columnIndex, final int length) {
// Don't allow the use of negative coordinates.
if (columnIndex < 0 || rowIndex < 0) {
return EMPTY_ARRAY;
}
// Don't allow the use of negative length.
if (length < 1) {
return EMPTY_ARRAY;
}
// Don't allow the starting row value to be beyond the grid's height.
if (rowIndex >= tiles.length) {
return EMPTY_ARRAY;
}
// Don't allow the starting column value to be beyond the grid's width.
if (columnIndex >= tiles[0].length) {
return EMPTY_ARRAY;
}
int endColumn = columnIndex + length;
if (endColumn > tiles[0].length) {
return Arrays.copyOfRange(getRow(rowIndex), columnIndex, tiles[0].length);
} else {
return Arrays.copyOfRange(getRow(rowIndex), columnIndex, endColumn);
}
}
/**
* Retrieves a subset of tiles from a column.
*
* If the row or column indices are negative, then an empty array is returned.
*
* If the length is less than 1, then an empty array is returned.
*
* If the row index exceeds the grid's width, then an empty array is returned.
*
* If the column index exceeds the grid's width, then an empty array is returned.
*
* @param rowIndex
* The index of the row to begin the subset at.
*
* @param columnIndex
* The index of the column.
*
* @param length
* The number of rows to retrieve.
*
* @return
* The subset.
*/
public Tile[] getColumnSubset(final int rowIndex, final int columnIndex, final int length) {
// Don't allow the use of negative coordinates.
if (columnIndex < 0 || rowIndex < 0) {
return EMPTY_ARRAY;
}
// Don't allow the use of negative length.
if (length < 1) {
return EMPTY_ARRAY;
}
// Don't allow the starting row value to be beyond the grid's height.
if (rowIndex >= tiles.length) {
return EMPTY_ARRAY;
}
// Don't allow the starting column value to be beyond the grid's width.
if (columnIndex >= tiles[0].length) {
return EMPTY_ARRAY;
}
int endRow = (rowIndex + length) >= tiles.length ? tiles.length : (rowIndex + length);
final Tile[] columnTiles = getColumn(columnIndex);
final Tile[] resultTiles = new Tile[endRow];
System.arraycopy(columnTiles, rowIndex, resultTiles, 0, endRow - rowIndex);
return resultTiles;
}
/**
* Retrieves a rectangular subset of tiles from the grid. The tiles are
* ordered first by row, then by column. The point (5x, 10y) would be
* at 'subset[10][5]'.
*
* If the width or height are less than 1, then an empty array is returned.
*
* If the start row or column is greater than the width/height of the grid,
* then an empty array is returned.
*
* @param startRow
* The index of the column to begin the subset at.
*
* @param startColumn
* The index of the row to begin the subset at.
*
* @param width
* The width of the subset to retrieve.
*
* @param height
* The height of the subset to retrieve.
*
* @return
* The subset.
*/
public Tile[][] getRectangularSubset(int startRow, int startColumn, final int width, final int height) {
int endColumn = width + startColumn;
int endRow = height + startRow;
// Don't allow the use of negative coordinates.
if (startRow < 0 || startColumn < 0) {
startRow = 0;
}
if (startColumn < 0) {
startColumn = 0;
}
// Don't allow the dimensions to be below 1 tile.
if (width < 1 || height < 1) {
return EMPTY_2D_ARRAY;
}
// Don't allow the starting row value to be beyond the grid's height.
if (startRow > tiles.length) {
return EMPTY_2D_ARRAY;
}
// Don't allow the starting column value to be beyond the grid's width.
if (startColumn > tiles[0].length) {
return EMPTY_2D_ARRAY;
}
// Don't allow the ending row value to be beyond the grid's height.
if (endRow > tiles.length) {
endRow = tiles.length;
}
// Don't allow the ending column value to be beyond the grid's width.
if (endColumn > tiles[0].length) {
endColumn = tiles[0].length;
}
// Don't allow the start/ending column values to be equal.
if (startColumn == endColumn) {
return EMPTY_2D_ARRAY;
}
// Don't allow the start/ending row values to be equal.
if (startRow == endRow) {
return EMPTY_2D_ARRAY;
}
// Create array.
final Tile[][] resultTiles = new Tile[endRow - startRow][endColumn - startColumn];
for (int y = startRow ; y < endRow ; y++) {
System.arraycopy(tiles[y], startColumn, resultTiles[y - startRow], 0, endColumn - startColumn);
}
return resultTiles;
}
/**
* Retrieves the x-axis coordinate of the grid within it's parent.
*
* @return
* The x-axis coordinate of the grid within it's parent.
*/
public int getXPosition() {
return position.x;
}
/**
* Retrieves the y-axis coordinate of the grid within it's parent.
*
* @return
* The y-axis coordinate of the grid within it's parent.
*/
public int getYPosition() {
return position.y;
}
/**
* Retrieves the width, also known as the total number of columns, in the grid.
*
* @return
* The width of the grid.
*/
public int getWidth() {
return tiles[0].length;
}
/**
* Retrieves the height, also known as the total number of rows, in the grid.
*
* @return
* The height of the grid.
*/
public int getHeight() {
return tiles.length;
}
/**
* Retrieves a tile from the grid.
*
* @param x
* The x-axis coordinate of the tile to retrieve.
*
* @param y
* The y-axis coordinate of the tile to retrieve.
*
* @return
* The tile, or null if the coordinates are outside the bounds
* of the grid.
*/
public Tile getTileAt(final int x, final int y) {
if (x < 0 || x >= tiles[0].length) {
return null;
}
if (y < 0 || y >= tiles.length) {
return null;
}
return tiles[y][x];
}
/**
* Retrieves a tile from the grid.
*
* @param position
* The x/y-axis coordinates of the tile to retrieve.
*
* @return
* The tile, or null if the coordinates are outside the bounds
* of the grid.
*/
public Tile getTileAt(final Point position) {
if (position == null) {
return null;
}
return getTileAt(position.x, position.y);
}
/**
* Sets the new x-axis coordinate of the grid within it's parent.
*
* Negative coordinates are ignored.
*
* @param x
* The new coordinate.
*/
public void setXPosition(final int x) {
position.x = x;
}
/**
* Sets the new y-axis coordinate of the grid within it's parent.
*
* Negative coordinates are ignored.
*
* @param y
* The new coordinate.
*/
public void setYPosition(final int y) {
position.y = y;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.untamedears.JukeAlert.storage;
import com.untamedears.JukeAlert.JukeAlert;
import com.untamedears.JukeAlert.chat.ChatFiller;
import com.untamedears.JukeAlert.group.GroupMediator;
import com.untamedears.JukeAlert.manager.ConfigManager;
import com.untamedears.JukeAlert.model.LoggedAction;
import com.untamedears.JukeAlert.model.Snitch;
import com.untamedears.JukeAlert.tasks.GetSnitchInfoTask;
import com.untamedears.JukeAlert.util.SparseQuadTree;
import com.untamedears.citadel.entity.Faction;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
/**
*
* @author Dylan Holmes
*/
public class JukeAlertLogger {
private JukeAlert plugin;
private ConfigManager configManager;
private GroupMediator groupMediator;
private Database db;
private String snitchsTbl;
private String snitchDetailsTbl;
private PreparedStatement getSnitchIdFromLocationStmt;
private PreparedStatement getAllSnitchesStmt;
private PreparedStatement getAllSnitchesByWorldStmt;
private PreparedStatement getLastSnitchID;
private PreparedStatement getSnitchLogStmt;
private PreparedStatement deleteSnitchLogStmt;
private PreparedStatement insertSnitchLogStmt;
private PreparedStatement insertNewSnitchStmt;
private PreparedStatement deleteSnitchStmt;
private PreparedStatement updateGroupStmt;
private PreparedStatement updateCuboidVolumeStmt;
private PreparedStatement updateSnitchNameStmt;
private PreparedStatement updateSnitchGroupStmt;
private int logsPerPage;
private int lastSnitchID;
public JukeAlertLogger() {
plugin = JukeAlert.getInstance();
configManager = plugin.getConfigManager();
groupMediator = plugin.getGroupMediator();
String host = configManager.getHost();
int port = configManager.getPort();
String dbname = configManager.getDatabase();
String username = configManager.getUsername();
String password = configManager.getPassword();
String prefix = configManager.getPrefix();
snitchsTbl = prefix + "snitchs";
snitchDetailsTbl = prefix + "snitch_details";
db = new Database(host, port, dbname, username, password, prefix, this.plugin.getLogger());
boolean connected = db.connect();
if (connected) {
genTables();
initializeStatements();
} else {
this.plugin.getLogger().log(Level.SEVERE, "Could not connect to the database! Fill out your config.yml!");
}
logsPerPage = configManager.getLogsPerPage();
}
public Database getDb() {
return db;
}
/**
* Table generator
*/
private void genTables() {
//Snitches
db.execute("CREATE TABLE IF NOT EXISTS `" + snitchsTbl + "` ("
+ "`snitch_id` int(10) unsigned NOT NULL AUTO_INCREMENT,"
+ "`snitch_world` varchar(40) NOT NULL,"
+ "`snitch_name` varchar(40) NOT NULL,"
+ "`snitch_x` int(10) NOT NULL,"
+ "`snitch_y` int(10) NOT NULL,"
+ "`snitch_z` int(10) NOT NULL,"
+ "`snitch_group` varchar(40) NOT NULL,"
+ "`snitch_cuboid_x` int(10) NOT NULL,"
+ "`snitch_cuboid_y` int(10) NOT NULL,"
+ "`snitch_cuboid_z` int(10) NOT NULL,"
+ "`snitch_should_log` BOOL,"
+ "PRIMARY KEY (`snitch_id`));");
//Snitch Details
// need to know:
// action: (killed, block break, block place, etc), can't be null
// person who initiated the action (player name), can't be null
// victim of action (player name, entity), can be null
// x, (for things like block place, bucket empty, etc, NOT the snitch x,y,z) can be null
// y, can be null
// z, can be null
// block_id, can be null (block id for block place, block use, block break, etc)
db.execute("CREATE TABLE IF NOT EXISTS `" + snitchDetailsTbl + "` ("
+ "`snitch_details_id` int(10) unsigned NOT NULL AUTO_INCREMENT,"
+ "`snitch_id` int(10) unsigned NOT NULL," // reference to the column in the main snitches table
+ "`snitch_log_time` datetime,"
+ "`snitch_logged_action` tinyint unsigned NOT NULL,"
+ "`snitch_logged_initiated_user` varchar(16) NOT NULL,"
+ "`snitch_logged_victim_user` varchar(16), "
+ "`snitch_logged_x` int(10), "
+ "`snitch_logged_Y` int(10), "
+ "`snitch_logged_z` int(10), "
+ "`snitch_logged_materialid` smallint unsigned," // can be either a block, item, etc
+ "PRIMARY KEY (`snitch_details_id`));");
}
private void initializeStatements() {
getAllSnitchesStmt = db.prepareStatement(String.format(
"SELECT * FROM %s", snitchsTbl));
getAllSnitchesByWorldStmt = db.prepareStatement(String.format(
"SELECT * FROM %s WHERE snitch_world = ?", snitchsTbl));
getLastSnitchID = db.prepareStatement(String.format(
"SHOW TABLE STATUS LIKE '%s'", snitchsTbl));
// statement to get LIMIT entries OFFSET from a number from the snitchesDetailsTbl based on a snitch_id from the main snitchesTbl
// LIMIT ?,? means offset followed by max rows to return
getSnitchLogStmt = db.prepareStatement(String.format(
"SELECT * FROM %s"
+ " WHERE snitch_id=? ORDER BY snitch_log_time DESC LIMIT ?,?",
snitchDetailsTbl));
// statement to get the ID of a snitch in the main snitchsTbl based on a Location (x,y,z, world)
getSnitchIdFromLocationStmt = db.prepareStatement(String.format("SELECT snitch_id FROM %s"
+ " WHERE snitch_x=? AND snitch_y=? AND snitch_z=? AND snitch_world=?", snitchsTbl));
// statement to insert a log entry into the snitchesDetailsTable
insertSnitchLogStmt = db.prepareStatement(String.format(
"INSERT INTO %s (snitch_id, snitch_log_time, snitch_logged_action, snitch_logged_initiated_user,"
+ " snitch_logged_victim_user, snitch_logged_x, snitch_logged_y, snitch_logged_z, snitch_logged_materialid) "
+ " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",
snitchDetailsTbl));
insertNewSnitchStmt = db.prepareStatement(String.format(
"INSERT INTO %s (snitch_world, snitch_name, snitch_x, snitch_y, snitch_z, snitch_group, snitch_cuboid_x, snitch_cuboid_y, snitch_cuboid_z)"
+ " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",
snitchsTbl));
deleteSnitchLogStmt = db.prepareStatement(String.format(
"DELETE FROM %s WHERE snitch_id=?",
snitchDetailsTbl));
deleteSnitchStmt = db.prepareStatement(String.format(
"DELETE FROM %s WHERE snitch_world=? AND snitch_x=? AND snitch_y=? AND snitch_z=?",
snitchsTbl));
updateGroupStmt = db.prepareStatement(String.format(
"UPDATE %s SET snitch_group=? WHERE snitch_world=? AND snitch_x=? AND snitch_y=? AND snitch_z=?",
snitchsTbl));
updateCuboidVolumeStmt = db.prepareStatement(String.format(
"UPDATE %s SET snitch_cuboid_x=?, snitch_cuboid_y=?, snitch_cuboid_z=?"
+ " WHERE snitch_world=? AND snitch_x=? AND snitch_y=? AND snitch_z=?",
snitchsTbl));
updateSnitchNameStmt = db.prepareStatement(String.format(
"UPDATE %s SET snitch_name=?"
+ " WHERE snitch_id=?",
snitchsTbl));
updateSnitchGroupStmt = db.prepareStatement(String.format(
"UPDATE %s SET snitch_group=?"
+ " WHERE snitch_id=?",
snitchsTbl));
}
public static String snitchKey(final Location loc) {
return String.format(
"World: %s X: %d Y: %d Z: %d",
loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
}
public Map<World, SparseQuadTree> getAllSnitches() {
Map<World, SparseQuadTree> snitches = new HashMap<World, SparseQuadTree>();
List<World> worlds = this.plugin.getServer().getWorlds();
for (World world : worlds) {
SparseQuadTree snitchesByWorld = getAllSnitchesByWorld(world);
snitches.put(world, snitchesByWorld);
}
return snitches;
}
public SparseQuadTree getAllSnitchesByWorld(World world) {
SparseQuadTree snitches = new SparseQuadTree();
try {
Snitch snitch = null;
getAllSnitchesByWorldStmt.setString(1, world.getName());
ResultSet rs = getAllSnitchesByWorldStmt.executeQuery();
while (rs.next()) {
double x = rs.getInt("snitch_x");
double y = rs.getInt("snitch_y");
double z = rs.getInt("snitch_z");
String groupName = rs.getString("snitch_group");
Faction group = groupMediator.getGroupByName(groupName);
Location location = new Location(world, x, y, z);
snitch = new Snitch(location, group);
snitch.setId(rs.getInt("snitch_id"));
snitch.setName(rs.getString("snitch_name"));
snitches.add(snitch);
}
ResultSet rsKey = getLastSnitchID.executeQuery();
if (rsKey.next()) {
lastSnitchID = rsKey.getInt("Auto_increment");
}
} catch (SQLException ex) {
this.plugin.getLogger().log(Level.SEVERE, "Could not get all Snitches from World " + world + "!");
}
return snitches;
}
public void saveAllSnitches() {
//TODO: Save snitches.
}
/**
* Gets
*
* @limit events about that snitch.
* @param loc - the location of the snitch
* @param offset - the number of entries to start at (10 means you start at
* the 10th entry and go to
* @limit)
* @param limit - the number of entries to limit
* @return a Map of String/Date objects of the snitch entries, formatted
* nicely
*/
public List<String> getSnitchInfo(Location loc, int offset) {
List<String> info = new ArrayList<String>();
// get the snitch's ID based on the location, then use that to get the snitch details from the snitchesDetail table
int interestedSnitchId = -1;
try {
// params are x(int), y(int), z(int), world(tinyint), column returned: snitch_id (int)
getSnitchIdFromLocationStmt.setInt(1, loc.getBlockX());
getSnitchIdFromLocationStmt.setInt(2, loc.getBlockY());
getSnitchIdFromLocationStmt.setInt(3, loc.getBlockZ());
getSnitchIdFromLocationStmt.setString(4, loc.getWorld().getName());
ResultSet snitchIdSet = getSnitchIdFromLocationStmt.executeQuery();
// make sure we got a result
boolean didFind = false;
while (snitchIdSet.next()) {
didFind = true;
interestedSnitchId = snitchIdSet.getInt("snitch_id");
}
// only continue if we actually got a result from the first query
if (!didFind) {
this.plugin.getLogger().log(Level.SEVERE, "Didn't get any results trying to find a snitch in the snitches table at location " + loc);
} else {
GetSnitchInfoTask task = new GetSnitchInfoTask(plugin, interestedSnitchId, offset);
Bukkit.getScheduler().runTaskAsynchronously(plugin, task);
return task.getInfo();
}
} catch (SQLException ex1) {
this.plugin.getLogger().log(Level.SEVERE, "Could not get Snitch Details! loc: " + loc, ex1);
}
return info;
}
public List<String> getSnitchInfo(int snitchId, int offset) {
List<String> info = new ArrayList<String>();
try {
getSnitchLogStmt.setInt(1, snitchId);
getSnitchLogStmt.setInt(2, offset);
getSnitchLogStmt.setInt(3, logsPerPage);
ResultSet set = getSnitchLogStmt.executeQuery();
if (!set.isBeforeFirst()) {
System.out.println("No data");
} else {
while (set.next()) {
// TODO: need a function to create a string based upon what things we have / don't have in this result set
// so like if we have a block place action, then we include the x,y,z, but if its a KILL action, then we just say
// x killed y, etc
info.add(createInfoString(set));
}
}
} catch (SQLException ex) {
this.plugin.getLogger().log(Level.SEVERE, "Could not get Snitch Details from the snitchesDetail table using the snitch id " + snitchId, ex);
}
return info;
}
public Boolean deleteSnitchInfo(Location loc) {
Boolean completed = false;
// get the snitch's ID based on the location, then use that to get the snitch details from the snitchesDetail table
int interestedSnitchId = -1;
try {
// params are x(int), y(int), z(int), world(tinyint), column returned: snitch_id (int)
getSnitchIdFromLocationStmt.setInt(1, loc.getBlockX());
getSnitchIdFromLocationStmt.setInt(2, loc.getBlockY());
getSnitchIdFromLocationStmt.setInt(3, loc.getBlockZ());
getSnitchIdFromLocationStmt.setString(4, loc.getWorld().getName());
ResultSet snitchIdSet = getSnitchIdFromLocationStmt.executeQuery();
// make sure we got a result
boolean didFind = false;
while (snitchIdSet.next()) {
didFind = true;
interestedSnitchId = snitchIdSet.getInt("snitch_id");
}
// only continue if we actually got a result from the first query
if (!didFind) {
this.plugin.getLogger().log(Level.SEVERE, "Didn't get any results trying to find a snitch in the snitches table at location " + loc);
} else {
deleteSnitchInfo(interestedSnitchId);
}
} catch (SQLException ex1) {
completed = false;
this.plugin.getLogger().log(Level.SEVERE, "Could not get Snitch Details! loc: " + loc, ex1);
}
return completed;
}
public Boolean deleteSnitchInfo(int snitchId) {
try {
deleteSnitchLogStmt.setInt(1, snitchId);
deleteSnitchLogStmt.execute();
return true;
} catch (SQLException ex) {
this.plugin.getLogger().log(Level.SEVERE, "Could not delete Snitch Details from the snitchesDetail table using the snitch id " + snitchId, ex);
return false;
}
}
public void logSnitchInfo(Snitch snitch, Material material, Location loc, Date date, LoggedAction action, String initiatedUser, String victimUser) {
try {
// snitchid
insertSnitchLogStmt.setInt(1, snitch.getId());
// snitch log time
insertSnitchLogStmt.setTimestamp(2, new java.sql.Timestamp(new java.util.Date().getTime()));
// snitch logged action
insertSnitchLogStmt.setByte(3, (byte) action.getLoggedActionId());
// initiated user
insertSnitchLogStmt.setString(4, initiatedUser);
// These columns, victimUser, location and materialid can all be null so check if it is an insert SQL null if it is
// victim user
if (victimUser != null) {
insertSnitchLogStmt.setString(5, victimUser);
} else {
insertSnitchLogStmt.setNull(5, java.sql.Types.VARCHAR);
}
// location, x, y, z
if (loc != null) {
insertSnitchLogStmt.setInt(6, loc.getBlockX());
insertSnitchLogStmt.setInt(7, loc.getBlockY());
insertSnitchLogStmt.setInt(8, loc.getBlockZ());
} else {
insertSnitchLogStmt.setNull(6, java.sql.Types.INTEGER);
insertSnitchLogStmt.setNull(7, java.sql.Types.INTEGER);
insertSnitchLogStmt.setNull(8, java.sql.Types.INTEGER);
}
// materialid
if (material != null) {
insertSnitchLogStmt.setShort(9, (short) material.getId());
} else {
insertSnitchLogStmt.setNull(9, java.sql.Types.SMALLINT);
}
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
try {
insertSnitchLogStmt.execute();
} catch (SQLException ex) {
Logger.getLogger(JukeAlertLogger.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
//To change body of generated methods, choose Tools | Templates.
} catch (SQLException ex) {
this.plugin.getLogger().log(Level.SEVERE, String.format("Could not create snitch log entry! with snitch %s, "
+ "material %s, date %s, initiatedUser %s, victimUser %s", snitch, material, date, initiatedUser, victimUser), ex);
}
}
/**
* logs a message that someone killed an entity
*
* @param snitch - the snitch that recorded this event
* @param player - the player that did the killing
* @param entity - the entity that died
*/
public void logSnitchEntityKill(Snitch snitch, Player player, Entity entity) {
// There is no material or location involved in this event
this.logSnitchInfo(snitch, null, null, new Date(), LoggedAction.KILL, player.getPlayerListName(), entity.getType().toString());
}
/**
* Logs a message that someone killed another player
*
* @param snitch - the snitch that recorded this event
* @param player - the player that did the killing
* @param victim - the player that died
*/
public void logSnitchPlayerKill(Snitch snitch, Player player, Player victim) {
// There is no material or location involved in this event
this.logSnitchInfo(snitch, null, null, new Date(), LoggedAction.KILL, player.getPlayerListName(), victim.getPlayerListName());
}
/**
* Logs a message that someone ignited a block within the snitch's field
*
* @param snitch - the snitch that recorded this event
* @param player - the player that did the ignition
* @param block - the block that was ignited
*/
public void logSnitchIgnite(Snitch snitch, Player player, Block block) {
// There is no material or location involved in this event
this.logSnitchInfo(snitch, block.getType(), block.getLocation(), new Date(), LoggedAction.IGNITED, player.getPlayerListName(), null);
}
/**
* Logs a message that someone entered the snitch's field
*
* @param snitch - the snitch that recorded this event
* @param player - the player that entered the snitch's field
* @param loc - the location of where the player entered
*/
public void logSnitchEntry(Snitch snitch, Location loc, Player player) {
// no material or victimUser for this event
this.logSnitchInfo(snitch, null, loc, new Date(), LoggedAction.ENTRY, player.getPlayerListName(), null);
}
/**
* Logs a message that someone broke a block within the snitch's field
*
* @param snitch - the snitch that recorded this event
* @param player - the player that broke the block
* @param block - the block that was broken
*/
public void logSnitchBlockBreak(Snitch snitch, Player player, Block block) {
// no victim user in this event
this.logSnitchInfo(snitch, block.getType(), block.getLocation(), new Date(), LoggedAction.BLOCK_BREAK, player.getPlayerListName(), null);
}
/**
* Logs a message that someone placed a block within the snitch's field
*
* @param snitch - the snitch that recorded this event
* @param player - the player that placed the block
* @param block - the block that was placed
*/
public void logSnitchBlockPlace(Snitch snitch, Player player, Block block) {
// no victim user in this event
this.logSnitchInfo(snitch, block.getType(), block.getLocation(), new Date(), LoggedAction.BLOCK_PLACE, player.getPlayerListName(), null);
}
/**
* Logs a message that someone emptied a bucket within the snitch's field
*
* @param snitch - the snitch that recorded this event
* @param player - the player that emptied the bucket
* @param loc - the location of where the bucket empty occurred
* @param item - the ItemStack representing the bucket that the player
* emptied
*/
public void logSnitchBucketEmpty(Snitch snitch, Player player, Location loc, ItemStack item) {
// no victim user in this event
this.logSnitchInfo(snitch, item.getType(), loc, new Date(), LoggedAction.BUCKET_EMPTY, player.getPlayerListName(), null);
}
/**
* Logs a message that someone filled a bucket within the snitch's field
*
* @param snitch - the snitch that recorded this event
* @param player - the player that filled the bucket
* @param block - the block that was 'put into' the bucket
*/
public void logSnitchBucketFill(Snitch snitch, Player player, Block block) {
// TODO: should we take a block or a ItemStack as a parameter here?
// JM: I think it'll be fine either way, most griefing is done with with block placement and this could be updated fairly easily
// no victim user in this event
this.logSnitchInfo(snitch, block.getType(), block.getLocation(), new Date(), LoggedAction.BUCKET_FILL, player.getPlayerListName(), null);
}
/**
* Logs a message that someone used a block within the snitch's field
*
* @param snitch - the snitch that recorded this event
* @param player - the player that used something
* @param block - the block that was used
*/
public void logUsed(Snitch snitch, Player player, Block block) {
// TODO: what should we use to identify what was used? Block? Material?
//JM: Let's keep this consistent with block plament
this.logSnitchInfo(snitch, block.getType(), block.getLocation(), new Date(), LoggedAction.BLOCK_USED, player.getPlayerListName(), null);
}
//Logs the snitch being placed at World, x, y, z in the database.
public void logSnitchPlace(final String world, final String group, final String name, final int x, final int y, final int z) {
final ConfigManager lockedConfigManager = this.configManager;
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
try {
insertNewSnitchStmt.setString(1, world);
insertNewSnitchStmt.setString(2, name);
insertNewSnitchStmt.setInt(3, x);
insertNewSnitchStmt.setInt(4, y);
insertNewSnitchStmt.setInt(5, z);
insertNewSnitchStmt.setString(6, group);
insertNewSnitchStmt.setInt(7, lockedConfigManager.getDefaultCuboidSize());
insertNewSnitchStmt.setInt(8, lockedConfigManager.getDefaultCuboidSize());
insertNewSnitchStmt.setInt(9, lockedConfigManager.getDefaultCuboidSize());
insertNewSnitchStmt.execute();
} catch (SQLException ex) {
Logger.getLogger(JukeAlertLogger.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
//Removes the snitch at the location of World, X, Y, Z from the database.
public void logSnitchBreak(final String world, final int x, final int y, final int z) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
try {
deleteSnitchStmt.setString(1, world);
deleteSnitchStmt.setInt(2, (int) Math.floor(x));
deleteSnitchStmt.setInt(3, (int) Math.floor(y));
deleteSnitchStmt.setInt(4, (int) Math.floor(z));
deleteSnitchStmt.execute();
} catch (SQLException ex) {
Logger.getLogger(JukeAlertLogger.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
//Changes the group of which the snitch is registered to at the location of loc in the database.
public void updateGroupSnitch(final Location loc, final String group) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
try {
updateGroupStmt.setString(1, group);
updateGroupStmt.setString(2, loc.getWorld().getName());
updateGroupStmt.setInt(3, loc.getBlockX());
updateGroupStmt.setInt(4, loc.getBlockY());
updateGroupStmt.setInt(5, loc.getBlockZ());
updateGroupStmt.execute();
} catch (SQLException ex) {
Logger.getLogger(JukeAlertLogger.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
//Updates the cuboid size of the snitch in the database.
public void updateCubiodSize(final Location loc, final int x, final int y, final int z) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
try {
updateCuboidVolumeStmt.setInt(1, x);
updateCuboidVolumeStmt.setInt(2, y);
updateCuboidVolumeStmt.setInt(3, z);
updateCuboidVolumeStmt.setString(4, loc.getWorld().getName());
updateCuboidVolumeStmt.setInt(5, loc.getBlockX());
updateCuboidVolumeStmt.setInt(6, loc.getBlockY());
updateCuboidVolumeStmt.setInt(7, loc.getBlockZ());
updateCuboidVolumeStmt.execute();
} catch (SQLException ex) {
Logger.getLogger(JukeAlertLogger.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
//Updates the name of the snitch in the database.
public void updateSnitchName(final Snitch snitch, final String name) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
try {
updateSnitchNameStmt.setString(1, name);
updateSnitchNameStmt.setInt(2, snitch.getId());
updateSnitchNameStmt.execute();
} catch (SQLException ex) {
Logger.getLogger(JukeAlertLogger.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
//Updates the group of the snitch in the database.
public void updateSnitchGroup(final Snitch snitch, final String group) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
try {
updateSnitchGroupStmt.setString(1, group);
updateSnitchGroupStmt.setInt(2, snitch.getId());
updateSnitchGroupStmt.execute();
} catch (SQLException ex) {
Logger.getLogger(JukeAlertLogger.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
public Integer getLastSnitchID() {
return lastSnitchID;
}
public void increaseLastSnitchID() {
lastSnitchID++;
}
public void logSnitchBlockBurn(Snitch snitch, Block block) {
this.logSnitchInfo(snitch, block.getType(), block.getLocation(), new Date(), LoggedAction.BLOCK_BURN, null, snitchDetailsTbl);
}
public String createInfoString(ResultSet set) {
String resultString = ChatColor.RED + "Error!";
try {
int id = set.getInt("snitch_details_id");
String initiator = set.getString("snitch_logged_initiated_user");
String victim = set.getString("snitch_logged_victim_user");
int action = (int) set.getByte("snitch_logged_action");
int material = set.getInt("snitch_logged_materialid");
int x = set.getInt("snitch_logged_X");
int y = set.getInt("snitch_logged_Y");
int z = set.getInt("snitch_logged_Z");
String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(set.getTimestamp("snitch_log_time"));
if (action == LoggedAction.ENTRY.getLoggedActionId()) {
resultString = String.format(" %s %s %s", ChatColor.GOLD + ChatFiller.fillString(initiator, (double) 25), ChatColor.BLUE + ChatFiller.fillString("Entry", (double) 20), ChatColor.WHITE + ChatFiller.fillString(timestamp, (double) 30));
} else if (action == LoggedAction.BLOCK_BREAK.getLoggedActionId()) {
resultString = String.format(" %s %s %s", ChatColor.GOLD + ChatFiller.fillString(initiator, (double) 25), ChatColor.DARK_RED + ChatFiller.fillString("Block Break", (double) 20), ChatColor.WHITE + ChatFiller.fillString(String.format("%d [%d %d %d]", material, x, y, z), (double) 30));
} else if (action == LoggedAction.BLOCK_PLACE.getLoggedActionId()) {
resultString = String.format(" %s %s %s", ChatColor.GOLD + ChatFiller.fillString(initiator, (double) 25), ChatColor.DARK_RED + ChatFiller.fillString("Block Place", (double) 20), ChatColor.WHITE + ChatFiller.fillString(String.format("%d [%d %d %d]", material, x, y, z), (double) 30));
} else if (action == LoggedAction.BLOCK_BURN.getLoggedActionId()) {
resultString = String.format(" %s %s %s", ChatColor.GOLD + ChatFiller.fillString(initiator, (double) 25), ChatColor.DARK_RED + ChatFiller.fillString("Block Burn", (double) 20), ChatColor.WHITE + ChatFiller.fillString(String.format("%d [%d %d %d]", material, x, y, z), (double) 30));
} else if (action == LoggedAction.IGNITED.getLoggedActionId()) {
resultString = String.format(" %s %s %s", ChatColor.GOLD + ChatFiller.fillString(initiator, (double) 25), ChatColor.GOLD + ChatFiller.fillString("Ignited", (double) 20), ChatColor.WHITE + ChatFiller.fillString(String.format("%d [%d %d %d]", material, x, y, z), (double) 30));
} else if (action == LoggedAction.USED.getLoggedActionId()) {
resultString = String.format(" %s %s %s", ChatColor.GOLD + ChatFiller.fillString(initiator, (double) 25), ChatColor.GREEN + ChatFiller.fillString("Used", (double) 20), ChatColor.WHITE + ChatFiller.fillString(String.format("%d [%d %d %d]", material, x, y, z), (double) 30));
} else if (action == LoggedAction.BUCKET_EMPTY.getLoggedActionId()) {
resultString = String.format(" %s %s %s", ChatColor.GOLD + ChatFiller.fillString(initiator, (double) 25), ChatColor.DARK_RED + ChatFiller.fillString("Bucket Empty", (double) 20), ChatColor.WHITE + ChatFiller.fillString(String.format("%d [%d %d %d]", material, x, y, z), (double) 30));
} else if (action == LoggedAction.BUCKET_FILL.getLoggedActionId()) {
resultString = String.format(" %s %s %s", ChatColor.GOLD + ChatFiller.fillString(initiator, (double) 25), ChatColor.GREEN + ChatFiller.fillString("Bucket Fill", (double) 20), ChatColor.WHITE + ChatFiller.fillString(String.format("%d [%d %d %d]", material, x, y, z), (double) 30));
} else if (action == LoggedAction.KILL.getLoggedActionId()) {
resultString = String.format(" %s %s %s", ChatColor.GOLD + ChatFiller.fillString(initiator, (double) 25), ChatColor.DARK_RED + ChatFiller.fillString("Killed", (double) 20), ChatColor.WHITE + ChatFiller.fillString(victim, (double) 30));
} else {
resultString = ChatColor.RED + "Action not found. Please contact your administrator with log ID " + id;
}
} catch (SQLException ex) {
this.plugin.getLogger().log(Level.SEVERE, "Could not get Snitch Details!");
}
return resultString;
}
}
|
package org.ow2.proactive.brokering.occi;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.ws.rs.core.Response;
import org.ow2.proactive.brokering.Broker;
import org.ow2.proactive.brokering.occi.api.Occi;
import org.ow2.proactive.brokering.occi.categories.Categories;
import org.ow2.proactive.brokering.occi.categories.Utils;
import org.ow2.proactive.brokering.occi.database.Database;
import org.ow2.proactive.brokering.occi.database.DatabaseFactory;
import org.ow2.proactive.brokering.updater.Updater;
import org.ow2.proactive.workflowcatalog.Reference;
import org.ow2.proactive.workflowcatalog.References;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import org.apache.log4j.Logger;
public class OcciServer implements Occi {
private static Logger logger = Logger.getLogger(OcciServer.class);
private Broker broker;
private Updater updater;
private DatabaseFactory databaseFactory;
private String serverPrefixUrl;
@Inject
public OcciServer(Broker broker, Updater updater, DatabaseFactory databaseFactory,
@Named("server.prefix") String serverPrefixUrl) {
this.broker = broker;
this.updater = updater;
this.serverPrefixUrl = serverPrefixUrl;
this.databaseFactory = databaseFactory;
}
@Override
public Response occiAction(String action) {
return Response.status(Response.Status.SERVICE_UNAVAILABLE).build();
}
@Override
public Response getOcciState(String action) {
return Response.status(Response.Status.SERVICE_UNAVAILABLE).build();
}
@Override
public Response createResource(String host, String category, String attributes) {
attributes = attributes.replaceAll("\"", "");
logger.info("
logger.info("Create : host = [" + host + "], category = [" + category + "]");
logger.debug(" attributes = [" + attributes + "]");
try {
String uuid = UUID.randomUUID().toString();
attributes += ",action.state=pending,occi.core.id=" + uuid;
// attributes += ",action.state=\"pending\", occi.core.id=\"" + uuid + "\"";
Resource resource = ResourceBuilder.factory(uuid, category, Utils.buildMap(attributes));
storeInDB(resource);
References references = broker.request(category, Resource.OP_CREATE, resource.getAttributes());
addResourceToUpdateQueue(resource, references);
if (!references.areAllSubmitted()) {
logger.debug("Response : CODE:" + Response.Status.BAD_REQUEST);
return Response.status(Response.Status.BAD_REQUEST).entity(references.getSummary()).build();
}
Response.ResponseBuilder responseBuilder = Response.status(Response.Status.CREATED);
responseBuilder.header("X-OCCI-Location", resource.getFullPath(serverPrefixUrl));
responseBuilder.entity(resource);
logger.debug("Response : [X-OCCI-Location: " + resource.getFullPath(
serverPrefixUrl) + "] CODE:" + Response.Status.CREATED);
return responseBuilder.build();
} catch (Throwable e) {
logger.error("Error", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
} finally {
logger.info("
}
}
@Override
public Response getAllResources(String category) {
logger.info("
logger.info("Get list : category = [" + category + "]");
try {
List<Resource> filteredResources = new ArrayList<Resource>();
for (Resource resource : findAllInDB()) {
if (resource.getCategory().equalsIgnoreCase(category)) {
resource = fillLinks(resource);
resource = fillActions(resource);
filteredResources.add(resource);
}
}
Resources resources = new Resources(filteredResources, serverPrefixUrl);
Response.ResponseBuilder response = Response.status(Response.Status.OK);
response.entity(resources);
logger.debug("Response : *" + resources.size() + " locations* CODE:" + Response.Status.OK);
return response.build();
} catch (Throwable e) {
logger.error("Error", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
} finally {
logger.info("
}
}
@Override
public Response RFC5785() {
return Response.status(Response.Status.OK).build();
}
@Override
public Response discovery() {
return Response.status(Response.Status.OK).entity(Categories.list()).build();
}
@Override
public Response getResource(String category, String uuid, String attribute) {
logger.info("
logger.info(
"Get : category = [" + category + "], uuid = [" + uuid + "], attribute = [" + attribute + "]");
try {
Resource resource = findInDB(uuid);
if (resource == null || !resource.getCategory().equalsIgnoreCase(category)) {
return Response.status(Response.Status.NOT_FOUND).build();
}
resource = fillLinks(resource);
resource = fillActions(resource);
Response.ResponseBuilder response = Response.status(Response.Status.OK);
if (attribute == null) {
response.entity(resource);
} else {
logger.info("Returning an attribute value : " + attribute);
response.entity(resource.getAttributes().get(attribute));
}
logger.debug(
"Response : *Returned resource : " + resource.getUuid() + "* CODE:" + Response.Status.OK);
return response.build();
} catch (Throwable e) {
logger.error("Error", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(e.getClass().getName() + ": " + e.getMessage()).build();
} finally {
logger.info("
}
}
private Resource fillLinks(Resource resource) {
if (resource.getAttributes().get("links") != null) {
String[] linksUuid = resource.getAttributes().get("links").split(",");
List<Resource> links = new ArrayList<Resource>();
for (String linkUuid : linksUuid) {
Resource linkedResource = findInDB(linkUuid);
if (linkedResource != null) {
linkedResource = fillActions(linkedResource);
links.add(linkedResource);
}
}
resource.setLinks(links);
}
return resource;
}
private Resource fillActions(Resource resource) {
resource.setActions(broker.listPossibleActions(resource.getCategory(), resource.getAttributes()));
return resource;
}
@Override
public Response updateResource(String category, String uuid, String action, String attributes) {
logger.info("
logger.info("Update : category = [" + category + "], uuid = [" + uuid + "], action = [" + action + "]");
logger.info(" attributes = [" + attributes + "]");
try {
Resource resource = findInDB(uuid);
if (resource == null || !resource.getCategory().equalsIgnoreCase(category)) {
logger.debug("Response : NOT_FOUND:" + Response.Status.NOT_FOUND);
return Response.status(Response.Status.NOT_FOUND).build();
}
Map<String, String> newAttributes = Utils.buildMap(attributes);
for (String key : newAttributes.keySet()) {
String attribute = resource.getAttributes().get(key);
if (attribute == null) {
logger.debug("Unexpected attribute: " + key);
continue;
}
resource.getAttributes().put(key, newAttributes.get(key));
}
storeInDB(resource);
addActionAttributes(action, resource, newAttributes);
References references = new References();
Response.ResponseBuilder response;
if (action != null) {
references = broker.request(category, Resource.OP_UPDATE, action, resource.getAttributes());
addResourceToUpdateQueue(resource, references);
}
response = Response.status(Response.Status.OK);
response.entity(references.getSummary());
response.header("X-OCCI-Location", resource.getFullPath(serverPrefixUrl));
response.entity(resource);
logger.debug("Response : [X-OCCI-Location: " + resource.getFullPath(
serverPrefixUrl) + "] CODE:" + Response.Status.OK);
return response.build();
} catch (Throwable e) {
logger.error("Error", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
} finally {
logger.info("
}
}
private void addActionAttributes(String action, Resource resource, Map<String, String> newAttributes) {
if (action != null) {
resource.getAttributes().put("action.state", "pending");
for (String key : newAttributes.keySet()) {
resource.getAttributes().put(key, newAttributes.get(key));
}
}
}
@Override
public Response fullUpdateResource(String category, String uuid, String action, String attributes) {
return updateResource(category, uuid, action, attributes);
}
@Override
public Response deleteResource(String category, String uuid, String status) {
logger.info("
try {
if (status == null) {
logger.info("Delete request : category = [" + category + "], uuid = [" + uuid + "]");
return updateResource(category, uuid, "delete", "");
}
logger.info(
"Delete URL : category = [" + category + "], uuid = [" + uuid + "], status = [" + status + "]");
if (status.equalsIgnoreCase("done")) {
deleteFromDB(uuid);
logger.info("
return Response.status(Response.Status.OK).build();
}
return Response.status(Response.Status.BAD_REQUEST).build();
} catch (Throwable e) {
logger.error("Error", e);
logger.info("
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
private void addResourceToUpdateQueue(Resource resource,
References references) {
for (Reference ref : references) {
if (Reference.Nature.NATURE_JOB.equals(ref.getNatureOfReference())) {
updater.addResourceToTheUpdateQueue(ref, getResource(resource.getAttributes()));
}
}
}
private Resource getResource(Map<String, String> attributes) {
return findInDB(attributes.get("occi.core.id"));
}
private void storeInDB(Resource resource) {
Database db = databaseFactory.build();
db.store(resource);
db.close();
}
private Resource findInDB(String uuid) {
Database db = databaseFactory.build();
Resource resource = db.load(uuid);
db.close();
return resource;
}
private List<Resource> findAllInDB() {
Database db = databaseFactory.build();
List<Resource> resources = db.getAllResources();
db.close();
return resources;
}
private void deleteFromDB(String uuid) {
Database db = databaseFactory.build();
db.delete(uuid);
db.close();
}
/** For testing */
public void setUpdater(Updater updater) {
this.updater = updater;
}
public void linkResources(String sourceLocation, String targetLocation) {
String sourceUuid = toRelativePath(sourceLocation);
String targetUuid = toRelativePath(targetLocation);
Resource source = findInDB(sourceUuid);
Resource target = findInDB(targetUuid);
addLinkToResource(source, target);
addLinkToResource(target, source);
storeInDB(source);
storeInDB(target);
}
private void addLinkToResource(Resource source, Resource target) {
// links is comma separated resource uuids
if (source.getAttributes().get("links") == null) {
source.getAttributes().put("links", target.getUuid());
} else {
source.getAttributes().put("links", source.getAttributes().get("links") + "," + target.getUuid());
}
}
private String toRelativePath(String sourceLocation) {
String[] urlParts = sourceLocation.split("/");
return urlParts[urlParts.length - 1];
}
}
|
package bndtools.wizards.workspace;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;
import org.bndtools.core.ui.wizards.shared.TemplateSelectionWizardPage;
import org.bndtools.templating.Resource;
import org.bndtools.templating.ResourceMap;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IProjectNature;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.IPerspectiveDescriptor;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWizard;
import aQute.lib.io.IO;
import bndtools.Plugin;
public class WorkspaceSetupWizard extends Wizard implements IWorkbenchWizard {
private IWorkbench workbench;
private IStructuredSelection selection;
private WorkspaceSetupWizardPage setupPage;
private TemplateSelectionWizardPage templatePage;
private WorkspacePreviewPage previewPage;
public WorkspaceSetupWizard() {
setNeedsProgressMonitor(true);
}
@Override
public void init(IWorkbench workbench, IStructuredSelection selection) {
this.workbench = workbench;
this.selection = selection;
setupPage = new WorkspaceSetupWizardPage();
updateSetupPageForExistingProjects();
templatePage = new TemplateSelectionWizardPage("workspaceTemplateSelection", "workspace", null);
templatePage.setTitle("Select Workspace Template");
previewPage = new WorkspacePreviewPage();
previewPage.setTargetDir(setupPage.getLocation().toFile());
setupPage.addPropertyChangeListener(WorkspaceLocationPart.PROP_LOCATION, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
previewPage.setTargetDir(setupPage.getLocation().toFile());
}
});
templatePage.addPropertyChangeListener(TemplateSelectionWizardPage.PROP_TEMPLATE, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
previewPage.setTemplate(templatePage.getTemplate());
}
});
}
@Override
public void addPages() {
addPage(setupPage);
addPage(templatePage);
addPage(previewPage);
}
@Override
public boolean performFinish() {
final IWorkspace workspace = ResourcesPlugin.getWorkspace();
final File targetDir = previewPage.getTargetDir();
final Set<String> checkedPaths = previewPage.getCheckedPaths();
try {
// Expand the template
ResourceMap outputs = previewPage.getTemplateOutputs();
final Set<File> topLevelFolders = new HashSet<>();
for (Entry<String,Resource> entry : outputs.entries()) {
String path = entry.getKey();
if (checkedPaths.contains(path)) {
Resource resource = entry.getValue();
// Create the folder or file resource
File file = new File(targetDir, path);
switch (resource.getType()) {
case Folder :
Files.createDirectories(file.toPath());
break;
case File :
File parentDir = file.getParentFile();
Files.createDirectories(parentDir.toPath());
try (InputStream in = resource.getContent(); FileOutputStream out = new FileOutputStream(file)) {
IO.copy(in, out);
}
break;
default :
throw new IllegalArgumentException("Unknown resource type " + resource.getType());
}
// Remember the top-level folders we create, for importing below
if (file.getParentFile().equals(targetDir))
topLevelFolders.add(file);
}
}
// Import anything that looks like an Eclipse project
final IWorkspaceRunnable importProjectsRunnable = new IWorkspaceRunnable() {
@Override
public void run(IProgressMonitor monitor) throws CoreException {
File[] children = targetDir.listFiles();
if (children != null) {
SubMonitor progress = SubMonitor.convert(monitor, children.length * 2);
for (File folder : children) {
if (folder.isDirectory() && topLevelFolders.contains(folder)) {
String projectName = folder.getName();
File projectFile = new File(folder, IProjectDescription.DESCRIPTION_FILE_NAME);
if (projectFile.exists()) {
IProject project = workspace.getRoot().getProject(projectName);
if (!project.exists()) {
// No existing project in the workspace, so import the generated project.
project.create(progress.newChild(1));
project.open(progress.newChild(1));
} else {
// If a project with the same name exists, does it live in the same location? If not, we can't import the generated project.
File existingLocation = project.getLocation().toFile();
if (!existingLocation.equals(folder)) {
String message = String.format("Cannot import generated project from %s. A project named %s already exists in the workspace and is mapped to location %s", folder.getAbsolutePath(), projectName,
existingLocation);
throw new CoreException(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, message, null));
}
// Open it if closed
project.open(progress.newChild(1));
// Refresh, as the template may have generated new content
project.refreshLocal(IResource.DEPTH_INFINITE, progress.newChild(1));
}
}
}
}
}
}
};
getContainer().run(true, true, new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
workspace.run(importProjectsRunnable, monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
});
// Prompt to switch to the bndtools perspective
IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
IPerspectiveDescriptor currentPerspective = window.getActivePage().getPerspective();
if (!"bndtools.perspective".equals(currentPerspective.getId())) {
if (MessageDialog.openQuestion(getShell(), "Bndtools Perspective", "Switch to the Bndtools perspective?")) {
workbench.showPerspective("bndtools.perspective", window);
}
}
return true;
} catch (InvocationTargetException e) {
ErrorDialog.openError(getShell(), "Error", null, new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error generating template output", e.getTargetException()));
return false;
} catch (Exception e) {
ErrorDialog.openError(getShell(), "Error", null, new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error generating template output", e));
return false;
}
}
private void updateSetupPageForExistingProjects() {
// find existing bnd projects
File existingBndLocation = null;
for (IProject project : ResourcesPlugin.getWorkspace().getRoot().getProjects()) {
if (!project.isOpen())
continue;
try {
IProjectNature bndNature = project.getNature(Plugin.BNDTOOLS_NATURE);
if (bndNature != null) {
File projectLocation = project.getLocation().toFile();
existingBndLocation = projectLocation.getParentFile();
break;
}
} catch (CoreException ex) {
Plugin.getDefault().getLog().log(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Failed to load project nature", ex));
}
}
if (existingBndLocation != null) {
setupPage.setLocation(new LocationSelection(false, existingBndLocation.getAbsolutePath()));
}
}
}
|
package com.wurmonline.server.spells;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.gotti.wurmunlimited.modsupport.actions.ModActions;
import com.schmois.wurmunlimited.mods.surfaceminingfix.Constants;
import com.wurmonline.server.Server;
import com.wurmonline.server.behaviours.ActionEntry;
import com.wurmonline.server.creatures.Creature;
import com.wurmonline.server.items.Item;
import com.wurmonline.server.items.ItemSpellEffects;
import com.wurmonline.server.items.Materials;
import com.wurmonline.server.skills.Skill;
public class AzbantiumFistEnchant extends ReligiousSpell {
private static Logger logger = Logger.getLogger(AzbantiumFistEnchant.class.getName());
public AzbantiumFistEnchant(int cost, int difficulty, long cooldown) {
super("Azbantium Fist", ModActions.getNextActionId(), 20, cost, difficulty, 30, cooldown);
this.targetItem = true;
this.enchantment = Constants.af_enchantmentId;
this.description = "increases surface mining speed";
this.effectdesc = "will mine surface rock quicker.";
ActionEntry actionEntry = ActionEntry.createEntry((short) number, name, "enchanting",
new int[] { 2 /* ACTION_TYPE_SPELL */, 36 /* ACTION_TYPE_ALWAYS_USE_ACTIVE_ITEM */,
48 /* ACTION_TYPE_ENEMY_ALWAYS */ });
ModActions.registerAction(actionEntry);
}
public static boolean isValidTarget(Item target) {
if (!target.isMiningtool())
return false;
if (Constants.af_ironMaterial && target.getMaterial() == Materials.MATERIAL_IRON)
return true;
if (Constants.af_steelMaterial && target.getMaterial() == Materials.MATERIAL_STEEL)
return true;
if (Constants.af_seryllMaterial && target.getMaterial() == Materials.MATERIAL_SERYLL)
return true;
if (Constants.af_glimmersteelMaterial && target.getMaterial() == Materials.MATERIAL_GLIMMERSTEEL)
return true;
if (Constants.af_adamantineMaterial && target.getMaterial() == Materials.MATERIAL_ADAMANTINE)
return true;
return false;
}
@Override
boolean precondition(final Skill castSkill, final Creature performer, final Item target) {
if (!isValidTarget(target)) {
performer.getCommunicator().sendNormalServerMessage("The spell will not work on that.");
return false;
}
if ((!Constants.af_allowWoA && target.getSpellEffect(BUFF_WIND_OF_AGES) != null)
|| (!Constants.af_allowBotD && target.getSpellEffect(BUFF_BLESSINGDARK) != null)) {
performer.getCommunicator().sendNormalServerMessage(
"The " + target.getName() + " is already enchanted with something that would negate the effect.");
return false;
}
return Spell.mayBeEnchanted(target);
}
@Override
boolean precondition(final Skill castSkill, final Creature performer, final Creature target) {
return false;
}
@Override
void doEffect(final Skill castSkill, double power, final Creature performer, final Item target) {
if (isMaxed(performer, target)) {
return;
}
if (!isValidTarget(target)) {
performer.getCommunicator().sendNormalServerMessage("The spell fizzles.");
return;
}
ItemSpellEffects effs = target.getSpellEffects();
if (effs == null) {
effs = new ItemSpellEffects(target.getWurmId());
}
if (!Constants.af_usePower) {
power = 100.0F;
}
SpellEffect eff = effs.getSpellEffect(this.enchantment);
if (eff == null) {
performer.getCommunicator()
.sendNormalServerMessage("The " + target.getName() + " will now surface mine quicker.");
eff = new SpellEffect(target.getWurmId(), this.enchantment, (float) power, 20000000);
effs.addSpellEffect(eff);
Server.getInstance().broadCastAction(String.valueOf(performer.getName()) + " looks pleased.", performer, 5);
} else if (eff.getPower() > power) {
performer.getCommunicator().sendNormalServerMessage("You frown as you fail to improve the power.");
Server.getInstance().broadCastAction(String.valueOf(performer.getName()) + " frowns.", performer, 5);
} else {
performer.getCommunicator()
.sendNormalServerMessage("You succeed in improving the power of the " + this.name + ".");
eff.improvePower((float) power);
Server.getInstance().broadCastAction(String.valueOf(performer.getName()) + " looks pleased.", performer, 5);
}
}
@Override
void doNegativeEffect(final Skill castSkill, final double power, final Creature performer, final Item target) {
if (!isMaxed(performer, target)) {
this.checkDestroyItem(power, performer, target);
}
}
private boolean isMaxed(Creature performer, Item target) {
SpellEffect eff = target.getSpellEffect(this.enchantment);
if (!Constants.af_usePower) {
if (eff != null) {
returnFavor(performer);
return true;
}
} else {
if (eff != null && eff.getPower() == 100.0F) {
returnFavor(performer);
return true;
}
}
return false;
}
private void returnFavor(Creature performer) {
try {
performer.setFavor(performer.getFavor() + (float) this.cost);
} catch (IOException e) {
logger.log(Level.WARNING, "Programming error", e);
}
performer.getCommunicator().sendNormalServerMessage(this.name + " is already maxed out.");
}
}
|
package cx2x.xcodeml.exception;
/**
* Exception thrown during the analysis of a directive.
*
* @author clementval
*/
public class IllegalDirectiveException extends Exception {
private int _directiveLine = 0;
private int _charPos = 0;
private String _directive;
public IllegalDirectiveException(String directive, String message) {
super(message);
_directive = directive;
}
public IllegalDirectiveException(String directive, String message, int lineno)
{
super(message);
_directive = directive;
_directiveLine = lineno;
}
public IllegalDirectiveException(String directive, String message, int lineno,
int charPos)
{
super(message);
_directive = directive;
_directiveLine = lineno;
_charPos = charPos;
}
public String getDirective() {
return _directive;
}
public void setDirective(String directive) {
_directive = directive;
}
public int getDirectiveLine() {
return _directiveLine;
}
public void setDirectiveLine(int lineno) {
_directiveLine = lineno;
}
/**
* Get the character position where the directive error happened.
*
* @return Character position in the line.
*/
public int getCharPosition() {
return _charPos;
}
@Override
public String getMessage() {
String errorMessage = "Illegal directive ";
if(_directiveLine > 0) {
errorMessage += _directiveLine + ":" + _charPos;
} else {
errorMessage += "-:" + _charPos;
}
errorMessage += ": " + super.getMessage();
return errorMessage;
}
}
|
package com.box.l10n.mojito.cli.command;
import com.box.l10n.mojito.cli.CLITestBase;
import com.box.l10n.mojito.entity.Locale;
import com.box.l10n.mojito.entity.Repository;
import com.box.l10n.mojito.rest.client.AssetClient;
import com.box.l10n.mojito.rest.entity.Asset;
import com.box.l10n.mojito.service.locale.LocaleService;
import com.box.l10n.mojito.service.tm.search.StatusFilter;
import com.box.l10n.mojito.service.tm.search.TextUnitDTO;
import com.box.l10n.mojito.service.tm.search.TextUnitSearcher;
import com.box.l10n.mojito.service.tm.search.TextUnitSearcherParameters;
import com.box.l10n.mojito.service.tm.search.UsedFilter;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.File;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author wyau
*/
public class PushCommandTest extends CLITestBase {
/**
* logger
*/
static Logger logger = LoggerFactory.getLogger(PushCommandTest.class);
@Autowired
AssetClient assetClient;
@Autowired
TextUnitSearcher textUnitSearcher;
@Autowired
LocaleService localeService;
@Test
public void testCommandName() throws Exception {
Repository repository = createTestRepoUsingRepoService();
File sourceDirectory = getInputResourcesTestDir("source");
logger.debug("Source directory is [{}]", sourceDirectory.getAbsoluteFile());
getL10nJCommander().run("push", "-r", repository.getName(), "-s", sourceDirectory.getAbsolutePath());
String outputString = outputCapture.toString();
assertTrue(outputString.contains("--> asset id"));
Matcher matcher = Pattern.compile("- Uploading:\\s*([\\w].*?)\\s").matcher(outputString);
matcher.find();
String sourcePath = matcher.group(1);
logger.debug("Source path is [{}]", sourcePath);
Asset assetByPathAndRepositoryId = assetClient.getAssetByPathAndRepositoryId(sourcePath, repository.getId());
assertEquals(sourcePath, assetByPathAndRepositoryId.getPath());
}
@Test
public void testDeleteAsset() throws Exception {
Repository repository = createTestRepoUsingRepoService();
File parentSourceDirectory = getInputResourcesTestDir("delete");
File childSourceDirectory = getInputResourcesTestDir("delete/dir");
List<String> locales = Arrays.asList("fr-FR");
getL10nJCommander().run("push", "-r", repository.getName(),
"-s", parentSourceDirectory.getAbsolutePath());
String outputString = outputCapture.toString();
assertTrue(outputString.contains("--> asset id"));
// delete/source-xliff.xliff has 5 strings
// delete/dir/source-xliff.xliff has 5 strings
checkNumberOfUsedUntranslatedTextUnit(repository, locales, 10);
checkNumberOfUnusedUntranslatedTextUnit(repository, locales, 0);
getL10nJCommander().run("push", "-r", repository.getName(),
"-s", childSourceDirectory.getAbsolutePath());
outputString = outputCapture.toString();
assertTrue(outputString.contains("--> asset id"));
// delete/source-xliff.xliff should be marked as deleted
// delete/dir/source-xliff.xliff has 5 strings
checkNumberOfUsedUntranslatedTextUnit(repository, locales, 5);
checkNumberOfUnusedUntranslatedTextUnit(repository, locales, 5);
}
@Test
public void testRenameAsset() throws Exception {
Repository repository = createTestRepoUsingRepoService();
File originalSourceDirectory = getInputResourcesTestDir("source");
File renamedSourceDirectory = getInputResourcesTestDir("rename");
List<String> locales = Arrays.asList("fr-FR");
getL10nJCommander().run("push", "-r", repository.getName(),
"-s", originalSourceDirectory.getAbsolutePath());
String outputString = outputCapture.toString();
assertTrue(outputString.contains("--> asset id"));
// source/source-xliff.xliff has 5 strings
checkNumberOfUsedUntranslatedTextUnit(repository, locales, 5);
checkNumberOfUnusedUntranslatedTextUnit(repository, locales, 0);
getL10nJCommander().run("push", "-r", repository.getName(),
"-s", renamedSourceDirectory.getAbsolutePath());
outputString = outputCapture.toString();
assertTrue(outputString.contains("--> asset id"));
// source/source-xliff.xliff should be marked as deleted
// rename/source-xliff.xliff has 5 strings
checkNumberOfUsedUntranslatedTextUnit(repository, locales, 5);
checkNumberOfUnusedUntranslatedTextUnit(repository, locales, 5);
}
@Test
public void testBranches() throws Exception {
Repository repository = createTestRepoUsingRepoService();
TextUnitSearcherParameters textUnitSearcherParameters = new TextUnitSearcherParameters();
textUnitSearcherParameters.setRepositoryIds(repository.getId());
textUnitSearcherParameters.setForRootLocale(true);
textUnitSearcherParameters.setUsedFilter(UsedFilter.USED);
logger.debug("Push one string to the master branch");
File masterDirectory = getInputResourcesTestDir("master");
getL10nJCommander().run("push", "-r", repository.getName(), "-s", masterDirectory.getAbsolutePath(), "-b", "master");
List<TextUnitDTO> textUnitDTOS = getTextUnitDTOsSortedById(textUnitSearcherParameters);
assertEquals(1L, textUnitDTOS.size());
assertEquals("from.master", textUnitDTOS.get(0).getName());
assertEquals("value from master", textUnitDTOS.get(0).getSource());
logger.debug("Push 2 strings to branch 1. One string has same key but different english as the master branch, the other is a new string");
File branch1 = getInputResourcesTestDir("branch1");
getL10nJCommander().run("push", "-r", repository.getName(), "-s", branch1.getAbsolutePath(), "-b", "branch1");
textUnitDTOS = getTextUnitDTOsSortedById(textUnitSearcherParameters);
assertEquals(3L, textUnitDTOS.size());
assertEquals("from.master", textUnitDTOS.get(0).getName());
assertEquals("value from master", textUnitDTOS.get(0).getSource());
assertEquals("from.master", textUnitDTOS.get(1).getName());
assertEquals("master value changed branch 1", textUnitDTOS.get(1).getSource());
assertEquals("from.branch1", textUnitDTOS.get(2).getName());
assertEquals("value added in branch 1", textUnitDTOS.get(2).getSource());
logger.debug("Push to branch 2 with no change compared to master");
File branch2 = getInputResourcesTestDir("branch2");
getL10nJCommander().run("push", "-r", repository.getName(), "-s", branch2.getAbsolutePath(), "-b", "branch2");
textUnitDTOS = getTextUnitDTOsSortedById(textUnitSearcherParameters);
assertEquals(3L, textUnitDTOS.size());
assertEquals("from.master", textUnitDTOS.get(0).getName());
assertEquals("value from master", textUnitDTOS.get(0).getSource());
assertEquals("from.master", textUnitDTOS.get(1).getName());
assertEquals("master value changed branch 1", textUnitDTOS.get(1).getSource());
assertEquals("from.branch1", textUnitDTOS.get(2).getName());
assertEquals("value added in branch 1", textUnitDTOS.get(2).getSource());
logger.debug("Push a new string to branch 2");
File branch2Update = getInputResourcesTestDir("branch2Update");
getL10nJCommander().run("push", "-r", repository.getName(), "-s", branch2Update.getAbsolutePath(), "-b", "branch2");
textUnitDTOS = getTextUnitDTOsSortedById(textUnitSearcherParameters);
assertEquals(4L, textUnitDTOS.size());
assertEquals("from.master", textUnitDTOS.get(0).getName());
assertEquals("value from master", textUnitDTOS.get(0).getSource());
assertEquals("from.master", textUnitDTOS.get(1).getName());
assertEquals("master value changed branch 1", textUnitDTOS.get(1).getSource());
assertEquals("from.branch1", textUnitDTOS.get(2).getName());
assertEquals("value added in branch 1", textUnitDTOS.get(2).getSource());
assertEquals("from.branch2", textUnitDTOS.get(3).getName());
assertEquals("value added in branch 2", textUnitDTOS.get(3).getSource());
logger.debug("Add new file in branch 1");
File branch1Update = getInputResourcesTestDir("branch1Update");
getL10nJCommander().run("push", "-r", repository.getName(), "-s", branch1Update.getAbsolutePath(), "-b", "branch1");
textUnitDTOS = getTextUnitDTOsSortedById(textUnitSearcherParameters);
assertEquals(5L, textUnitDTOS.size());
assertEquals("from.master", textUnitDTOS.get(0).getName());
assertEquals("value from master", textUnitDTOS.get(0).getSource());
assertEquals("from.master", textUnitDTOS.get(1).getName());
assertEquals("master value changed branch 1", textUnitDTOS.get(1).getSource());
assertEquals("from.branch1", textUnitDTOS.get(2).getName());
assertEquals("value added in branch 1", textUnitDTOS.get(2).getSource());
assertEquals("from.branch2", textUnitDTOS.get(3).getName());
assertEquals("value added in branch 2", textUnitDTOS.get(3).getSource());
assertEquals("from.branch1.app2", textUnitDTOS.get(4).getName());
assertEquals("value added in branch 1 in app2.properties", textUnitDTOS.get(4).getSource());
assertEquals("app2.properties", textUnitDTOS.get(4).getAssetPath());
logger.debug("Remove file in branch 2");
File branch2Update2 = getInputResourcesTestDir("branch2Update2");
getL10nJCommander().run("push", "-r", repository.getName(), "-s", branch2Update2.getAbsolutePath(), "-b", "branch2");
textUnitDTOS = getTextUnitDTOsSortedById(textUnitSearcherParameters);
assertEquals(4L, textUnitDTOS.size());
assertEquals("from.master", textUnitDTOS.get(0).getName());
assertEquals("value from master", textUnitDTOS.get(0).getSource());
assertEquals("from.master", textUnitDTOS.get(1).getName());
assertEquals("master value changed branch 1", textUnitDTOS.get(1).getSource());
assertEquals("from.branch1", textUnitDTOS.get(2).getName());
assertEquals("value added in branch 1", textUnitDTOS.get(2).getSource());
assertEquals("from.branch1.app2", textUnitDTOS.get(3).getName());
assertEquals("value added in branch 1 in app2.properties", textUnitDTOS.get(3).getSource());
assertEquals("app2.properties", textUnitDTOS.get(3).getAssetPath());
logger.debug("Remove branch 1");
getL10nJCommander().run("branch-delete", "-r", repository.getName(), "-n", "branch1");
textUnitDTOS = getTextUnitDTOsSortedById(textUnitSearcherParameters);
assertEquals(1L, textUnitDTOS.size());
assertEquals("from.master", textUnitDTOS.get(0).getName());
assertEquals("value from master", textUnitDTOS.get(0).getSource());
logger.debug("Re-push branch 1");
getL10nJCommander().run("push", "-r", repository.getName(), "-s", branch1Update.getAbsolutePath(), "-b", "branch1");
textUnitDTOS = getTextUnitDTOsSortedById(textUnitSearcherParameters);
assertEquals(4L, textUnitDTOS.size());
assertEquals("from.master", textUnitDTOS.get(0).getName());
assertEquals("value from master", textUnitDTOS.get(0).getSource());
assertEquals("from.master", textUnitDTOS.get(1).getName());
assertEquals("master value changed branch 1", textUnitDTOS.get(1).getSource());
assertEquals("from.branch1", textUnitDTOS.get(2).getName());
assertEquals("value added in branch 1", textUnitDTOS.get(2).getSource());
assertEquals("from.branch1.app2", textUnitDTOS.get(3).getName());
assertEquals("value added in branch 1 in app2.properties", textUnitDTOS.get(3).getSource());
assertEquals("app2.properties", textUnitDTOS.get(3).getAssetPath());
}
@Test
public void testBranchesNull() throws Exception {
Repository repository = createTestRepoUsingRepoService();
TextUnitSearcherParameters textUnitSearcherParameters = new TextUnitSearcherParameters();
textUnitSearcherParameters.setRepositoryIds(repository.getId());
textUnitSearcherParameters.setForRootLocale(true);
textUnitSearcherParameters.setUsedFilter(UsedFilter.USED);
logger.debug("Push 1 string to the null branch");
File masterDirectory = getInputResourcesTestDir("null");
getL10nJCommander().run("push", "-r", repository.getName(), "-s", masterDirectory.getAbsolutePath());
List<TextUnitDTO> textUnitDTOS = getTextUnitDTOsSortedById(textUnitSearcherParameters);
assertEquals(1L, textUnitDTOS.size());
assertEquals("from.null", textUnitDTOS.get(0).getName());
assertEquals("value from null", textUnitDTOS.get(0).getSource());
logger.debug("Push 1 string to master branch");
File branch1 = getInputResourcesTestDir("master");
getL10nJCommander().run("push", "-r", repository.getName(), "-s", branch1.getAbsolutePath(), "-b", "master");
textUnitDTOS = getTextUnitDTOsSortedById(textUnitSearcherParameters);
assertEquals(2L, textUnitDTOS.size());
assertEquals("from.null", textUnitDTOS.get(0).getName());
assertEquals("value from null", textUnitDTOS.get(0).getSource());
assertEquals("from.master", textUnitDTOS.get(1).getName());
assertEquals("value from master", textUnitDTOS.get(1).getSource());
logger.debug("Remove null branch");
getL10nJCommander().run("branch-delete", "-r", repository.getName(), "-nr" , "(?!^master$)", "-nb");
textUnitDTOS = getTextUnitDTOsSortedById(textUnitSearcherParameters);
assertEquals(1L, textUnitDTOS.size());
assertEquals("from.master", textUnitDTOS.get(0).getName());
assertEquals("value from master", textUnitDTOS.get(0).getSource());
logger.debug("Re push null branch");
File branch2Update = getInputResourcesTestDir("null");
getL10nJCommander().run("push", "-r", repository.getName(), "-s", branch2Update.getAbsolutePath());
textUnitDTOS = getTextUnitDTOsSortedById(textUnitSearcherParameters);
assertEquals(2L, textUnitDTOS.size());
assertEquals("from.null", textUnitDTOS.get(0).getName());
assertEquals("value from null", textUnitDTOS.get(0).getSource());
assertEquals("from.master", textUnitDTOS.get(1).getName());
assertEquals("value from master", textUnitDTOS.get(1).getSource());
}
@Test
public void testDifferentSourceLocale() throws Exception {
String repoName = testIdWatcher.getEntityName("repository");
Locale frFRLocale = localeService.findByBcp47Tag("fr-FR");
Repository repository = repositoryService.createRepository(repoName, repoName + " description", frFRLocale, false);
repositoryService.addRepositoryLocale(repository, "en", "fr-FR", true);
repositoryService.addRepositoryLocale(repository, "fr-CA", "fr-FR", false);
repositoryService.addRepositoryLocale(repository, "ja-JP");
File sourceDirectory = getInputResourcesTestDir("source");
logger.debug("Source directory is [{}]", sourceDirectory.getAbsoluteFile());
getL10nJCommander().run("push", "-r", repository.getName(), "-s", sourceDirectory.getAbsolutePath());
TextUnitSearcherParameters textUnitSearcherParametersForSource = new TextUnitSearcherParameters();
textUnitSearcherParametersForSource.setRepositoryIds(repository.getId());
textUnitSearcherParametersForSource.setForRootLocale(true);
List<TextUnitDTO> sourceTextUnitDTOS = textUnitSearcher.search(textUnitSearcherParametersForSource);
assertEquals("k1", sourceTextUnitDTOS.get(0).getName());
assertEquals("en francais", sourceTextUnitDTOS.get(0).getSource());
assertEquals("fr-FR", sourceTextUnitDTOS.get(0).getTargetLocale());
TextUnitSearcherParameters textUnitSearcherParametersForTarget = new TextUnitSearcherParameters();
textUnitSearcherParametersForTarget.setRepositoryIds(repository.getId());
List<TextUnitDTO> targetTextUnitDTOS = textUnitSearcher.search(textUnitSearcherParametersForTarget);
assertEquals("k1", targetTextUnitDTOS.get(0).getName());
assertEquals("en francais", targetTextUnitDTOS.get(0).getSource());
assertEquals("en", targetTextUnitDTOS.get(0).getTargetLocale());
assertEquals("k1", targetTextUnitDTOS.get(1).getName());
assertEquals("en francais", targetTextUnitDTOS.get(1).getSource());
assertEquals("fr-CA", targetTextUnitDTOS.get(1).getTargetLocale());
assertEquals("k1", targetTextUnitDTOS.get(2).getName());
assertEquals("en francais", targetTextUnitDTOS.get(2).getSource());
assertEquals("ja-JP", targetTextUnitDTOS.get(2).getTargetLocale());
}
@Test
public void testInitialPushWithNofile() throws Exception {
Repository repository = createTestRepoUsingRepoService();
L10nJCommander l10nJCommander = getL10nJCommander();
l10nJCommander.run("push", "-r", repository.getName(), "-s", getInputResourcesTestDir().getAbsolutePath());
assertEquals(0, l10nJCommander.getExitCode());
}
private void checkNumberOfUsedUntranslatedTextUnit(Repository repository, List<String> locales, int expectedNumberOfUnstranslated) {
checkNumberOfUntranslatedTextUnit(repository, locales, true, expectedNumberOfUnstranslated);
}
private void checkNumberOfUnusedUntranslatedTextUnit(Repository repository, List<String> locales, int expectedNumberOfUnstranslated) {
checkNumberOfUntranslatedTextUnit(repository, locales, false, expectedNumberOfUnstranslated);
}
private void checkNumberOfUntranslatedTextUnit(Repository repository, List<String> locales, boolean used, int expectedNumberOfUnstranslated) {
TextUnitSearcherParameters textUnitSearcherParameters = new TextUnitSearcherParameters();
textUnitSearcherParameters.setRepositoryIds(repository.getId());
textUnitSearcherParameters.setStatusFilter(StatusFilter.UNTRANSLATED);
textUnitSearcherParameters.setLocaleTags(locales);
if (used) {
textUnitSearcherParameters.setUsedFilter(UsedFilter.USED);
} else {
textUnitSearcherParameters.setUsedFilter(UsedFilter.UNUSED);
}
List<TextUnitDTO> search = textUnitSearcher.search(textUnitSearcherParameters);
assertEquals(expectedNumberOfUnstranslated, search.size());
for (TextUnitDTO textUnitDTO : search) {
assertEquals(used, textUnitDTO.isUsed());
}
}
private List<TextUnitDTO> getTextUnitDTOsSortedById(TextUnitSearcherParameters textUnitSearcherParameters){
return textUnitSearcher.search(textUnitSearcherParameters).stream()
.sorted(Comparator.comparingLong(TextUnitDTO::getTmTextUnitId))
.peek(textUnitDTO -> logger.debug("name: {}, source: {}", textUnitDTO.getName(), textUnitDTO.getSource()))
.collect(Collectors.toList());
}
}
|
package ly.count.android.sdk;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ModuleConsent extends ModuleBase implements ConsentProvider {
Consent consentInterface = null;
//a list of valid feature names that are used for checking
protected static final String[] validFeatureNames = new String[] {
Countly.CountlyFeatureNames.sessions,
Countly.CountlyFeatureNames.events,
Countly.CountlyFeatureNames.views,
Countly.CountlyFeatureNames.location,
Countly.CountlyFeatureNames.crashes,
Countly.CountlyFeatureNames.attribution,
Countly.CountlyFeatureNames.users,
Countly.CountlyFeatureNames.push,
Countly.CountlyFeatureNames.starRating,
Countly.CountlyFeatureNames.remoteConfig,
Countly.CountlyFeatureNames.apm,
Countly.CountlyFeatureNames.feedback,
Countly.CountlyFeatureNames.clicks,
Countly.CountlyFeatureNames.scrolls
};
public enum ConsentChangeSource { ChangeConsentCall, DeviceIDChangedNotMerged }
protected boolean requiresConsent = false;
final Map<String, Boolean> featureConsentValues = new HashMap<>();
private final Map<String, String[]> groupedFeatures = new HashMap<>();
ModuleConsent(@NonNull final Countly cly, @NonNull final CountlyConfig config) {
super(cly, config);
consentProvider = this;
config.consentProvider = this;
L.v("[ModuleConsent] Initialising");
L.i("[ModuleConsent] Is consent required? [" + config.shouldRequireConsent + "]");
//setup initial consent data structure
//initialize all features to "false"
for(String featureName : validFeatureNames) {
featureConsentValues.put(featureName, false);
}
//react to given consent during init
if (config.shouldRequireConsent) {
requiresConsent = config.shouldRequireConsent;
if (config.enabledFeatureNames == null) {
L.i("[Init] Consent has been required but no consent was given during init");
} else {
//set provided consent values
for(String providedFeature : config.enabledFeatureNames){
featureConsentValues.put(providedFeature, true);
}
}
}
consentInterface = new Consent();
}
public boolean getConsent(@NonNull final String featureName) {
return getConsentInternal(featureName);
}
public boolean anyConsentGiven() {
if (!requiresConsent) {
//no consent required - all consent given
return true;
}
for (String key : featureConsentValues.keySet()) {
if (getConsentTrue(key)) {
return true;
}
}
return false;
}
boolean getConsentInternal(@Nullable final String featureName) {
if(featureName == null) {
L.e("[ModuleConsent] getConsentInternal, Can't call this with a 'null' feature name!");
return false;
}
if (!requiresConsent) {
//return true silently
return true;
}
boolean returnValue = getConsentTrue(featureName);
L.v("[ModuleConsent] Returning consent for feature named: [" + featureName + "] [" + returnValue + "]");
return returnValue;
}
/**
* Returns the true internally set value
* @param featureName
*/
private boolean getConsentTrue(@NonNull final String featureName) {
Boolean returnValue = featureConsentValues.get(featureName);
if (returnValue == null) {
returnValue = false;
}
return returnValue;
}
/**
* Print the consent values of all features
*/
public void checkAllConsentInternal() {
L.d("[ModuleConsent] Checking and printing consent for All features");
L.d("[ModuleConsent] Is consent required? [" + requiresConsent + "]");
//make sure push consent has been added to the feature map
getConsent(Countly.CountlyFeatureNames.push);
StringBuilder sb = new StringBuilder();
for (String key : featureConsentValues.keySet()) {
sb.append("Feature named [").append(key).append("], consent value: [").append(featureConsentValues.get(key)).append("]\n");
}
L.d(sb.toString());
}
/**
* Special things needed to be done during setting push consent
*
* @param consentValue The value of push consent
*/
void doPushConsentSpecialAction(final boolean consentValue) {
L.d("[ModuleConsent] Doing push consent special action: [" + consentValue + "]");
_cly.countlyStore.setConsentPush(consentValue);
_cly.context_.sendBroadcast(new Intent(Countly.CONSENT_BROADCAST));
}
/**
* Check if the given name is a valid feature name
*
* @param name the name of the feature to be tested if it is valid
* @return returns true if value is contained in feature name array
*/
private boolean isValidFeatureName(@Nullable final String name) {
for (String fName : validFeatureNames) {
if (fName.equals(name)) {
return true;
}
}
return false;
}
/**
* Prepare the current feature state into a json format
*
* @param features the names of features that are about to be changed
* @return provided consent changes in json format
*/
private @NonNull String formatConsentState(@NonNull final Map<String, Boolean> features) {
StringBuilder preparedConsent = new StringBuilder();
preparedConsent.append("{");
boolean commaAdded = false;
for (Map.Entry<String, Boolean> entry : features.entrySet()) {
if (commaAdded) {
preparedConsent.append(",");
} {
commaAdded = true;
}
preparedConsent.append('"');
preparedConsent.append(entry.getKey());
preparedConsent.append('"');
preparedConsent.append(':');
preparedConsent.append(entry.getValue());
}
preparedConsent.append("}");
return preparedConsent.toString();
}
void setConsentInternal(@Nullable final String[] featureNames, final boolean isConsentGiven, final ConsentChangeSource changeSource) {
if (!requiresConsent) {
//if consent is not required, ignore all calls to it
return;
}
if (featureNames == null) {
L.w("[ModuleConsent] Calling setConsent with null featureNames!");
return;
}
List<String> consentThatWillChange = new ArrayList<>(featureNames.length);
for (String featureName : featureNames) {
L.d("[ModuleConsent] Setting consent for feature: [" + featureName + "] with value: [" + isConsentGiven + "]");
if (!isValidFeatureName(featureName)) {
L.w("[ModuleConsent] Given feature: [" + featureName + "] is not a valid name, ignoring it");
continue;
}
if(getConsentTrue(featureName) != isConsentGiven) {
//if the current consent does not match the one give, add it to the list
consentThatWillChange.add(featureName);
//set new consent value
featureConsentValues.put(featureName, isConsentGiven);
}
}
for(ModuleBase module:_cly.modules) {
module.onConsentChanged(consentThatWillChange, isConsentGiven, changeSource);
}
//send consent changes
String formattedConsentState = formatConsentState(featureConsentValues);
requestQueueProvider.sendConsentChanges(formattedConsentState);
}
/**
* Remove the consent of a feature
*
* @param featureNames the names of features for which consent should be removed
*/
public void removeConsentInternal(@Nullable final String[] featureNames, final ConsentChangeSource changeSource) {
L.d("[ModuleConsent] Removing consent for features named: [" + Arrays.toString(featureNames) + "]");
setConsentInternal(featureNames, false, changeSource);
}
/**
* Remove consent for all features
*/
public void removeConsentAllInternal(final ConsentChangeSource changeSource) {
L.d("[ModuleConsent] Removing consent for all features");
removeConsentInternal(validFeatureNames, changeSource);
}
@Override
void initFinished(@NonNull final CountlyConfig config) {
if (requiresConsent) {
//do appropriate action regarding the current consent state
//remove persistent push flag if no push consent was set
doPushConsentSpecialAction(getConsentTrue(Countly.CountlyFeatureNames.push));
//send 'after init' consent state
String formattedConsentState = formatConsentState(featureConsentValues);
requestQueueProvider.sendConsentChanges(formattedConsentState);
if (L.logEnabled()) {
L.d("[ModuleConsent] [Init] Countly is initialized with the current consent state:");
checkAllConsentInternal();
}
}
}
@Override
void onConsentChanged(@NonNull final List<String> consentChangeDelta, final boolean newConsent, @NonNull final ModuleConsent.ConsentChangeSource changeSource) {
if(consentChangeDelta.contains(Countly.CountlyFeatureNames.push)) {
//handle push consent changes
doPushConsentSpecialAction(newConsent);
}
}
@Override
void halt() {
consentInterface = null;
}
public class Consent {
/**
* Print the consent values of all features
*/
public void checkAllConsent() {
synchronized (_cly) {
L.i("[Consent] calling checkAllConsent");
checkAllConsentInternal();
}
}
/**
* Get the current consent state of a feature
*
* @param featureName the name of a feature for which consent should be checked
* @return the consent value
*/
public boolean getConsent(@Nullable final String featureName) {
synchronized (_cly) {
return getConsentInternal(featureName);
}
}
/**
* Remove consent for all features
*/
public void removeConsentAll() {
synchronized (_cly) {
removeConsentAllInternal(ConsentChangeSource.ChangeConsentCall);
}
}
/**
* Remove the consent of a feature
*
* @param featureNames the names of features for which consent should be removed
*/
public void removeConsent(@Nullable final String[] featureNames) {
synchronized (_cly) {
removeConsentInternal(featureNames, ConsentChangeSource.ChangeConsentCall);
}
}
/**
* Gives consent for all features
*/
public void giveConsentAll() {
synchronized (_cly) {
L.i("[Consent] Giving consent for all features");
setConsentInternal(validFeatureNames, true, ConsentChangeSource.ChangeConsentCall);
}
}
/**
* Give the consent to a feature
*
* @param featureNames the names of features for which consent should be given
*/
public void giveConsent(@Nullable final String[] featureNames) {
synchronized (_cly) {
setConsentInternal(featureNames, true, ConsentChangeSource.ChangeConsentCall);
}
}
/**
* Set the consent of a feature
*
* @param featureNames feature names for which consent should be changed
* @param isConsentGiven the consent value that should be set
*/
public void setConsent(@Nullable final String[] featureNames, final boolean isConsentGiven) {
synchronized (_cly) {
setConsentInternal(featureNames, isConsentGiven, ConsentChangeSource.ChangeConsentCall);
}
}
/**
* Set the consent of a feature group
*
* @param groupName name of the consent group
* @param isConsentGiven the value that should be set for this consent group
*/
public void setConsentFeatureGroup(@Nullable final String groupName, final boolean isConsentGiven) {
synchronized (_cly) {
if (!groupedFeatures.containsKey(groupName)) {
L.d("[Countly] Trying to set consent for a unknown feature group: [" + groupName + "]");
return;
}
setConsentInternal(groupedFeatures.get(groupName), isConsentGiven, ConsentChangeSource.ChangeConsentCall);
}
}
/**
* Group multiple features into a feature group
*
* @param groupName name of the consent group
* @param features array of feature to be added to the consent group
*/
public void createFeatureGroup(@Nullable final String groupName, @Nullable final String[] features) {
synchronized (_cly) {
groupedFeatures.put(groupName, features);
}
}
}
}
|
package com.intellij.codeInsight.template;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.SuggestedNameInfo;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.text.BlockSupport;
import com.intellij.util.IncorrectOperationException;
/**
* @author mike
*/
public class ExpressionUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.template.ExpressionUtil");
public static String[] getNames(final ExpressionContext context) {
Project project = context.getProject();
int offset = context.getStartOffset();
PsiDocumentManager.getInstance(project).commitAllDocuments();
String[] names = null;
PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(context.getEditor().getDocument());
PsiElement element = file.findElementAt(offset);
if (element instanceof PsiIdentifier){
names = getNamesForIdentifier(project, (PsiIdentifier)element);
}
else{
PsiFile fileCopy = (PsiFile)file.copy();
BlockSupport blockSupport = project.getComponent(BlockSupport.class);
try{
blockSupport.reparseRange(fileCopy, offset, offset, "xxx");
}
catch(IncorrectOperationException e){
LOG.error(e);
}
PsiElement identifierCopy = fileCopy.findElementAt(offset);
if (identifierCopy instanceof PsiIdentifier) {
names = getNamesForIdentifier(project, (PsiIdentifier)identifierCopy);
}
}
return names;
}
private static String[] getNamesForIdentifier(Project project, PsiIdentifier identifier){
if (identifier.getParent() instanceof PsiVariable){
PsiVariable var = (PsiVariable)identifier.getParent();
if (var.getNameIdentifier().equals(identifier)){
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
VariableKind variableKind = codeStyleManager.getVariableKind(var);
SuggestedNameInfo suggestedInfo = codeStyleManager.suggestVariableName(variableKind, null, var.getInitializer(), var.getType());
return suggestedInfo.names; //TODO: callback about choosen name
}
}
return null;
}
}
|
package com.github.ojdcheck.report;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
import com.github.ojdcheck.test.ITestReport;
import com.github.ojdcheck.test.IClassDocTester.Priority;
/**
* Implementation of {@link IReportGenerator} that serializes the
* reports into an XHTML format.
*/
public class XHTMLGenerator implements IReportGenerator {
private final static String NEWLINE = System.getProperty("line.separator");
private BufferedWriter writer;
private int lineCounter = 0;
private Map<Priority,Integer> counters;
/**
* Starts the creation of a report.
*/
public void startReport(OutputStream output) throws IOException {
// set up a BufferedWriter
writer = new BufferedWriter(
new OutputStreamWriter(output)
);
lineCounter = 0;
counters = new HashMap<Priority, Integer>();
for (Priority prior : Priority.values()) counters.put(prior, 0);
writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + NEWLINE);
writer.write(
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML+RDFa 1.0//EN "+
"http:
);
writer.write(
"<html xmlns=\"http:
"version=\"XHTML+RDFa 1.0\"" + NEWLINE +
"xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns
NEWLINE
);
writer.write("<body><table>" + NEWLINE);
writer.write(" <tr>" + NEWLINE);
writer.write(" <td></td>" + NEWLINE);
writer.write(" <td><b>Class</b></td>" + NEWLINE);
writer.write(" <td><b>Line</b></td>" + NEWLINE);
writer.write(" <td><b>Error</b></td>" + NEWLINE);
writer.write(" </tr>" + NEWLINE);
}
/**
* Ends the creation of a report.
*/
public void endReport() throws IOException {
writer.write("</table>" + NEWLINE);
writer.write("<p>Summary: " + NEWLINE);
for (Priority prior : counters.keySet()) {
writer.write(prior + ": <span class=\"" + prior + "\">" +
counters.get(prior) + "</span>" + NEWLINE);
}
writer.write("</p>" + NEWLINE);
writer.write("</html>" + NEWLINE);
writer.flush();
}
/**
* Generates a report item for the given {@link ITestReport}.
*/
public void report(ITestReport report) throws IOException {
lineCounter++;
Priority prior = report.getPriority();
counters.put(prior, counters.get(prior) + 1);
writer.write(" <tr " + (
lineCounter % 2 == 0
? "style=\"background-color: silver\""
: "") +
">" + NEWLINE);
writer.write(" <td style=\"background-color: " +
getPriorityColor(prior) +
"\">" + (prior.ordinal() + 1) + "</td>" + NEWLINE +
" <td>" + report.getTestedClass().qualifiedTypeName() + "</td>" +
NEWLINE + " <td>" + report.getStartLine() + "</td>" + NEWLINE +
" <td>" + report.getFailMessage() + "</td>" + NEWLINE
);
writer.write(" </tr>" + NEWLINE);
writer.flush();
}
private String getPriorityColor(Priority priority) {
if (priority == Priority.ERROR) return "red";
if (priority == Priority.MINOR_ERROR) return "orange";
if (priority == Priority.WARNING) return "green";
return "white";
}
}
|
package org.eclipse.kapua.commons.jpa;
import org.eclipse.kapua.KapuaException;
import org.eclipse.kapua.commons.model.id.KapuaEid;
import org.eclipse.kapua.model.KapuaEntity;
import org.eclipse.kapua.model.id.KapuaId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.persistence.LockModeType;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import java.io.Serializable;
/**
* Kapua JPA entity manager wrapper
*
* @since 1.0
*/
public class EntityManager {
private static final Logger LOG = LoggerFactory.getLogger(AbstractEntityManagerFactory.class);
private javax.persistence.EntityManager javaxPersitenceEntityManager;
/**
* Constructs a new entity manager wrapping the given {@link javax.persistence.EntityManager}
*
* @param javaxPersitenceEntityManager
*/
public EntityManager(javax.persistence.EntityManager javaxPersitenceEntityManager) {
this.javaxPersitenceEntityManager = javaxPersitenceEntityManager;
}
/**
* Opens a Jpa Transaction.
*
* @throws KapuaException if {@link org.eclipse.kapua.commons.jpa.EntityManager} is {@code null}
*/
public void beginTransaction()
throws KapuaException {
if (javaxPersitenceEntityManager == null) {
throw KapuaException.internalError(new NullPointerException(), "null EntityManager");
}
javaxPersitenceEntityManager.getTransaction().begin();
}
/**
* Commits the current Jpa Transaction.
*
* @throws KapuaException
*/
public void commit()
throws KapuaException {
if (javaxPersitenceEntityManager == null) {
throw KapuaException.internalError("null EntityManager");
}
if (!javaxPersitenceEntityManager.getTransaction().isActive()) {
throw KapuaException.internalError("Transaction Not Active");
}
try {
javaxPersitenceEntityManager.getTransaction().commit();
} catch (Exception e) {
throw KapuaException.internalError(e, "Commit Error");
}
}
/**
* Rollbacks the current Jpa Transaction. No exception will be thrown when rolling back so that the original exception that caused the rollback can be thrown.
*/
public void rollback() {
try {
if (javaxPersitenceEntityManager != null &&
javaxPersitenceEntityManager.getTransaction().isActive()) {
javaxPersitenceEntityManager.getTransaction().rollback();
}
} catch (Exception e) {
LOG.warn("Rollback Error", e);
}
}
/**
* Return the transaction status
*
* @return
*/
public boolean isTransactionActive() {
return (javaxPersitenceEntityManager != null &&
javaxPersitenceEntityManager.getTransaction().isActive());
}
/**
* Closes the EntityManager
*/
public void close() {
if (javaxPersitenceEntityManager != null) {
javaxPersitenceEntityManager.close();
}
}
/**
* Persist a {@link Serializable} entity;
*
* @param entity
*/
public <E extends Serializable> void persist(E entity) {
javaxPersitenceEntityManager.persist(entity);
}
/**
* Persist a {@link KapuaEntity}
*
* @param entity
* @since 1.0.0
*/
public <E extends KapuaEntity> void persist(E entity) {
persist((Serializable) entity);
}
/**
* Flush the {@link EntityManager}
*
* @since 1.0.0}
*/
public void flush() {
javaxPersitenceEntityManager.flush();
}
/**
* Finds a {@link KapuaEntity} by the given id and type
*
* @param clazz The {@link Serializable} entity type.
* @param id The id of the entity.
* @return The found {@link Serializable} or {@code null} otherwise.
* @since 1.2.0
*/
public <E extends Serializable> E find(Class<E> clazz, Object id) {
return javaxPersitenceEntityManager.find(clazz, id);
}
/**
* Finds a {@link KapuaEntity} by the given id and type
*
* @param clazz The {@link KapuaEntity} type.
* @param id The {@link KapuaEntity#getId()}
* @return The found {@link KapuaEntity} or {@code null} otherwise.
* @since 1.0.0
*/
public <E extends KapuaEntity> E find(Class<E> clazz, KapuaId id) {
KapuaEid eid = KapuaEid.parseKapuaId(id);
return javaxPersitenceEntityManager.find(clazz, eid);
}
/**
* Find a {@link Serializable} by the given id and type
*
* @param clazz
* @param id
* @return
* @since 1.0.0
*/
public <E extends Serializable> E findWithLock(Class<E> clazz, Object id) {
return javaxPersitenceEntityManager.find(clazz, id, LockModeType.PESSIMISTIC_WRITE);
}
/**
* Merges a {@link Serializable} entity.
*
* @param entity The {@link Serializable} entity to merge.
* @since 1.2.0.
*/
public <E extends Serializable> void merge(E entity) {
javaxPersitenceEntityManager.merge(entity);
}
/**
* Merges a {@link KapuaEntity}
*
* @param entity The {@link KapuaEntity} to merge.
* @since 1.0.0.
*/
public <E extends KapuaEntity> void merge(E entity) {
merge((Serializable) entity);
}
/**
* Refresh a {@link Serializable} entity
*
* @param entity The {@link Serializable} entity to refresh.
* @since 1.2.0
*/
public <E extends Serializable> void refresh(E entity) {
javaxPersitenceEntityManager.refresh(entity);
}
/**
* Refresh a {@link KapuaEntity}
*
* @param entity The {@link KapuaEntity} to refresh.
* @since 1.0.0
*/
public <E extends KapuaEntity> void refresh(E entity) {
refresh((Serializable) entity);
}
/**
* Remove the entity
*
* @param entity
*/
public <E extends KapuaEntity> void remove(E entity) {
javaxPersitenceEntityManager.remove(entity);
}
/**
* Return the {@link javax.persistence.criteria.CriteriaBuilder}
*
* @return
*/
public CriteriaBuilder getCriteriaBuilder() {
return javaxPersitenceEntityManager.getCriteriaBuilder();
}
/**
* Return the typed query based on the criteria
*
* @param criteriaSelectQuery
* @return
*/
public <E> TypedQuery<E> createQuery(CriteriaQuery<E> criteriaSelectQuery) {
return javaxPersitenceEntityManager.createQuery(criteriaSelectQuery);
}
/**
* Return the typed query based on the query name
*
* @param queryName
* @param clazz
* @return
*/
public <E> TypedQuery<E> createNamedQuery(String queryName, Class<E> clazz) {
return javaxPersitenceEntityManager.createNamedQuery(queryName, clazz);
}
/**
* Return native query based on provided sql query
*
* @param querySelectUuidShort
* @return
*/
public <E> Query createNativeQuery(String querySelectUuidShort) {
return javaxPersitenceEntityManager.createNativeQuery(querySelectUuidShort);
}
}
|
package gr.grnet.escience.fs.pithos;
import gr.grnet.escience.commons.Utils;
import gr.grnet.escience.pithos.rest.HadoopPithosConnector;
import gr.grnet.escience.pithos.rest.PithosResponse;
import gr.grnet.escience.pithos.rest.PithosResponseFormat;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.util.Progressable;
/**
* This class implements a custom file system based on FIleSystem class of
* Hadoop 2.5.2. Essentially the main idea here, respects to the development of
* a custom File System that will be able to allow the interaction between
* hadoop and pithos storage system.
*
* @since March, 2015
* @author Dimitris G. Kelaidonis & Ioannis Stenos
* @version 0.1
*
*/
public class PithosFileSystem extends FileSystem {
private URI uri;
private static HadoopPithosConnector hadoopPithosConnector;
private Path workingDir;
private String pathToString;
private PithosPath pithosPath;
static String filename;
private String[] filesList;
private boolean exist = true;
private boolean isDir = false;
private long length = 0;
private PithosFileStatus pithos_file_status;
public static final Log LOG = LogFactory.getLog(PithosFileSystem.class);
public PithosFileSystem() {
}
public String getConfig(String param) {
Configuration conf = new Configuration();
String result = conf.get(param);
return result;
}
/**
* @return the instance of hadoop - pithos connector
*/
public static HadoopPithosConnector getHadoopPithosConnector() {
return hadoopPithosConnector;
}
/**
* Set thes instance of hadoop - pithos connector
*/
public static void setHadoopPithosConnector(
HadoopPithosConnector hadoopPithosConnector) {
PithosFileSystem.hadoopPithosConnector = hadoopPithosConnector;
}
@Override
public String getScheme() {
System.out.println("getScheme!");
return "pithos";
}
@Override
public URI getUri() {
System.out.println("GetUri!");
return uri;
}
@Override
public void initialize(URI uri, Configuration conf) throws IOException {
super.initialize(uri, conf);
System.out.println("Initialize!");
setConf(conf);
this.uri = URI.create(uri.getScheme() + "://" + uri.getAuthority());
System.out.println(this.uri.toString());
this.workingDir = new Path("/user", System.getProperty("user.name"));
// this.workingDir = new Path("/user", System.getProperty("user.name"))
// .makeQualified(this.uri, this.getWorkingDirectory());
System.out.println(this.workingDir.toString());
System.out.println("Create System Store connector");
// - Create instance of Hadoop connector
setHadoopPithosConnector(new HadoopPithosConnector(
getConfig("fs.pithos.url"), getConfig("auth.pithos.token"),
getConfig("auth.pithos.uuid")));
}
@Override
public Path getWorkingDirectory() {
System.out.println("getWorkingDirectory!");
return workingDir;
}
@Override
public void setWorkingDirectory(Path dir) {
System.out.println("SetWorkingDirectory!");
workingDir = makeAbsolute(dir);
}
private Path makeAbsolute(Path path) {
if (path.isAbsolute()) {
return path;
}
return new Path(workingDir, path);
}
/** This optional operation is not yet supported. */
@Override
public FSDataOutputStream append(Path f, int bufferSize,
Progressable progress) throws IOException {
System.out.println("append!");
throw new IOException("Not supported");
}
@Override
public long getDefaultBlockSize() {
System.out.println("blockSize!");
return getConf().getLongBytes("dfs.blocksize", 4 * 1024 * 1024);
}
@Override
public String getCanonicalServiceName() {
System.out.println("getcanonicalservicename!");
// Does not support Token
return null;
}
@Override
public FSDataOutputStream create(Path arg0, FsPermission arg1,
boolean arg2, int arg3, short arg4, long arg5, Progressable arg6)
throws IOException {
System.out.println("Create!");
// TODO Auto-generated method stub
return null;
}
@Override
public boolean delete(Path arg0, boolean arg1) throws IOException {
System.out.println("Delete!");
// TODO Auto-generated method stub
return false;
}
public boolean ContainerExistance(String container) {
PithosResponse containerInfo = getHadoopPithosConnector()
.getContainerInfo(container);
if (containerInfo.toString().contains("404")) {
return false;
} else {
return true;
}
}
@Override
public PithosFileStatus getFileStatus(Path targetPath) throws IOException {
System.out.println("here in getFileStatus BEFORE!");
System.out.println("Path: " + targetPath.toString());
// - Process the given path
pithosPath = new PithosPath(targetPath);
PithosResponse metadata = getHadoopPithosConnector()
.getPithosObjectMetaData(pithosPath.getContainer(),
pithosPath.getObjectAbsolutePath(), PithosResponseFormat.JSON);
if (metadata.toString().contains("404")) {
FileNotFoundException fnfe = new FileNotFoundException("File does not exist in Pithos FS.");
throw fnfe;
}
for (String obj : metadata.getResponseData().keySet()) {
if (obj != null) {
if (obj.matches("Content-Type") || obj.matches("Content_Type")) {
for (String fileType : metadata.getResponseData()
.get(obj)) {
if (fileType.contains("application/directory")) {
isDir = true;
break;
} else {
isDir = false;
}
}
}
}
}
if (isDir) {
pithos_file_status = new PithosFileStatus(true, getDefaultBlockSize(), false, targetPath);
} else {
for (String obj : metadata.getResponseData().keySet()) {
if (obj != null) {
if (obj.matches("Content-Length")) {
for (String lengthStr : metadata.getResponseData()
.get(obj)) {
length = Long.parseLong(lengthStr);
}
}
}
}
pithos_file_status = new PithosFileStatus(length, getDefaultBlockSize(), 123, targetPath);
}
System.out.println("here in getFileStatus AFTER!");
return pithos_file_status;
}
@Override
public FileStatus[] listStatus(Path f) throws FileNotFoundException,
IOException {
System.out.println("\n---> List Status Method!");
filename = "";
pithosPath = new PithosPath(f);
pathToString = pithosPath.toString();
pathToString = pathToString.substring(this.getScheme().toString()
.concat("://").length());
filesList = pathToString.split("/");
filename = filesList[filesList.length - 1];
int count = 2;
while (!filesList[filesList.length-count].equals(pithosPath.getContainer())){
filename = filesList[filesList.length-count]+"/"+filename;
count ++;
}
final List<FileStatus> result = new ArrayList<FileStatus>();
FileStatus fileStatus;
String files[] = getHadoopPithosConnector().getFileList(pithosPath.getContainer()).split("\\r?\\n");
// - Iterate on available files in the container
for (int i = 0; i < files.length; i++) {
String file = files[i].substring(files[i].lastIndexOf("/")+1);
files[i] = files[i].substring(0, (files[i].length() - file.length()));
if ((filename + "/").equals(files[i])) {
Path path = new Path("pithos://"+pithosPath.getContainer()+"/"+filename + "/" + file);
fileStatus = getFileStatus(path);
result.add(fileStatus);
}
}
// - Return the list of the available files
if (!result.isEmpty()) {
return result.toArray(new FileStatus[result.size()]);
} else {
return null;
}
}
@Override
public boolean mkdirs(Path arg0, FsPermission arg1) throws IOException {
System.out.println("Make dirs!");
// TODO Auto-generated method stub
return false;
}
@Override
public FSDataInputStream open(Path target_file, int buffer_size)
throws IOException {
// TODO: parse the container
pithosPath = new PithosPath(target_file);
return getHadoopPithosConnector().pithosObjectInputStream(
pithosPath.getContainer(), pithosPath.getObjectAbsolutePath());
}
@Override
public boolean rename(Path arg0, Path arg1) throws IOException {
System.out.println("rename!");
// TODO Auto-generated method stub
return false;
}
/**
*
* @param args
*/
public static void main(String[] args) {
// Stub so we can create a 'runnable jar' export for packing
// dependencies
Utils util = new Utils();
String out = null;
try {
out = util.computeHash("Lorem ipsum dolor sit amet.", "SHA-256");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Pithos FileSystem Connector loaded.");
System.out.println("Test hashing: " + out);
}
}
|
package com.intellij.psi.impl.meta;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicatorProvider;
import com.intellij.openapi.util.NullUtils;
import com.intellij.openapi.util.RecursionManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.filters.ElementFilter;
import com.intellij.psi.meta.MetaDataContributor;
import com.intellij.psi.meta.MetaDataRegistrar;
import com.intellij.psi.meta.PsiMetaData;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.CachedValuesManager;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.function.Supplier;
public class MetaRegistry extends MetaDataRegistrar {
private static final Logger LOG = Logger.getInstance(MetaRegistry.class);
private static final List<MyBinding> ourBindings = ContainerUtil.createLockFreeCopyOnWriteList();
private static volatile boolean ourContributorsLoaded;
public static PsiMetaData getMeta(final PsiElement element) {
return getMetaBase(element);
}
private static void ensureContributorsLoaded() {
if (!ourContributorsLoaded) {
synchronized (ourBindings) {
if (!ourContributorsLoaded) {
for (MetaDataContributor contributor : MetaDataContributor.EP_NAME.getExtensionList()) {
contributor.contributeMetaData(MetaDataRegistrar.getInstance());
}
ourContributorsLoaded = true;
}
}
}
}
@Nullable
public static PsiMetaData getMetaBase(PsiElement element) {
ProgressIndicatorProvider.checkCanceled();
return CachedValuesManager.getCachedValue(element, () -> {
ensureContributorsLoaded();
CachedValueProvider.Result<PsiMetaData> result = RecursionManager.doPreventingRecursion(element, false, () -> {
for (MyBinding binding : ourBindings) {
if (binding.myFilter.isClassAcceptable(element.getClass()) && binding.myFilter.isAcceptable(element, element.getParent())) {
PsiMetaData data = binding.myDataClass.get();
data.init(element);
Object[] dependencies = data.getDependencies();
if (NullUtils.hasNull(dependencies)) {
LOG.error(data + "(" + binding.myDataClass + ") provided null dependency");
}
return new CachedValueProvider.Result<>(data, ArrayUtil.append(dependencies, element));
}
}
return null;
});
if (result == null) {
return new CachedValueProvider.Result<>(null, element);
}
return result;
});
}
@Override
public <T extends PsiMetaData> void registerMetaData(ElementFilter filter, Class<T> metadataDescriptorClass) {
Supplier<? extends T> supplier = ()-> {
try {
return metadataDescriptorClass.newInstance();
}
catch (InstantiationException | IllegalAccessException e) {
LOG.error(e);
}
return null;
};
ourBindings.add(0, new MyBinding(filter, supplier));
}
private static class MyBinding {
private final ElementFilter myFilter;
private final Supplier<? extends PsiMetaData> myDataClass;
MyBinding(@NotNull ElementFilter filter, @NotNull Supplier<? extends PsiMetaData> dataClass) {
myFilter = filter;
myDataClass = dataClass;
}
}
}
|
package com.intellij.ui;
import com.intellij.util.ui.EditableModel;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* @author Konstantin Bulenkov
*/
class ListToolbarDecorator extends ToolbarDecorator {
private final JList myList;
private final EditableModel myEditableModel;
ListToolbarDecorator(JList list, @Nullable EditableModel editableModel) {
myList = list;
myEditableModel = editableModel;
myAddActionEnabled = myRemoveActionEnabled = myUpActionEnabled = myDownActionEnabled = true;
createActions();
myList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
updateButtons();
}
});
ListDataListener modelListener = new ListDataListener() {
@Override
public void intervalAdded(ListDataEvent e) {
updateButtons();
}
@Override
public void intervalRemoved(ListDataEvent e) {
updateButtons();
}
@Override
public void contentsChanged(ListDataEvent e) {
updateButtons();
}
};
myList.getModel().addListDataListener(modelListener);
myList.addPropertyChangeListener("model", evt -> {
if (evt.getOldValue() != null) {
((ListModel)evt.getOldValue()).removeListDataListener(modelListener);
}
if (evt.getNewValue() != null) {
((ListModel)evt.getNewValue()).addListDataListener(modelListener);
}
});
myList.addPropertyChangeListener("enabled", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateButtons();
}
});
}
private void createActions() {
myRemoveAction = new AnActionButtonRunnable() {
@Override
public void run(AnActionButton button) {
ListUtil.removeSelectedItems(myList);
updateButtons();
}
};
myUpAction = new AnActionButtonRunnable() {
@Override
public void run(AnActionButton button) {
ListUtil.moveSelectedItemsUp(myList);
updateButtons();
}
};
myDownAction = new AnActionButtonRunnable() {
@Override
public void run(AnActionButton button) {
ListUtil.moveSelectedItemsDown(myList);
updateButtons();
}
};
}
@Override
protected JComponent getComponent() {
return myList;
}
@Override
protected void updateButtons() {
final CommonActionsPanel p = getActionsPanel();
if (p != null) {
boolean someElementSelected;
if (myList.isEnabled()) {
final int index = myList.getSelectedIndex();
someElementSelected = 0 <= index && index < myList.getModel().getSize();
if (someElementSelected) {
final boolean downEnable = myList.getMaxSelectionIndex() < myList.getModel().getSize() - 1;
final boolean upEnable = myList.getMinSelectionIndex() > 0;
final boolean editEnabled = myList.getSelectedIndices().length == 1;
p.setEnabled(CommonActionsPanel.Buttons.EDIT, editEnabled);
p.setEnabled(CommonActionsPanel.Buttons.UP, upEnable);
p.setEnabled(CommonActionsPanel.Buttons.DOWN, downEnable);
}
else {
p.setEnabled(CommonActionsPanel.Buttons.EDIT, false);
p.setEnabled(CommonActionsPanel.Buttons.UP, false);
p.setEnabled(CommonActionsPanel.Buttons.DOWN, false);
}
p.setEnabled(CommonActionsPanel.Buttons.ADD, true);
}
else {
someElementSelected = false;
p.setEnabled(CommonActionsPanel.Buttons.ADD, false);
p.setEnabled(CommonActionsPanel.Buttons.UP, false);
p.setEnabled(CommonActionsPanel.Buttons.DOWN, false);
}
p.setEnabled(CommonActionsPanel.Buttons.REMOVE, someElementSelected);
updateExtraElementActions(someElementSelected);
}
}
@Override
public ToolbarDecorator setVisibleRowCount(int rowCount) {
myList.setVisibleRowCount(rowCount);
return this;
}
@Override
protected boolean isModelEditable() {
return myEditableModel != null || myList.getModel() instanceof EditableModel;
}
@Override
protected void installDnDSupport() {
RowsDnDSupport.install(myList, myEditableModel != null ? myEditableModel : (EditableModel)myList.getModel());
}
}
|
package com.intellij.ui.tabs.impl;
import com.intellij.ide.ui.UISettings;
import com.intellij.ide.ui.UISettingsListener;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.rd.RdIdeaKt;
import com.intellij.openapi.ui.*;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.IdeGlassPane;
import com.intellij.openapi.wm.IdeGlassPaneUtil;
import com.intellij.ui.ScreenUtil;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.scale.JBUIScale;
import com.intellij.ui.switcher.QuickActionProvider;
import com.intellij.ui.tabs.*;
import com.intellij.ui.tabs.impl.singleRow.ScrollableSingleRowLayout;
import com.intellij.ui.tabs.impl.singleRow.SingleRowLayout;
import com.intellij.ui.tabs.impl.singleRow.SingleRowPassInfo;
import com.intellij.ui.tabs.impl.table.TableLayout;
import com.intellij.util.Alarm;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.JBIterable;
import com.intellij.util.ui.*;
import com.intellij.util.ui.update.LazyUiDisposable;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.accessibility.*;
import javax.swing.*;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.plaf.ComponentUI;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;
import java.util.*;
import static com.intellij.openapi.wm.IdeFocusManager.getGlobalInstance;
public class JBTabsImpl extends JComponent
implements JBTabsEx, PropertyChangeListener, TimerListener, DataProvider, PopupMenuListener, Disposable, JBTabsPresentation, Queryable,
UISettingsListener, QuickActionProvider, Accessible {
@NonNls public static final Key<Integer> SIDE_TABS_SIZE_LIMIT_KEY = Key.create("SIDE_TABS_SIZE_LIMIT_KEY");
static final int MIN_TAB_WIDTH = JBUIScale.scale(75);
static final int DEFAULT_MAX_TAB_WIDTH = JBUIScale.scale(300);
private static final Comparator<TabInfo> ABC_COMPARATOR = (o1, o2) -> StringUtil.naturalCompare(o1.getText(), o2.getText());
private static final Logger LOG = Logger.getInstance(JBTabsImpl.class);
@NotNull final ActionManager myActionManager;
private final List<TabInfo> myVisibleInfos = new ArrayList<>();
private final Map<TabInfo, AccessibleTabPage> myInfo2Page = new HashMap<>();
private final Map<TabInfo, Integer> myHiddenInfos = new HashMap<>();
private TabInfo mySelectedInfo;
public final Map<TabInfo, TabLabel> myInfo2Label = new HashMap<>();
public final Map<TabInfo, Toolbar> myInfo2Toolbar = new HashMap<>();
public Dimension myHeaderFitSize;
private Insets myInnerInsets = JBUI.emptyInsets();
private final List<EventListener> myTabMouseListeners = ContainerUtil.createLockFreeCopyOnWriteList();
private final List<TabsListener> myTabListeners = ContainerUtil.createLockFreeCopyOnWriteList();
private boolean myFocused;
private Getter<? extends ActionGroup> myPopupGroup;
private String myPopupPlace;
TabInfo myPopupInfo;
final DefaultActionGroup myNavigationActions;
final PopupMenuListener myPopupListener;
JPopupMenu myActivePopup;
public boolean myHorizontalSide = true;
private boolean mySideComponentOnTabs = true;
private boolean mySideComponentBefore = true;
private final int mySeparatorWidth = JBUI.scale(1);
private DataProvider myDataProvider;
private final WeakHashMap<Component, Component> myDeferredToRemove = new WeakHashMap<>();
private SingleRowLayout mySingleRowLayout;
private final TableLayout myTableLayout = new TableLayout(this);
private final TabsSideSplitter mySplitter = new TabsSideSplitter(this);
private TabLayout myLayout;
private LayoutPassInfo myLastLayoutPass;
public boolean myForcedRelayout;
private UiDecorator myUiDecorator;
static final UiDecorator ourDefaultDecorator = new DefaultDecorator();
private boolean myPaintFocus;
private boolean myHideTabs;
@Nullable private Project myProject;
private boolean myRequestFocusOnLastFocusedComponent;
private boolean myListenerAdded;
final Set<TabInfo> myAttractions = new HashSet<>();
private final Animator myAnimator;
private List<TabInfo> myAllTabs;
private IdeFocusManager myFocusManager;
private static final boolean myAdjustBorders = true;
private Set<JBTabsImpl> myNestedTabs = new HashSet<>();
private JBTabsImpl myParentTabs = null;
boolean myAddNavigationGroup = true;
private boolean myDisposed;
private Color myActiveTabFillIn;
private boolean myTabLabelActionsAutoHide;
private final TabActionsAutoHideListener myTabActionsAutoHideListener = new TabActionsAutoHideListener();
private Disposable myTabActionsAutoHideListenerDisposable = Disposer.newDisposable();
private IdeGlassPane myGlassPane;
@NonNls private static final String LAYOUT_DONE = "Layout.done";
@NonNls public static final String STRETCHED_BY_WIDTH = "Layout.stretchedByWidth";
private TimedDeadzone.Length myTabActionsMouseDeadzone = TimedDeadzone.DEFAULT;
private long myRemoveDeferredRequest;
private JBTabsPosition myPosition = JBTabsPosition.top;
private final JBTabsBorder myBorder = createTabBorder();
private final BaseNavigationAction myNextAction;
private final BaseNavigationAction myPrevAction;
private boolean myTabDraggingEnabled;
private DragHelper myDragHelper;
private boolean myNavigationActionsEnabled = true;
protected TabInfo myDropInfo;
private int myDropInfoIndex;
protected boolean myShowDropLocation = true;
private TabInfo myOldSelection;
private SelectionChangeHandler mySelectionChangeHandler;
private Runnable myDeferredFocusRequest;
private int myFirstTabOffset;
private final TabPainterAdapter myTabPainterAdapter = createTabPainterAdapter();
protected final JBTabPainter myTabPainter = myTabPainterAdapter.getTabPainter();
private boolean myAlphabeticalMode;
private boolean mySupportsCompression;
private String myEmptyText;
private boolean myMouseInsideTabsArea;
private boolean myRemoveNotifyInProgress;
protected JBTabsBorder createTabBorder() {
return new JBDefaultTabsBorder(this);
}
public JBTabPainter getTabPainter() {
return myTabPainter;
}
TabPainterAdapter getTabPainterAdapter() {
return myTabPainterAdapter;
}
protected TabPainterAdapter createTabPainterAdapter() {
return new DefaultTabPainterAdapter(JBTabPainter.getDEFAULT());
}
private TabLabel tabLabelAtMouse;
public JBTabsImpl(@NotNull Project project) {
this(project, project);
}
private JBTabsImpl(@NotNull Project project, @NotNull Disposable parent) {
this(project, ActionManager.getInstance(), IdeFocusManager.getInstance(project), parent);
}
public JBTabsImpl(@Nullable Project project, IdeFocusManager focusManager, @NotNull Disposable parent) {
this(project, ActionManager.getInstance(), focusManager, parent);
}
public JBTabsImpl(@Nullable Project project, @NotNull ActionManager actionManager, IdeFocusManager focusManager, @NotNull Disposable parent) {
myProject = project;
myActionManager = actionManager;
myFocusManager = focusManager != null ? focusManager : getGlobalInstance();
setOpaque(true);
setBackground(myTabPainter.getBackgroundColor());
setBorder(myBorder);
Disposer.register(parent, this);
myNavigationActions = new DefaultActionGroup();
myNextAction = new SelectNextAction(this, myActionManager);
myPrevAction = new SelectPreviousAction(this, myActionManager);
myNavigationActions.add(myNextAction);
myNavigationActions.add(myPrevAction);
setUiDecorator(null);
mySingleRowLayout = createSingleRowLayout();
myLayout = mySingleRowLayout;
mySplitter.getDivider().setOpaque(false);
myPopupListener = new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(final PopupMenuEvent e) {
}
@Override
public void popupMenuWillBecomeInvisible(final PopupMenuEvent e) {
disposePopupListener();
}
@Override
public void popupMenuCanceled(final PopupMenuEvent e) {
disposePopupListener();
}
};
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(final MouseEvent e) {
if (mySingleRowLayout.myLastSingRowLayout != null &&
mySingleRowLayout.myLastSingRowLayout.moreRect != null &&
mySingleRowLayout.myLastSingRowLayout.moreRect.contains(e.getPoint())) {
showMorePopup(e);
}
}
});
addMouseWheelListener(event -> {
int units = event.getUnitsToScroll();
if (units == 0) return;
if (mySingleRowLayout.myLastSingRowLayout != null) {
mySingleRowLayout.scroll((int)(event.getPreciseWheelRotation() * mySingleRowLayout.getScrollUnitIncrement()));
revalidateAndRepaint(false);
}
});
AWTEventListener listener = new AWTEventListener() {
final Alarm afterScroll = new Alarm(JBTabsImpl.this);
@Override
public void eventDispatched(AWTEvent event) {
if (mySingleRowLayout.myLastSingRowLayout == null) return;
MouseEvent me = (MouseEvent)event;
Point point = me.getPoint();
SwingUtilities.convertPointToScreen(point, me.getComponent());
Rectangle rect = getVisibleRect();
rect = rect.intersection(mySingleRowLayout.myLastSingRowLayout.tabRectangle);
Point p = rect.getLocation();
SwingUtilities.convertPointToScreen(p, JBTabsImpl.this);
rect.setLocation(p);
boolean inside = rect.contains(point);
if (inside != myMouseInsideTabsArea) {
myMouseInsideTabsArea = inside;
afterScroll.cancelAllRequests();
if (!inside) {
afterScroll.addRequest(() -> {
// here is no any "isEDT"-checks <== this task should be called in EDT <==
// <== Alarm instance executes tasks in EDT <== used constructor of Alarm uses EDT for tasks by default
if (!myMouseInsideTabsArea) {
relayout(false, false);
}
}, 500);
}
}
}
};
Toolkit.getDefaultToolkit().addAWTEventListener(listener, AWTEvent.MOUSE_MOTION_EVENT_MASK);
Disposer.register(this, () -> {
Toolkit toolkit = Toolkit.getDefaultToolkit();
if (toolkit != null) {
toolkit.removeAWTEventListener(listener);
}
});
myAnimator = new Animator("JBTabs Attractions", 2, 500, true) {
@Override
public void paintNow(final int frame, final int totalFrames, final int cycle) {
repaintAttractions();
}
};
setFocusTraversalPolicyProvider(true);
setFocusTraversalPolicy(new LayoutFocusTraversalPolicy() {
@Override
public Component getDefaultComponent(final Container aContainer) {
return getToFocus();
}
});
new LazyUiDisposable<JBTabsImpl>(parent, this, this) {
@Override
protected void initialize(@NotNull Disposable parent, @NotNull JBTabsImpl child, @Nullable Project project) {
if (myProject == null && project != null) {
myProject = project;
}
Disposer.register(child, myAnimator);
Disposer.register(child, () -> removeTimerUpdate());
IdeGlassPane gp = IdeGlassPaneUtil.find(child);
myTabActionsAutoHideListenerDisposable = Disposer.newDisposable("myTabActionsAutoHideListener");
Disposer.register(child, myTabActionsAutoHideListenerDisposable);
gp.addMouseMotionPreprocessor(myTabActionsAutoHideListener, myTabActionsAutoHideListenerDisposable);
myGlassPane = gp;
UIUtil.addAwtListener(__ -> {
if (mySingleRowLayout.myMorePopup != null) return;
processFocusChange();
}, AWTEvent.FOCUS_EVENT_MASK, child);
myDragHelper = new DragHelper(child);
myDragHelper.start();
if (myProject != null && myFocusManager == getGlobalInstance()) {
myFocusManager = IdeFocusManager.getInstance(myProject);
}
}
};
UIUtil.putClientProperty(
this, UIUtil.NOT_IN_HIERARCHY_COMPONENTS,
(Iterable<JComponent>)() -> JBIterable.from(getVisibleInfos()).filter(Conditions.not(Conditions.is(mySelectedInfo))).transform(
info -> info.getComponent()).iterator());
}
public boolean isMouseInsideTabsArea() {
return myMouseInsideTabsArea;
}
@Override
public void uiSettingsChanged(UISettings uiSettings) {
for (Map.Entry<TabInfo, TabLabel> entry : myInfo2Label.entrySet()) {
entry.getKey().revalidate();
entry.getValue().updateActionLabelPosition();
}
boolean oldHideTabsIfNeeded = mySingleRowLayout instanceof ScrollableSingleRowLayout;
boolean newHideTabsIfNeeded = UISettings.getInstance().getHideTabsIfNeeded();
if (oldHideTabsIfNeeded != newHideTabsIfNeeded) {
updateRowLayout();
}
}
private void updateRowLayout() {
boolean wasSingleRow = isSingleRow();
mySingleRowLayout = createSingleRowLayout();
if (wasSingleRow) {
myLayout = mySingleRowLayout;
}
relayout(true, true);
}
protected SingleRowLayout createSingleRowLayout() {
return new ScrollableSingleRowLayout(this);
}
@Override
public JBTabs setNavigationActionBinding(String prevActionId, String nextActionId) {
if (myNextAction != null) {
myNextAction.reconnect(nextActionId);
}
if (myPrevAction != null) {
myPrevAction.reconnect(prevActionId);
}
return this;
}
public void setHovered(TabLabel label) {
TabLabel old = tabLabelAtMouse;
tabLabelAtMouse = label;
if(old != null) {
old.repaint();
}
if(tabLabelAtMouse != null) {
tabLabelAtMouse.repaint();
}
}
void unHover(TabLabel label) {
if(tabLabelAtMouse == label) {
tabLabelAtMouse = null;
label.repaint();
}
}
protected boolean isHoveredTab(TabLabel label) {
return label != null && label == tabLabelAtMouse;
}
protected boolean isActiveTabs(TabInfo info) {
return UIUtil.isFocusAncestor(this);
}
@Override
public boolean isEditorTabs() {
return false;
}
public boolean supportsCompression() {
return mySupportsCompression;
}
@Override
public JBTabs setNavigationActionsEnabled(boolean enabled) {
myNavigationActionsEnabled = enabled;
return this;
}
@Override
public final boolean isDisposed() {
return myDisposed;
}
public void addNestedTabs(JBTabsImpl tabs) {
myNestedTabs.add(tabs);
tabs.myParentTabs = this;
}
public void removeNestedTabs(JBTabsImpl tabs) {
myNestedTabs.remove(tabs);
tabs.myParentTabs = null;
}
public static Image getComponentImage(TabInfo info) {
JComponent cmp = info.getComponent();
BufferedImage img;
if (cmp.isShowing()) {
final int width = cmp.getWidth();
final int height = cmp.getHeight();
img = UIUtil.createImage(info.getComponent(), width > 0 ? width : 500, height > 0 ? height : 500, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = img.createGraphics();
cmp.paint(g);
}
else {
img = UIUtil.createImage(info.getComponent(), 500, 500, BufferedImage.TYPE_INT_ARGB);
}
return img;
}
@Override
public void dispose() {
myDisposed = true;
mySelectedInfo = null;
myDeferredFocusRequest = null;
resetTabsCache();
myAttractions.clear();
myVisibleInfos.clear();
myUiDecorator = null;
myActivePopup = null;
myInfo2Label.clear();
myInfo2Page.clear();
myInfo2Toolbar.clear();
myTabListeners.clear();
myLastLayoutPass = null;
if (myParentTabs != null) myParentTabs.removeNestedTabs(this);
}
void resetTabsCache() {
ApplicationManager.getApplication().assertIsDispatchThread();
myAllTabs = null;
}
private void processFocusChange() {
Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
if (owner == null) {
setFocused(false);
return;
}
if (owner == this || SwingUtilities.isDescendingFrom(owner, this)) {
setFocused(true);
}
else {
setFocused(false);
}
}
private void repaintAttractions() {
boolean needsUpdate = false;
for (TabInfo each : myVisibleInfos) {
TabLabel eachLabel = myInfo2Label.get(each);
needsUpdate |= eachLabel.repaintAttraction();
}
if (needsUpdate) {
relayout(true, false);
}
}
@Override
public void addNotify() {
super.addNotify();
addTimerUpdate();
if (myDeferredFocusRequest != null) {
final Runnable request = myDeferredFocusRequest;
myDeferredFocusRequest = null;
request.run();
}
}
@Override
public void remove(int index) {
if (myRemoveNotifyInProgress) {
LOG.warn(new IllegalStateException("removeNotify in progress"));
}
super.remove(index);
}
@Override
public void removeAll() {
if (myRemoveNotifyInProgress) {
LOG.warn(new IllegalStateException("removeNotify in progress"));
}
super.removeAll();
}
@Override
public void removeNotify() {
try {
myRemoveNotifyInProgress = true;
super.removeNotify();
}
finally {
myRemoveNotifyInProgress = false;
}
setFocused(false);
removeTimerUpdate();
if (ScreenUtil.isStandardAddRemoveNotify(this) && myGlassPane != null) {
Disposer.dispose(myTabActionsAutoHideListenerDisposable);
myTabActionsAutoHideListenerDisposable = Disposer.newDisposable();
myGlassPane = null;
}
}
@Override
public void processMouseEvent(MouseEvent e) {
super.processMouseEvent(e);
}
private void addTimerUpdate() {
if (!myListenerAdded) {
myActionManager.addTimerListener(500, this);
myListenerAdded = true;
}
}
private void removeTimerUpdate() {
if (myListenerAdded) {
myActionManager.removeTimerListener(this);
myListenerAdded = false;
}
}
public void layoutComp(SingleRowPassInfo data, int deltaX, int deltaY, int deltaWidth, int deltaHeight) {
JComponent hToolbar = data.hToolbar.get();
JComponent vToolbar = data.vToolbar.get();
if (hToolbar != null) {
final int toolbarHeight = hToolbar.getPreferredSize().height;
final int hSeparatorHeight = toolbarHeight > 0 ? 1 : 0;
final Rectangle compRect = layoutComp(deltaX, toolbarHeight + hSeparatorHeight + deltaY, data.comp.get(), deltaWidth, deltaHeight);
layout(hToolbar, compRect.x, compRect.y - toolbarHeight - hSeparatorHeight, compRect.width, toolbarHeight);
}
else if (vToolbar != null) {
final int toolbarWidth = vToolbar.getPreferredSize().width;
final int vSeparatorWidth = toolbarWidth > 0 ? 1 : 0;
if (mySideComponentBefore) {
final Rectangle compRect = layoutComp(toolbarWidth + vSeparatorWidth + deltaX, deltaY, data.comp.get(), deltaWidth, deltaHeight);
layout(vToolbar, compRect.x - toolbarWidth - vSeparatorWidth, compRect.y, toolbarWidth, compRect.height);
}
else {
final Rectangle compRect = layoutComp(new Rectangle(deltaX, deltaY, getWidth() - toolbarWidth - vSeparatorWidth, getHeight()),
data.comp.get(), deltaWidth, deltaHeight);
layout(vToolbar, compRect.x + compRect.width + vSeparatorWidth, compRect.y, toolbarWidth, compRect.height);
}
}
else {
layoutComp(deltaX, deltaY, data.comp.get(), deltaWidth, deltaHeight);
}
}
public boolean isDropTarget(TabInfo info) {
return myDropInfo != null && myDropInfo == info;
}
private void setDropInfoIndex(int dropInfoIndex) {
myDropInfoIndex = dropInfoIndex;
}
public int getFirstTabOffset() {
return myFirstTabOffset;
}
@Override
public void setFirstTabOffset(int firstTabOffset) {
myFirstTabOffset = firstTabOffset;
}
@Override
public JBTabsPresentation setEmptyText(@Nullable String text) {
myEmptyText = text;
return this;
}
public int tabMSize() {
return 20;
}
/**
* TODO use {@link RdIdeaKt#childAtMouse(IdeGlassPane, Container)}
*/
@Deprecated
class TabActionsAutoHideListener extends MouseMotionAdapter implements Weighted {
private TabLabel myCurrentOverLabel;
private Point myLastOverPoint;
@Override
public double getWeight() {
return 1;
}
@Override
public void mouseMoved(final MouseEvent e) {
if (!myTabLabelActionsAutoHide) return;
myLastOverPoint = SwingUtilities.convertPoint(e.getComponent(), e.getX(), e.getY(), JBTabsImpl.this);
processMouseOver();
}
void processMouseOver() {
if (!myTabLabelActionsAutoHide) return;
if (myLastOverPoint == null) return;
if (myLastOverPoint.x >= 0 && myLastOverPoint.x < getWidth() && myLastOverPoint.y > 0 && myLastOverPoint.y < getHeight()) {
final TabLabel label = myInfo2Label.get(_findInfo(myLastOverPoint, true));
if (label != null) {
if (myCurrentOverLabel != null) {
myCurrentOverLabel.toggleShowActions(false);
}
label.toggleShowActions(true);
myCurrentOverLabel = label;
return;
}
}
if (myCurrentOverLabel != null) {
myCurrentOverLabel.toggleShowActions(false);
myCurrentOverLabel = null;
}
}
}
@Override
public ModalityState getModalityState() {
return ModalityState.stateForComponent(this);
}
@Override
public void run() {
updateTabActions(false);
}
@Override
public void updateTabActions(final boolean validateNow) {
final Ref<Boolean> changed = new Ref<>(Boolean.FALSE);
for (final TabInfo eachInfo : myInfo2Label.keySet()) {
final boolean changes = myInfo2Label.get(eachInfo).updateTabActions();
changed.set(changed.get().booleanValue() || changes);
}
if (changed.get()) {
revalidateAndRepaint();
}
}
@Override
public boolean canShowMorePopup() {
final SingleRowPassInfo lastLayout = mySingleRowLayout.myLastSingRowLayout;
return lastLayout != null && lastLayout.moreRect != null;
}
@Override
public void showMorePopup(@Nullable final MouseEvent e) {
final SingleRowPassInfo lastLayout = mySingleRowLayout.myLastSingRowLayout;
if (lastLayout == null) {
return;
}
mySingleRowLayout.myMorePopup = new JBPopupMenu();
for (final TabInfo each : getVisibleInfos()) {
if (!mySingleRowLayout.isTabHidden(each)) continue;
final JBMenuItem item = new JBMenuItem(each.getText(), each.getIcon());
item.setForeground(each.getDefaultForeground());
item.setBackground(each.getTabColor());
mySingleRowLayout.myMorePopup.add(item);
item.addActionListener(__ -> select(each, true));
}
mySingleRowLayout.myMorePopup.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(final PopupMenuEvent e) {
}
@Override
public void popupMenuWillBecomeInvisible(final PopupMenuEvent e) {
mySingleRowLayout.myMorePopup = null;
}
@Override
public void popupMenuCanceled(final PopupMenuEvent e) {
mySingleRowLayout.myMorePopup = null;
}
});
if (e != null) {
mySingleRowLayout.myMorePopup.show(this, e.getX(), e.getY());
}
else {
final Rectangle rect = lastLayout.moreRect;
if (rect != null) {
mySingleRowLayout.myMorePopup.show(this, rect.x, rect.y + rect.height);
}
}
}
@Nullable
private JComponent getToFocus() {
final TabInfo info = getSelectedInfo();
if (info == null) return null;
JComponent toFocus = null;
if (isRequestFocusOnLastFocusedComponent() && info.getLastFocusOwner() != null && !isMyChildIsFocusedNow()) {
toFocus = info.getLastFocusOwner();
}
if (toFocus == null) {
toFocus = info.getPreferredFocusableComponent();
if (toFocus == null) {
return null;
}
final JComponent policyToFocus = myFocusManager.getFocusTargetFor(toFocus);
if (policyToFocus != null) {
toFocus = policyToFocus;
}
}
return toFocus;
}
@Override
public void requestFocus() {
final JComponent toFocus = getToFocus();
if (toFocus != null) {
getGlobalInstance().doWhenFocusSettlesDown(() -> getGlobalInstance().requestFocus(toFocus, true));
}
else {
getGlobalInstance().doWhenFocusSettlesDown(() -> super.requestFocus());
}
}
@Override
public boolean requestFocusInWindow() {
final JComponent toFocus = getToFocus();
return toFocus != null ? toFocus.requestFocusInWindow() : super.requestFocusInWindow();
}
@Override
@NotNull
public TabInfo addTab(TabInfo info, int index) {
return addTab(info, index, false, true);
}
@Override
public TabInfo addTabSilently(TabInfo info, int index) {
return addTab(info, index, false, false);
}
private TabInfo addTab(TabInfo info, int index, boolean isDropTarget, boolean fireEvents) {
if (!isDropTarget && getTabs().contains(info)) {
return getTabs().get(getTabs().indexOf(info));
}
info.getChangeSupport().addPropertyChangeListener(this);
final TabLabel label = createTabLabel(info);
Disposer.register(this, label);
myInfo2Label.put(info, label);
myInfo2Page.put(info, new AccessibleTabPage(info));
if (!isDropTarget) {
if (index < 0 || index > myVisibleInfos.size() - 1) {
myVisibleInfos.add(info);
}
else {
myVisibleInfos.add(index, info);
}
}
resetTabsCache();
updateText(info);
updateIcon(info);
updateSideComponent(info);
updateTabActions(info);
add(label);
adjust(info);
updateAll(false);
if (info.isHidden()) {
updateHiding();
}
if (!isDropTarget && fireEvents) {
if (getTabCount() == 1) {
fireBeforeSelectionChanged(null, info);
fireSelectionChanged(null, info);
}
}
revalidateAndRepaint(false);
return info;
}
protected TabLabel createTabLabel(TabInfo info) {
return new TabLabel(this, info);
}
@Override
@NotNull
public TabInfo addTab(TabInfo info) {
return addTab(info, -1);
}
@Override
public TabLabel getTabLabel(TabInfo info) {
return myInfo2Label.get(info);
}
@Nullable
public ActionGroup getPopupGroup() {
return myPopupGroup != null ? myPopupGroup.get() : null;
}
String getPopupPlace() {
return myPopupPlace;
}
@Override
@NotNull
public JBTabs setPopupGroup(@NotNull final ActionGroup popupGroup, @NotNull String place, final boolean addNavigationGroup) {
return setPopupGroup(() -> popupGroup, place, addNavigationGroup);
}
@Override
@NotNull
public JBTabs setPopupGroup(@NotNull final Getter<? extends ActionGroup> popupGroup,
@NotNull final String place,
final boolean addNavigationGroup) {
myPopupGroup = popupGroup;
myPopupPlace = place;
myAddNavigationGroup = addNavigationGroup;
return this;
}
private void updateAll(final boolean forcedRelayout) {
mySelectedInfo = getSelectedInfo();
updateContainer(forcedRelayout, false);
removeDeferred();
updateListeners();
updateTabActions(false);
updateEnabling();
}
private boolean isMyChildIsFocusedNow() {
final Component owner = getFocusOwner();
if (owner == null) return false;
if (mySelectedInfo != null) {
if (!SwingUtilities.isDescendingFrom(owner, mySelectedInfo.getComponent())) return false;
}
return SwingUtilities.isDescendingFrom(owner, this);
}
@Nullable
private static JComponent getFocusOwner() {
final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
return (JComponent)(owner instanceof JComponent ? owner : null);
}
@Override
@NotNull
public ActionCallback select(@NotNull TabInfo info, boolean requestFocus) {
return _setSelected(info, requestFocus);
}
@NotNull
private ActionCallback _setSelected(final TabInfo info, final boolean requestFocus) {
if (!isEnabled()) {
return ActionCallback.REJECTED;
}
if (mySelectionChangeHandler != null) {
return mySelectionChangeHandler.execute(info, requestFocus, new ActiveRunnable() {
@NotNull
@Override
public ActionCallback run() {
return executeSelectionChange(info, requestFocus);
}
});
}
return executeSelectionChange(info, requestFocus);
}
@NotNull
private ActionCallback executeSelectionChange(TabInfo info, boolean requestFocus) {
if (mySelectedInfo != null && mySelectedInfo.equals(info)) {
if (!requestFocus) {
return ActionCallback.DONE;
}
else {
Component owner = myFocusManager.getFocusOwner();
JComponent c = info.getComponent();
if (c != null && owner != null) {
if (c == owner || SwingUtilities.isDescendingFrom(owner, c)) {
return ActionCallback.DONE;
}
}
return requestFocus(getToFocus());
}
}
if (myRequestFocusOnLastFocusedComponent && mySelectedInfo != null) {
if (isMyChildIsFocusedNow()) {
mySelectedInfo.setLastFocusOwner(getFocusOwner());
}
}
TabInfo oldInfo = mySelectedInfo;
mySelectedInfo = info;
final TabInfo newInfo = getSelectedInfo();
if (myRequestFocusOnLastFocusedComponent && newInfo != null) {
newInfo.setLastFocusOwner(null);
}
TabLabel label = myInfo2Label.get(info);
if(label != null) {
setComponentZOrder(label, 0);
}
boolean oldValue = myMouseInsideTabsArea;
try {
fireBeforeSelectionChanged(oldInfo, newInfo);
} finally {
myMouseInsideTabsArea = oldValue;
}
updateContainer(false, true);
fireSelectionChanged(oldInfo, newInfo);
if (requestFocus) {
final JComponent toFocus = getToFocus();
if (myProject != null && toFocus != null) {
final ActionCallback result = new ActionCallback();
requestFocus(toFocus).doWhenProcessed(() -> {
if (myDisposed) {
result.setRejected();
}
else {
removeDeferred().notifyWhenDone(result);
}
});
return result;
}
else {
requestFocus();
return removeDeferred();
}
}
else {
return removeDeferred();
}
}
private void fireBeforeSelectionChanged(@Nullable TabInfo oldInfo, TabInfo newInfo) {
if (oldInfo != newInfo) {
myOldSelection = oldInfo;
try {
for (TabsListener eachListener : myTabListeners) {
eachListener.beforeSelectionChanged(oldInfo, newInfo);
}
}
finally {
myOldSelection = null;
}
}
}
private void fireSelectionChanged(@Nullable TabInfo oldInfo, TabInfo newInfo) {
if (oldInfo != newInfo) {
for (TabsListener eachListener : myTabListeners) {
if (eachListener != null) {
eachListener.selectionChanged(oldInfo, newInfo);
}
}
}
}
void fireTabsMoved() {
for (TabsListener eachListener : myTabListeners) {
if (eachListener != null) {
eachListener.tabsMoved();
}
}
}
private void fireTabRemoved(@NotNull TabInfo info) {
for (TabsListener eachListener : myTabListeners) {
if (eachListener != null) {
eachListener.tabRemoved(info);
}
}
}
@NotNull
private ActionCallback requestFocus(final JComponent toFocus) {
if (toFocus == null) return ActionCallback.DONE;
if (isShowing()) {
return myFocusManager.requestFocusInProject(toFocus, myProject);
}
return ActionCallback.REJECTED;
}
@NotNull
private ActionCallback removeDeferred() {
if (myDeferredToRemove.isEmpty()) {
return ActionCallback.DONE;
}
final ActionCallback callback = new ActionCallback();
final long executionRequest = ++myRemoveDeferredRequest;
final Runnable onDone = () -> {
if (myRemoveDeferredRequest == executionRequest) {
removeDeferredNow();
}
callback.setDone();
};
myFocusManager.doWhenFocusSettlesDown(onDone);
return callback;
}
private void queueForRemove(Component c) {
if (c instanceof JComponent) {
addToDeferredRemove(c);
}
else {
remove(c);
}
}
private void unqueueFromRemove(Component c) {
myDeferredToRemove.remove(c);
}
private void removeDeferredNow() {
for (Component each : myDeferredToRemove.keySet()) {
if (each != null && each.getParent() == this) {
remove(each);
}
}
myDeferredToRemove.clear();
}
@Override
public void propertyChange(final PropertyChangeEvent evt) {
final TabInfo tabInfo = (TabInfo)evt.getSource();
if (TabInfo.ACTION_GROUP.equals(evt.getPropertyName())) {
updateSideComponent(tabInfo);
relayout(false, false);
}
else if (TabInfo.COMPONENT.equals(evt.getPropertyName())) {
relayout(true, false);
}
else if (TabInfo.TEXT.equals(evt.getPropertyName())) {
updateText(tabInfo);
}
else if (TabInfo.ICON.equals(evt.getPropertyName())) {
updateIcon(tabInfo);
}
else if (TabInfo.TAB_COLOR.equals(evt.getPropertyName())) {
revalidateAndRepaint();
}
else if (TabInfo.ALERT_STATUS.equals(evt.getPropertyName())) {
boolean start = ((Boolean)evt.getNewValue()).booleanValue();
updateAttraction(tabInfo, start);
}
else if (TabInfo.TAB_ACTION_GROUP.equals(evt.getPropertyName())) {
updateTabActions(tabInfo);
relayout(false, false);
}
else if (TabInfo.HIDDEN.equals(evt.getPropertyName())) {
updateHiding();
relayout(false, false);
}
else if (TabInfo.ENABLED.equals(evt.getPropertyName())) {
updateEnabling();
}
}
private void updateEnabling() {
final List<TabInfo> all = getTabs();
for (TabInfo each : all) {
final TabLabel eachLabel = myInfo2Label.get(each);
eachLabel.setTabEnabled(each.isEnabled());
}
final TabInfo selected = getSelectedInfo();
if (selected != null && !selected.isEnabled()) {
final TabInfo toSelect = getToSelectOnRemoveOf(selected);
if (toSelect != null) {
select(toSelect, myFocusManager.getFocusedDescendantFor(this) != null);
}
}
}
private void updateHiding() {
boolean update = false;
Iterator<TabInfo> visible = myVisibleInfos.iterator();
while (visible.hasNext()) {
TabInfo each = visible.next();
if (each.isHidden() && !myHiddenInfos.containsKey(each)) {
myHiddenInfos.put(each, myVisibleInfos.indexOf(each));
visible.remove();
update = true;
}
}
Iterator<TabInfo> hidden = myHiddenInfos.keySet().iterator();
while (hidden.hasNext()) {
TabInfo each = hidden.next();
if (!each.isHidden() && myHiddenInfos.containsKey(each)) {
myVisibleInfos.add(getIndexInVisibleArray(each), each);
hidden.remove();
update = true;
}
}
if (update) {
resetTabsCache();
if (mySelectedInfo != null && myHiddenInfos.containsKey(mySelectedInfo)) {
mySelectedInfo = getToSelectOnRemoveOf(mySelectedInfo);
}
updateAll(true);
}
}
private int getIndexInVisibleArray(TabInfo each) {
Integer info = myHiddenInfos.get(each);
int index = info == null ? myVisibleInfos.size() : info.intValue();
if (index > myVisibleInfos.size()) {
index = myVisibleInfos.size();
}
if (index < 0) {
index = 0;
}
return index;
}
private void updateIcon(final TabInfo tabInfo) {
myInfo2Label.get(tabInfo).setIcon(tabInfo.getIcon());
revalidateAndRepaint();
}
public void revalidateAndRepaint() {
revalidateAndRepaint(true);
}
protected void revalidateAndRepaint(final boolean layoutNow) {
if (myVisibleInfos.isEmpty()) {
setOpaque(false);
Component nonOpaque = UIUtil.findUltimateParent(this);
if (getParent() != null) {
final Rectangle toRepaint = SwingUtilities.convertRectangle(getParent(), getBounds(), nonOpaque);
nonOpaque.repaint(toRepaint.x, toRepaint.y, toRepaint.width, toRepaint.height);
}
}
else {
setOpaque(true);
}
if (layoutNow) {
validate();
}
else {
revalidate();
}
repaint();
}
private void updateAttraction(final TabInfo tabInfo, boolean start) {
if (start) {
myAttractions.add(tabInfo);
}
else {
myAttractions.remove(tabInfo);
tabInfo.setBlinkCount(0);
}
if (start && !myAnimator.isRunning()) {
myAnimator.resume();
}
else if (!start && myAttractions.isEmpty()) {
myAnimator.suspend();
repaintAttractions();
}
}
private void updateText(final TabInfo tabInfo) {
final TabLabel label = myInfo2Label.get(tabInfo);
label.setText(tabInfo.getColoredText());
label.setToolTipText(tabInfo.getTooltipText());
revalidateAndRepaint();
}
private void updateSideComponent(final TabInfo tabInfo) {
final Toolbar old = myInfo2Toolbar.get(tabInfo);
if (old != null) {
remove(old);
}
final Toolbar toolbar = createToolbarComponent(tabInfo);
myInfo2Toolbar.put(tabInfo, toolbar);
add(toolbar);
}
private void updateTabActions(final TabInfo info) {
myInfo2Label.get(info).setTabActions(info.getTabLabelActions());
}
@Override
@Nullable
public TabInfo getSelectedInfo() {
if (myOldSelection != null) return myOldSelection;
if (!myVisibleInfos.contains(mySelectedInfo)) {
mySelectedInfo = null;
}
return mySelectedInfo != null ? mySelectedInfo : !myVisibleInfos.isEmpty() ? myVisibleInfos.get(0) : null;
}
@Override
@Nullable
public TabInfo getToSelectOnRemoveOf(TabInfo info) {
if (!myVisibleInfos.contains(info)) return null;
if (mySelectedInfo != info) return null;
if (myVisibleInfos.size() == 1) return null;
int index = getVisibleInfos().indexOf(info);
TabInfo result = null;
if (index > 0) {
result = findEnabledBackward(index, false);
}
if (result == null) {
result = findEnabledForward(index, false);
}
return result;
}
@Nullable
TabInfo findEnabledForward(int from, boolean cycle) {
if (from < 0) return null;
int index = from;
List<TabInfo> infos = getVisibleInfos();
while (true) {
index++;
if (index == infos.size()) {
if (!cycle) break;
index = 0;
}
if (index == from) break;
final TabInfo each = infos.get(index);
if (each.isEnabled()) return each;
}
return null;
}
public boolean isAlphabeticalMode() {
return myAlphabeticalMode;
}
@Nullable
TabInfo findEnabledBackward(int from, boolean cycle) {
if (from < 0) return null;
int index = from;
List<TabInfo> infos = getVisibleInfos();
while (true) {
index
if (index == -1) {
if (!cycle) break;
index = infos.size() - 1;
}
if (index == from) break;
final TabInfo each = infos.get(index);
if (each.isEnabled()) return each;
}
return null;
}
private Toolbar createToolbarComponent(final TabInfo tabInfo) {
return new Toolbar(this, tabInfo);
}
@Override
@NotNull
public TabInfo getTabAt(final int tabIndex) {
return getTabs().get(tabIndex);
}
@Override
@NotNull
public List<TabInfo> getTabs() {
ApplicationManager.getApplication().assertIsDispatchThread();
if (myAllTabs != null) return myAllTabs;
ArrayList<TabInfo> result = new ArrayList<>(myVisibleInfos);
for (TabInfo each : myHiddenInfos.keySet()) {
result.add(getIndexInVisibleArray(each), each);
}
if (isAlphabeticalMode()) {
Collections.sort(result, ABC_COMPARATOR);
}
myAllTabs = result;
return result;
}
@Override
public TabInfo getTargetInfo() {
return myPopupInfo != null ? myPopupInfo : getSelectedInfo();
}
@Override
public void popupMenuWillBecomeVisible(final PopupMenuEvent e) {
}
@Override
public void popupMenuWillBecomeInvisible(final PopupMenuEvent e) {
resetPopup();
}
@Override
public void popupMenuCanceled(final PopupMenuEvent e) {
resetPopup();
}
private void resetPopup() {
//todo [kirillk] dirty hack, should rely on ActionManager to understand that menu item was either chosen on or cancelled
SwingUtilities.invokeLater(() -> {
// No need to reset popup info if a new popup has been already opened and myPopupInfo refers to the corresponding info.
if (myActivePopup == null) {
myPopupInfo = null;
}
});
}
@Override
public void setPaintBlocked(boolean blocked, final boolean takeSnapshot) {
}
private void addToDeferredRemove(final Component c) {
if (!myDeferredToRemove.containsKey(c)) {
myDeferredToRemove.put(c, c);
}
}
@Override
@NotNull
public JBTabsPresentation setToDrawBorderIfTabsHidden(final boolean toDrawBorderIfTabsHidden) {
return this;
}
@Override
@NotNull
public JBTabs getJBTabs() {
return this;
}
public static class Toolbar extends JPanel {
public Toolbar(JBTabsImpl tabs, TabInfo info) {
setLayout(new BorderLayout());
final ActionGroup group = info.getGroup();
final JComponent side = info.getSideComponent();
if (group != null) {
final String place = info.getPlace();
ActionToolbar toolbar = tabs.myActionManager.createActionToolbar(place != null ? place : "JBTabs", group, tabs.myHorizontalSide);
toolbar.setTargetComponent(info.getActionsContextComponent());
final JComponent actionToolbar = toolbar.getComponent();
add(actionToolbar, BorderLayout.CENTER);
}
if (side != null) {
if (group != null) {
add(side, BorderLayout.EAST);
}
else {
add(side, BorderLayout.CENTER);
}
}
UIUtil.uiTraverser(this).forEach(c -> c.setFocusable(false));
}
public boolean isEmpty() {
return getComponentCount() == 0;
}
}
@Override
public void doLayout() {
try {
myHeaderFitSize = computeHeaderFitSize();
final Collection<TabLabel> labels = myInfo2Label.values();
for (TabLabel each : labels) {
each.setTabActionsAutoHide(myTabLabelActionsAutoHide);
}
List<TabInfo> visible = new ArrayList<>(getVisibleInfos());
if (myDropInfo != null && !visible.contains(myDropInfo) && myShowDropLocation) {
if (getDropInfoIndex() >= 0 && getDropInfoIndex() < visible.size()) {
visible.add(getDropInfoIndex(), myDropInfo);
}
else {
visible.add(myDropInfo);
}
}
if (isSingleRow()) {
mySingleRowLayout.scrollSelectionInView();
myLastLayoutPass = mySingleRowLayout.layoutSingleRow(visible);
myTableLayout.myLastTableLayout = null;
OnePixelDivider divider = mySplitter.getDivider();
if (divider.getParent() == this) {
int location = getTabsPosition() == JBTabsPosition.left
? mySingleRowLayout.myLastSingRowLayout.tabRectangle.width
: getWidth() - mySingleRowLayout.myLastSingRowLayout.tabRectangle.width;
divider.setBounds(location, 0, 1, getHeight());
}
}
else {
myLastLayoutPass = myTableLayout.layoutTable(visible);
mySingleRowLayout.myLastSingRowLayout = null;
}
moveDraggedTabLabel();
myTabActionsAutoHideListener.processMouseOver();
}
finally {
myForcedRelayout = false;
}
applyResetComponents();
}
void moveDraggedTabLabel() {
if (myDragHelper != null && myDragHelper.myDragRec != null) {
final TabLabel selectedLabel = myInfo2Label.get(getSelectedInfo());
if (selectedLabel != null) {
final Rectangle bounds = selectedLabel.getBounds();
if (isHorizontalTabs()) {
selectedLabel.setBounds(myDragHelper.myDragRec.x, bounds.y, bounds.width, bounds.height);
}
else {
selectedLabel.setBounds(bounds.x, myDragHelper.myDragRec.y, bounds.width, bounds.height);
}
}
}
}
private Dimension computeHeaderFitSize() {
final Max max = computeMaxSize();
if (myPosition == JBTabsPosition.top || myPosition == JBTabsPosition.bottom) {
return new Dimension(getSize().width, myHorizontalSide ? Math.max(max.myLabel.height, max.myToolbar.height) : max.myLabel.height);
}
return new Dimension(max.myLabel.width + (myHorizontalSide ? 0 : max.myToolbar.width), getSize().height);
}
public Rectangle layoutComp(int componentX, int componentY, final JComponent comp, int deltaWidth, int deltaHeight) {
return layoutComp(new Rectangle(componentX, componentY, getWidth(), getHeight()), comp, deltaWidth, deltaHeight);
}
public Rectangle layoutComp(final Rectangle bounds, final JComponent comp, int deltaWidth, int deltaHeight) {
final Insets insets = getLayoutInsets();
final Insets inner = getInnerInsets();
int x = insets.left + bounds.x + inner.left;
int y = insets.top + bounds.y + inner.top;
int width = bounds.width - insets.left - insets.right - bounds.x - inner.left - inner.right;
int height = bounds.height - insets.top - insets.bottom - bounds.y - inner.top - inner.bottom;
if (!isHideTabs()) {
width += deltaWidth;
height += deltaHeight;
}
return layout(comp, x, y, width, height);
}
@Override
public JBTabsPresentation setInnerInsets(final Insets innerInsets) {
myInnerInsets = innerInsets;
return this;
}
private Insets getInnerInsets() {
return myInnerInsets;
}
public Insets getLayoutInsets() {
return myBorder.getEffectiveBorder();
}
public int getToolbarInset() {
return getArcSize() + 1;
}
public void resetLayout(boolean resetLabels) {
for (TabInfo each : myVisibleInfos) {
reset(each, resetLabels);
}
if (myDropInfo != null) {
reset(myDropInfo, resetLabels);
}
for (TabInfo each : myHiddenInfos.keySet()) {
reset(each, resetLabels);
}
for (Component eachDeferred : myDeferredToRemove.keySet()) {
resetLayout((JComponent)eachDeferred);
}
}
private void reset(final TabInfo each, final boolean resetLabels) {
final JComponent c = each.getComponent();
if (c != null) {
resetLayout(c);
}
resetLayout(myInfo2Toolbar.get(each));
if (resetLabels) {
resetLayout(myInfo2Label.get(each));
}
}
private static int getArcSize() {
return 4;
}
protected JBTabsPosition getPosition() {
return myPosition;
}
/**
* @deprecated You should implement {@link JBTabsBorder} interface
*/
@Deprecated
protected void doPaintBackground(Graphics2D g2d, Rectangle clip) {
}
@Override
protected void paintComponent(final Graphics g) {
super.paintComponent(g);
if (myVisibleInfos.isEmpty()) {
if (myEmptyText != null) {
UISettings.setupAntialiasing(g);
UIUtil.drawCenteredString((Graphics2D)g, getBounds(), myEmptyText);
}
return;
}
myTabPainter.fillBackground((Graphics2D)g, new Rectangle(0, 0, getWidth(), getHeight()));
drawBorder(g);
drawToolbarSeparator(g);
}
private void drawToolbarSeparator(Graphics g) {
Toolbar toolbar = myInfo2Toolbar.get(getSelectedInfo());
if (toolbar != null && toolbar.getParent() == this && !mySideComponentOnTabs && !myHorizontalSide && isHideTabs()) {
Rectangle bounds = toolbar.getBounds();
if (bounds.width > 0) {
if (mySideComponentBefore) {
getTabPainter().paintBorderLine((Graphics2D)g, mySeparatorWidth,
new Point(bounds.x + bounds.width, bounds.y),
new Point(bounds.x + bounds.width, bounds.y + bounds.height));
}
else {
getTabPainter().paintBorderLine((Graphics2D)g, mySeparatorWidth,
new Point(bounds.x - mySeparatorWidth, bounds.y),
new Point(bounds.x - mySeparatorWidth, bounds.y + bounds.height));
}
}
}
}
protected TabLabel getSelectedLabel() {
return myInfo2Label.get(getSelectedInfo());
}
protected List<TabInfo> getVisibleInfos() {
if (!isAlphabeticalMode()) {
return myVisibleInfos;
} else {
List<TabInfo> sortedCopy = new ArrayList<>(myVisibleInfos);
Collections.sort(sortedCopy, ABC_COMPARATOR);
return sortedCopy;
}
}
protected LayoutPassInfo getLastLayoutPass() {
return myLastLayoutPass;
}
public static int getSelectionTabVShift() {
return 2;
}
private boolean isNavigationVisible() {
return myVisibleInfos.size() > 1;
}
@Override
protected Graphics getComponentGraphics(Graphics graphics) {
return JBSwingUtilities.runGlobalCGTransform(this, super.getComponentGraphics(graphics));
}
@Override
protected void paintChildren(final Graphics g) {
super.paintChildren(g);
mySingleRowLayout.myMoreIcon.paintIcon(this, g);
}
protected void drawBorder(Graphics g) {
if (!isHideTabs()) {
myBorder.paintBorder(this, g, 0, 0, getWidth(), getHeight());
}
}
private Max computeMaxSize() {
Max max = new Max();
for (TabInfo eachInfo : myVisibleInfos) {
final TabLabel label = myInfo2Label.get(eachInfo);
max.myLabel.height = Math.max(max.myLabel.height, label.getPreferredSize().height);
max.myLabel.width = Math.max(max.myLabel.width, label.getPreferredSize().width);
final Toolbar toolbar = myInfo2Toolbar.get(eachInfo);
if (myLayout.isSideComponentOnTabs() && toolbar != null && !toolbar.isEmpty()) {
max.myToolbar.height = Math.max(max.myToolbar.height, toolbar.getPreferredSize().height);
max.myToolbar.width = Math.max(max.myToolbar.width, toolbar.getPreferredSize().width);
}
}
if (getTabsPosition().isSide()) {
if (mySplitter.getSideTabsLimit() > 0) {
max.myLabel.width = Math.min(max.myLabel.width, mySplitter.getSideTabsLimit());
}
}
max.myToolbar.height++;
return max;
}
@Override
public Dimension getMinimumSize() {
return computeSize(component -> component.getMinimumSize(), 1);
}
@Override
public Dimension getPreferredSize() {
return computeSize(component -> component.getPreferredSize(), 3);
}
private Dimension computeSize(Function<? super JComponent, ? extends Dimension> transform, int tabCount) {
Dimension size = new Dimension();
for (TabInfo each : myVisibleInfos) {
final JComponent c = each.getComponent();
if (c != null) {
final Dimension eachSize = transform.fun(c);
size.width = Math.max(eachSize.width, size.width);
size.height = Math.max(eachSize.height, size.height);
}
}
addHeaderSize(size, tabCount);
return size;
}
private void addHeaderSize(Dimension size, final int tabsCount) {
Dimension header = computeHeaderPreferredSize(tabsCount);
final boolean horizontal = getTabsPosition() == JBTabsPosition.top || getTabsPosition() == JBTabsPosition.bottom;
if (horizontal) {
size.height += header.height;
size.width = Math.max(size.width, header.width);
}
else {
size.height += Math.max(size.height, header.height);
size.width += header.width;
}
final Insets insets = getLayoutInsets();
size.width += insets.left + insets.right + 1;
size.height += insets.top + insets.bottom + 1;
}
private Dimension computeHeaderPreferredSize(int tabsCount) {
final Iterator<TabInfo> infos = myInfo2Label.keySet().iterator();
Dimension size = new Dimension();
int currentTab = 0;
final boolean horizontal = getTabsPosition() == JBTabsPosition.top || getTabsPosition() == JBTabsPosition.bottom;
while (infos.hasNext()) {
final boolean canGrow = currentTab < tabsCount;
TabInfo eachInfo = infos.next();
final TabLabel eachLabel = myInfo2Label.get(eachInfo);
final Dimension eachPrefSize = eachLabel.getPreferredSize();
if (horizontal) {
if (canGrow) {
size.width += eachPrefSize.width;
}
size.height = Math.max(size.height, eachPrefSize.height);
}
else {
size.width = Math.max(size.width, eachPrefSize.width);
if (canGrow) {
size.height += eachPrefSize.height;
}
}
currentTab++;
}
if (horizontal) {
size.height += myBorder.getThickness();
}
else {
size.width += myBorder.getThickness();
}
return size;
}
@Override
public int getTabCount() {
return getTabs().size();
}
@Override
@NotNull
public JBTabsPresentation getPresentation() {
return this;
}
@Override
@NotNull
public ActionCallback removeTab(final TabInfo info) {
return removeTab(info, null, true);
}
@Override
@NotNull
public ActionCallback removeTab(final TabInfo info, @Nullable TabInfo forcedSelectionTransfer, boolean transferFocus) {
return removeTab(info, forcedSelectionTransfer, transferFocus, false);
}
@NotNull
private ActionCallback removeTab(TabInfo info, @Nullable TabInfo forcedSelectionTransfer, boolean transferFocus, boolean isDropTarget) {
if (myRemoveNotifyInProgress) {
LOG.warn(new IllegalStateException("removeNotify in progress"));
}
if (myPopupInfo == info) myPopupInfo = null;
if (!isDropTarget) {
if (info == null || !getTabs().contains(info)) return ActionCallback.DONE;
}
if (isDropTarget && myLastLayoutPass != null) {
myLastLayoutPass.myVisibleInfos.remove(info);
}
final ActionCallback result = new ActionCallback();
TabInfo toSelect;
if (forcedSelectionTransfer == null) {
toSelect = getToSelectOnRemoveOf(info);
}
else {
assert myVisibleInfos.contains(forcedSelectionTransfer) : "Cannot find tab for selection transfer, tab=" + forcedSelectionTransfer;
toSelect = forcedSelectionTransfer;
}
if (toSelect != null) {
boolean clearSelection = info.equals(mySelectedInfo);
processRemove(info, false);
if (clearSelection) {
mySelectedInfo = info;
}
_setSelected(toSelect, transferFocus).doWhenProcessed(() -> removeDeferred().notifyWhenDone(result));
}
else {
processRemove(info, true);
removeDeferred().notifyWhenDone(result);
}
if (myVisibleInfos.isEmpty()) {
removeDeferredNow();
}
revalidateAndRepaint(true);
fireTabRemoved(info);
return result;
}
private void processRemove(final TabInfo info, boolean forcedNow) {
remove(myInfo2Label.get(info));
remove(myInfo2Toolbar.get(info));
JComponent tabComponent = info.getComponent();
if (!isToDeferRemoveForLater(tabComponent) || forcedNow) {
remove(tabComponent);
}
else {
queueForRemove(tabComponent);
}
TabLabel tabLabel = myInfo2Label.get(info);
if (tabLabel != null) {
Disposer.dispose(tabLabel);
}
myVisibleInfos.remove(info);
myHiddenInfos.remove(info);
myInfo2Label.remove(info);
myInfo2Page.remove(info);
myInfo2Toolbar.remove(info);
resetTabsCache();
updateAll(false);
}
@Nullable
@Override
public TabInfo findInfo(Component component) {
for (TabInfo each : getTabs()) {
if (each.getComponent() == component) return each;
}
return null;
}
@Override
public TabInfo findInfo(MouseEvent event) {
final Point point = SwingUtilities.convertPoint(event.getComponent(), event.getPoint(), this);
return _findInfo(point, false);
}
@Override
public TabInfo findInfo(final Object object) {
for (int i = 0; i < getTabCount(); i++) {
final TabInfo each = getTabAt(i);
final Object eachObject = each.getObject();
if (eachObject != null && eachObject.equals(object)) return each;
}
return null;
}
@Nullable
private TabInfo _findInfo(final Point point, boolean labelsOnly) {
Component component = findComponentAt(point);
if (component == null) return null;
while (component != this || component != null) {
if (component instanceof TabLabel) {
return ((TabLabel)component).getInfo();
}
if (!labelsOnly) {
final TabInfo info = findInfo(component);
if (info != null) return info;
}
if (component == null) break;
component = component.getParent();
}
return null;
}
@Override
public void removeAllTabs() {
for (TabInfo each : getTabs()) {
removeTab(each);
}
}
private static class Max {
final Dimension myLabel = new Dimension();
final Dimension myToolbar = new Dimension();
}
private void updateContainer(boolean forced, final boolean layoutNow) {
if (myProject != null && !myProject.isOpen()) return;
for (TabInfo each : new ArrayList<>(myVisibleInfos)) {
final JComponent eachComponent = each.getComponent();
if (getSelectedInfo() == each && getSelectedInfo() != null) {
unqueueFromRemove(eachComponent);
final Container parent = eachComponent.getParent();
if (parent != null && parent != this) {
parent.remove(eachComponent);
}
if (eachComponent.getParent() == null) {
add(eachComponent);
}
}
else {
if (eachComponent.getParent() == null) continue;
if (isToDeferRemoveForLater(eachComponent)) {
queueForRemove(eachComponent);
}
else {
remove(eachComponent);
}
}
}
mySingleRowLayout.scrollSelectionInView();
relayout(forced, layoutNow);
}
@Override
protected void addImpl(final Component comp, final Object constraints, final int index) {
unqueueFromRemove(comp);
if (comp instanceof TabLabel) {
((TabLabel)comp).apply(myUiDecorator != null ? myUiDecorator.getDecoration() : ourDefaultDecorator.getDecoration());
}
super.addImpl(comp, constraints, index);
}
private static boolean isToDeferRemoveForLater(JComponent c) {
return c.getRootPane() != null;
}
void relayout(boolean forced, final boolean layoutNow) {
if (!myForcedRelayout) {
myForcedRelayout = forced;
}
revalidateAndRepaint(layoutNow);
}
public int getBorderThickness() {
return myBorder.getThickness();
}
@Override
@NotNull
public JBTabs addTabMouseListener(@NotNull MouseListener listener) {
removeListeners();
myTabMouseListeners.add(listener);
addListeners();
return this;
}
@Override
@NotNull
public JComponent getComponent() {
return this;
}
private void addListeners() {
for (TabInfo eachInfo : myVisibleInfos) {
final TabLabel label = myInfo2Label.get(eachInfo);
for (EventListener eachListener : myTabMouseListeners) {
if (eachListener instanceof MouseListener) {
label.addMouseListener((MouseListener)eachListener);
}
else if (eachListener instanceof MouseMotionListener) {
label.addMouseMotionListener((MouseMotionListener)eachListener);
}
else {
assert false;
}
}
}
}
private void removeListeners() {
for (TabInfo eachInfo : myVisibleInfos) {
final TabLabel label = myInfo2Label.get(eachInfo);
for (EventListener eachListener : myTabMouseListeners) {
if (eachListener instanceof MouseListener) {
label.removeMouseListener((MouseListener)eachListener);
}
else if (eachListener instanceof MouseMotionListener) {
label.removeMouseMotionListener((MouseMotionListener)eachListener);
}
else {
assert false;
}
}
}
}
private void updateListeners() {
removeListeners();
addListeners();
}
@Override
public JBTabs addListener(@NotNull TabsListener listener) {
myTabListeners.add(listener);
return this;
}
@Override
public JBTabs setSelectionChangeHandler(SelectionChangeHandler handler) {
mySelectionChangeHandler = handler;
return this;
}
public void setFocused(final boolean focused) {
if (myFocused == focused) return;
myFocused = focused;
if (myPaintFocus) {
repaint();
}
}
@Override
public int getIndexOf(@Nullable final TabInfo tabInfo) {
return getVisibleInfos().indexOf(tabInfo);
}
@Override
public boolean isHideTabs() {
return myHideTabs;
}
@Override
public void setHideTabs(final boolean hideTabs) {
if (isHideTabs() == hideTabs) return;
myHideTabs = hideTabs;
relayout(true, false);
}
@Override
public JBTabsPresentation setPaintBorder(int top, int left, int right, int bottom) {
return this;
}
@Override
public JBTabsPresentation setTabSidePaintBorder(int size) {
return this;
}
@Override
@NotNull
public JBTabsPresentation setActiveTabFillIn(@Nullable final Color color) {
if (!isChanged(myActiveTabFillIn, color)) return this;
myActiveTabFillIn = color;
revalidateAndRepaint(false);
return this;
}
private static boolean isChanged(Object oldObject, Object newObject) {
return !Comparing.equal(oldObject, newObject);
}
@Override
@NotNull
public JBTabsPresentation setTabLabelActionsAutoHide(final boolean autoHide) {
if (myTabLabelActionsAutoHide != autoHide) {
myTabLabelActionsAutoHide = autoHide;
revalidateAndRepaint(false);
}
return this;
}
@Override
public JBTabsPresentation setFocusCycle(final boolean root) {
setFocusCycleRoot(root);
return this;
}
@Override
public JBTabsPresentation setPaintFocus(final boolean paintFocus) {
myPaintFocus = paintFocus;
return this;
}
private abstract static class BaseNavigationAction extends AnAction {
private final ShadowAction myShadow;
@NotNull private final ActionManager myActionManager;
private final JBTabsImpl myTabs;
BaseNavigationAction(@NotNull String copyFromID, @NotNull JBTabsImpl tabs, @NotNull ActionManager mgr) {
myActionManager = mgr;
myTabs = tabs;
myShadow = new ShadowAction(this, myActionManager.getAction(copyFromID), tabs, tabs);
setEnabledInModalContext(true);
}
@Override
public final void update(@NotNull final AnActionEvent e) {
JBTabsImpl tabs = (JBTabsImpl)e.getData(NAVIGATION_ACTIONS_KEY);
e.getPresentation().setVisible(tabs != null);
if (tabs == null) return;
tabs = findNavigatableTabs(tabs);
e.getPresentation().setEnabled(tabs != null);
if (tabs != null) {
_update(e, tabs, tabs.getVisibleInfos().indexOf(tabs.getSelectedInfo()));
}
}
@Nullable
JBTabsImpl findNavigatableTabs(JBTabsImpl tabs) {
// The debugger UI contains multiple nested JBTabsImpl, where the innermost JBTabsImpl has only one tab. In this case,
// the action should target the outer JBTabsImpl.
if (tabs == null || tabs != myTabs) {
return null;
}
if (tabs.isNavigatable()) {
return tabs;
}
Component c = tabs.getParent();
while (c != null) {
if (c instanceof JBTabsImpl && ((JBTabsImpl)c).isNavigatable()) {
return (JBTabsImpl)c;
}
c = c.getParent();
}
return null;
}
public void reconnect(String actionId) {
myShadow.reconnect(myActionManager.getAction(actionId));
}
protected abstract void _update(AnActionEvent e, final JBTabsImpl tabs, int selectedIndex);
@Override
public final void actionPerformed(@NotNull final AnActionEvent e) {
JBTabsImpl tabs = (JBTabsImpl)e.getData(NAVIGATION_ACTIONS_KEY);
tabs = findNavigatableTabs(tabs);
if (tabs == null) return;
List<TabInfo> infos;
int index;
while (true) {
infos = tabs.getVisibleInfos();
index = infos.indexOf(tabs.getSelectedInfo());
if (index == -1) return;
if (borderIndex(infos, index) && tabs.navigatableParent() != null) {
tabs = tabs.navigatableParent();
} else {
break;
}
}
_actionPerformed(e, tabs, index);
}
protected abstract boolean borderIndex(List<TabInfo> infos, int index);
protected abstract void _actionPerformed(final AnActionEvent e, final JBTabsImpl tabs, final int selectedIndex);
}
private static class SelectNextAction extends BaseNavigationAction {
private SelectNextAction(JBTabsImpl tabs, @NotNull ActionManager mgr) {
super(IdeActions.ACTION_NEXT_TAB, tabs, mgr);
}
@Override
protected void _update(final AnActionEvent e, final JBTabsImpl tabs, int selectedIndex) {
e.getPresentation().setEnabled(tabs.findEnabledForward(selectedIndex, true) != null);
}
@Override
protected boolean borderIndex(List<TabInfo> infos, int index) {
return index == infos.size() - 1;
}
@Override
protected void _actionPerformed(final AnActionEvent e, final JBTabsImpl tabs, final int selectedIndex) {
TabInfo tabInfo = tabs.findEnabledForward(selectedIndex, true);
if (tabInfo != null) {
JComponent lastFocus = tabInfo.getLastFocusOwner();
tabs.select(tabInfo, true);
tabs.myNestedTabs.stream()
.filter((nestedTabs) -> (lastFocus == null) || SwingUtilities.isDescendingFrom(lastFocus, nestedTabs))
.forEach((nestedTabs) -> {
nestedTabs.selectFirstVisible();
});
}
}
}
protected boolean isNavigatable() {
final int selectedIndex = getVisibleInfos().indexOf(getSelectedInfo());
return isNavigationVisible() && selectedIndex >= 0 && myNavigationActionsEnabled;
}
private JBTabsImpl navigatableParent() {
Component c = getParent();
while (c != null) {
if (c instanceof JBTabsImpl && ((JBTabsImpl)c).isNavigatable()) {
return (JBTabsImpl)c;
}
c = c.getParent();
}
return null;
}
private void selectFirstVisible() {
if (!isNavigatable()) return;
TabInfo select = getVisibleInfos().get(0);
JComponent lastFocus = select.getLastFocusOwner();
select(select, true);
myNestedTabs.stream()
.filter((nestedTabs) -> (lastFocus == null) || SwingUtilities.isDescendingFrom(lastFocus, nestedTabs))
.forEach((nestedTabs) -> {
nestedTabs.selectFirstVisible();
});
}
private void selectLastVisible() {
if (!isNavigatable()) return;
int last = getVisibleInfos().size() - 1;
TabInfo select = getVisibleInfos().get(last);
JComponent lastFocus = select.getLastFocusOwner();
select(select, true);
myNestedTabs.stream()
.filter((nestedTabs) -> (lastFocus == null) || SwingUtilities.isDescendingFrom(lastFocus, nestedTabs))
.forEach((nestedTabs) -> {
nestedTabs.selectLastVisible();
});
}
private static class SelectPreviousAction extends BaseNavigationAction {
private SelectPreviousAction(JBTabsImpl tabs, @NotNull ActionManager mgr) {
super(IdeActions.ACTION_PREVIOUS_TAB, tabs, mgr);
}
@Override
protected void _update(final AnActionEvent e, final JBTabsImpl tabs, int selectedIndex) {
e.getPresentation().setEnabled(tabs.findEnabledBackward(selectedIndex, true) != null);
}
@Override
protected boolean borderIndex(List<TabInfo> infos, int index) {
return index == 0;
}
@Override
protected void _actionPerformed(final AnActionEvent e, final JBTabsImpl tabs, final int selectedIndex) {
TabInfo tabInfo = tabs.findEnabledBackward(selectedIndex, true);
if (tabInfo != null) {
JComponent lastFocus = tabInfo.getLastFocusOwner();
tabs.select(tabInfo, true);
tabs.myNestedTabs.stream()
.filter((nestedTabs) -> (lastFocus == null) || SwingUtilities.isDescendingFrom(lastFocus, nestedTabs))
.forEach((nestedTabs) -> {
nestedTabs.selectLastVisible();
});
}
}
}
private void disposePopupListener() {
if (myActivePopup != null) {
myActivePopup.removePopupMenuListener(myPopupListener);
myActivePopup = null;
}
}
@Override
public JBTabsPresentation setSideComponentVertical(final boolean vertical) {
myHorizontalSide = !vertical;
for (TabInfo each : myVisibleInfos) {
each.getChangeSupport().firePropertyChange(TabInfo.ACTION_GROUP, "new1", "new2");
}
relayout(true, false);
return this;
}
@Override
public JBTabsPresentation setSideComponentOnTabs(boolean onTabs) {
mySideComponentOnTabs = onTabs;
relayout(true, false);
return this;
}
@Override
public JBTabsPresentation setSideComponentBefore(boolean before) {
mySideComponentBefore = before;
relayout(true, false);
return this;
}
@Override
public JBTabsPresentation setSingleRow(boolean singleRow) {
myLayout = singleRow ? mySingleRowLayout : myTableLayout;
relayout(true, false);
return this;
}
public int getSeparatorWidth() {
return mySeparatorWidth;
}
public boolean useSmallLabels() {
return false;
}
public boolean useBoldLabels() {
return false;
}
@Override
public boolean isSingleRow() {
return getEffectiveLayout() == mySingleRowLayout;
}
public boolean isSideComponentVertical() {
return !myHorizontalSide;
}
public boolean isSideComponentOnTabs() {
return mySideComponentOnTabs;
}
public boolean isSideComponentBefore() {
return mySideComponentBefore;
}
public TabLayout getEffectiveLayout() {
if (myLayout == myTableLayout && getTabsPosition() == JBTabsPosition.top) return myTableLayout;
return mySingleRowLayout;
}
@Override
public JBTabsPresentation setUiDecorator(@Nullable UiDecorator decorator) {
myUiDecorator = decorator == null ? ourDefaultDecorator : decorator;
applyDecoration();
return this;
}
@Override
protected void setUI(final ComponentUI newUI) {
super.setUI(newUI);
applyDecoration();
}
@Override
public void updateUI() {
super.updateUI();
SwingUtilities.invokeLater(() -> {
applyDecoration();
revalidateAndRepaint(false);
});
}
private void applyDecoration() {
if (myUiDecorator != null) {
UiDecorator.UiDecoration uiDecoration = myUiDecorator.getDecoration();
for (TabLabel each : myInfo2Label.values()) {
each.apply(uiDecoration);
}
}
for (TabInfo each : getTabs()) {
adjust(each);
}
relayout(true, false);
}
private static void adjust(final TabInfo each) {
if (myAdjustBorders) {
UIUtil.removeScrollBorder(each.getComponent());
}
}
@Override
public void sortTabs(Comparator<? super TabInfo> comparator) {
Collections.sort(myVisibleInfos, comparator);
relayout(true, false);
}
private boolean isRequestFocusOnLastFocusedComponent() {
return myRequestFocusOnLastFocusedComponent;
}
@Override
public JBTabsPresentation setRequestFocusOnLastFocusedComponent(final boolean requestFocusOnLastFocusedComponent) {
myRequestFocusOnLastFocusedComponent = requestFocusOnLastFocusedComponent;
return this;
}
@Override
@Nullable
public Object getData(@NotNull @NonNls final String dataId) {
if (myDataProvider != null) {
final Object value = myDataProvider.getData(dataId);
if (value != null) return value;
}
if (QuickActionProvider.KEY.getName().equals(dataId)) {
return this;
}
return NAVIGATION_ACTIONS_KEY.is(dataId) ? this : null;
}
@NotNull
@Override
public List<AnAction> getActions(boolean originalProvider) {
ArrayList<AnAction> result = new ArrayList<>();
TabInfo selection = getSelectedInfo();
if (selection != null) {
ActionGroup group = selection.getGroup();
if (group != null) {
AnAction[] children = group.getChildren(null);
Collections.addAll(result, children);
}
}
return result;
}
@Override
public DataProvider getDataProvider() {
return myDataProvider;
}
@Override
public JBTabsImpl setDataProvider(@NotNull final DataProvider dataProvider) {
myDataProvider = dataProvider;
return this;
}
static boolean isSelectionClick(final MouseEvent e, boolean canBeQuick) {
if (e.getClickCount() == 1 || canBeQuick) {
if (!e.isPopupTrigger()) {
return e.getButton() == MouseEvent.BUTTON1 && !e.isControlDown() && !e.isAltDown() && !e.isMetaDown();
}
}
return false;
}
private static class DefaultDecorator implements UiDecorator {
@Override
@NotNull
public UiDecoration getDecoration() {
return new UiDecoration(null, new JBInsets(5, 12, 5, 12));
}
}
public Rectangle layout(JComponent c, Rectangle bounds) {
final Rectangle now = c.getBounds();
if (!bounds.equals(now)) {
c.setBounds(bounds);
}
c.doLayout();
c.putClientProperty(LAYOUT_DONE, Boolean.TRUE);
return bounds;
}
public Rectangle layout(JComponent c, int x, int y, int width, int height) {
return layout(c, new Rectangle(x, y, width, height));
}
public static void resetLayout(JComponent c) {
if (c == null) return;
c.putClientProperty(LAYOUT_DONE, null);
c.putClientProperty(STRETCHED_BY_WIDTH, null);
}
private void applyResetComponents() {
for (int i = 0; i < getComponentCount(); i++) {
final Component each = getComponent(i);
if (each instanceof JComponent) {
final JComponent jc = (JComponent)each;
if (!UIUtil.isClientPropertyTrue(jc, LAYOUT_DONE)) {
layout(jc, new Rectangle(0, 0, 0, 0));
}
}
}
}
@Override
@NotNull
public JBTabsPresentation setTabLabelActionsMouseDeadzone(final TimedDeadzone.Length length) {
myTabActionsMouseDeadzone = length;
final List<TabInfo> all = getTabs();
for (TabInfo each : all) {
final TabLabel eachLabel = myInfo2Label.get(each);
eachLabel.updateTabActions();
}
return this;
}
@Override
@NotNull
public JBTabsPresentation setTabsPosition(final JBTabsPosition position) {
myPosition = position;
OnePixelDivider divider = mySplitter.getDivider();
if (position.isSide() && divider.getParent() == null) {
add(divider);
} else if (divider.getParent() == this){
remove(divider);
}
relayout(true, false);
return this;
}
@Override
public JBTabsPosition getTabsPosition() {
return myPosition;
}
public TimedDeadzone.Length getTabActionsMouseDeadzone() {
return myTabActionsMouseDeadzone;
}
@Override
public JBTabsPresentation setTabDraggingEnabled(boolean enabled) {
myTabDraggingEnabled = enabled;
return this;
}
@Override
public JBTabsPresentation setAlphabeticalMode(boolean alphabeticalMode) {
myAlphabeticalMode = alphabeticalMode;
return this;
}
@Override
public JBTabsPresentation setSupportsCompression(boolean supportsCompression) {
mySupportsCompression = supportsCompression;
updateRowLayout();
return this;
}
public boolean isTabDraggingEnabled() {
return myTabDraggingEnabled && !mySplitter.isDragging();
}
void reallocate(TabInfo source, TabInfo target) {
if (source == target || source == null || target == null) return;
final int targetIndex = myVisibleInfos.indexOf(target);
myVisibleInfos.remove(source);
myVisibleInfos.add(targetIndex, source);
invalidate();
relayout(true, true);
}
public boolean isHorizontalTabs() {
return getTabsPosition() == JBTabsPosition.top || getTabsPosition() == JBTabsPosition.bottom;
}
@Override
public void putInfo(@NotNull Map<String, String> info) {
final TabInfo selected = getSelectedInfo();
if (selected != null) {
selected.putInfo(info);
}
}
@Override
public void resetDropOver(TabInfo tabInfo) {
if (myDropInfo != null) {
TabInfo dropInfo = myDropInfo;
myDropInfo = null;
myShowDropLocation = true;
myForcedRelayout = true;
setDropInfoIndex(-1);
if (!isDisposed()) {
removeTab(dropInfo, null, false, true);
}
}
}
@Override
public Image startDropOver(TabInfo tabInfo, RelativePoint point) {
myDropInfo = tabInfo;
int index = myLayout.getDropIndexFor(point.getPoint(this));
setDropInfoIndex(index);
addTab(myDropInfo, index, true, true);
TabLabel label = myInfo2Label.get(myDropInfo);
Dimension size = label.getPreferredSize();
label.setBounds(0, 0, size.width, size.height);
BufferedImage img = UIUtil.createImage(this, size.width, size.height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = img.createGraphics();
label.paintOffscreen(g);
g.dispose();
relayout(true, false);
return img;
}
@Override
public void processDropOver(TabInfo over, RelativePoint point) {
int index = myLayout.getDropIndexFor(point.getPoint(this));
if (index != getDropInfoIndex()) {
setDropInfoIndex(index);
relayout(true, false);
}
}
@Override
public int getDropInfoIndex() {
return myDropInfoIndex;
}
@Override
public boolean isEmptyVisible() {
return myVisibleInfos.isEmpty();
}
@Deprecated
public int getInterTabSpaceLength() {
return getTabHGap();
}
public int getTabHGap() {
return -myBorder.getThickness();
}
@Override
public String toString() {
return "JBTabs visible=" + myVisibleInfos + " selected=" + mySelectedInfo;
}
@Override
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJBTabsImpl();
}
return accessibleContext;
}
/**
* Custom implementation of Accessible interface. Given JBTabsImpl is similar
* to the built-it JTabbedPane, we expose similar behavior. The one tricky part
* is that JBTabsImpl can only expose the content of the selected tab, as the
* content of tabs is created/deleted on demand when a tab is selected.
*/
protected class AccessibleJBTabsImpl extends AccessibleJComponent implements AccessibleSelection {
AccessibleJBTabsImpl() {
getAccessibleComponent();
addListener(new TabsListener() {
@Override
public void selectionChanged(TabInfo oldSelection, TabInfo newSelection) {
firePropertyChange(AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY, null, null);
}
});
}
@Override
public String getAccessibleName() {
String name = accessibleName;
if (name == null) {
name = (String)getClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY);
}
if (name == null) {
// Similar to JTabbedPane, we return the name of our selected tab
// as our own name.
TabLabel selectedLabel = getSelectedLabel();
if (selectedLabel != null) {
if (selectedLabel.getAccessibleContext() != null) {
name = selectedLabel.getAccessibleContext().getAccessibleName();
}
}
}
if (name == null) {
name = super.getAccessibleName();
}
return name;
}
@Override
public AccessibleRole getAccessibleRole() {
return AccessibleRole.PAGE_TAB_LIST;
}
@Override
public Accessible getAccessibleChild(int i) {
Accessible accessibleChild = super.getAccessibleChild(i);
// Note: Unlike a JTabbedPane, JBTabsImpl has many more child types than just pages.
// So we wrap TabLabel instances with their corresponding AccessibleTabPage, while
// leaving other types of children untouched.
if (accessibleChild instanceof TabLabel) {
TabLabel label = (TabLabel)accessibleChild;
return myInfo2Page.get(label.getInfo());
}
return accessibleChild;
}
@Override
public AccessibleSelection getAccessibleSelection() {
return this;
}
@Override
public int getAccessibleSelectionCount() {
return getSelectedInfo() == null ? 0 : 1;
}
@Override
public Accessible getAccessibleSelection(int i) {
if (getSelectedInfo() == null)
return null;
return myInfo2Page.get(getSelectedInfo());
}
@Override
public boolean isAccessibleChildSelected(int i) {
return i == getIndexOf(getSelectedInfo());
}
@Override
public void addAccessibleSelection(int i) {
TabInfo info = getTabAt(i);
select(info, false);
}
@Override
public void removeAccessibleSelection(int i) {
// can't do
}
@Override
public void clearAccessibleSelection() {
// can't do
}
@Override
public void selectAllAccessibleSelection() {
// can't do
}
}
/**
* AccessibleContext implementation for a single tab page.
*
* A tab page has a label as the display zone, name, description, etc.
* A tab page exposes a child component only if it corresponds to the
* selected tab in the tab pane. Inactive tabs don't have a child
* component to expose, as components are created/deleted on demand.
* A tab page exposes one action: select and activate the panel.
*/
private class AccessibleTabPage extends AccessibleContext
implements Accessible, AccessibleComponent, AccessibleAction {
@NotNull
private final JBTabsImpl myParent;
@NotNull
private final TabInfo myTabInfo;
private final Component myComponent;
AccessibleTabPage(@NotNull TabInfo tabInfo) {
myParent = JBTabsImpl.this;
myTabInfo = tabInfo;
myComponent = tabInfo.getComponent();
setAccessibleParent(myParent);
initAccessibleContext();
}
@NotNull
private TabInfo getTabInfo() {
return myTabInfo;
}
private int getTabIndex() {
return getIndexOf(myTabInfo);
}
private TabLabel getTabLabel() {
return myInfo2Label.get(getTabInfo());
}
/*
* initializes the AccessibleContext for the page
*/
void initAccessibleContext() {
// Note: null checks because we do not want to load Accessibility classes unnecessarily.
if (accessibleContext != null && myComponent instanceof Accessible) {
AccessibleContext ac = myComponent.getAccessibleContext();
if (ac != null) {
ac.setAccessibleParent(this);
}
}
}
// Accessibility support
@Override
public AccessibleContext getAccessibleContext() {
return this;
}
// AccessibleContext methods
@Override
public String getAccessibleName() {
String name = accessibleName;
if (name == null) {
name = (String)getClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY);
}
if (name == null) {
TabLabel label = getTabLabel();
if (label != null && label.getAccessibleContext() != null) {
name = label.getAccessibleContext().getAccessibleName();
}
}
if (name == null) {
name = super.getAccessibleName();
}
return name;
}
@Override
public String getAccessibleDescription() {
String description = accessibleDescription;
if (description == null) {
description = (String)getClientProperty(AccessibleContext.ACCESSIBLE_DESCRIPTION_PROPERTY);
}
if (description == null) {
TabLabel label = getTabLabel();
if (label != null && label.getAccessibleContext() != null) {
description = label.getAccessibleContext().getAccessibleDescription();
}
}
if (description == null) {
description = super.getAccessibleDescription();
}
return description;
}
@Override
public AccessibleRole getAccessibleRole() {
return AccessibleRole.PAGE_TAB;
}
@Override
public AccessibleStateSet getAccessibleStateSet() {
AccessibleStateSet states = myParent.getAccessibleContext().getAccessibleStateSet();
states.add(AccessibleState.SELECTABLE);
TabInfo info = myParent.getSelectedInfo();
if (info == getTabInfo()) {
states.add(AccessibleState.SELECTED);
}
return states;
}
@Override
public int getAccessibleIndexInParent() {
return getTabIndex();
}
@Override
public int getAccessibleChildrenCount() {
// Expose the tab content only if it is active, as the content for
// inactive tab does is usually not ready (i.e. may never have been
// activated).
return getSelectedInfo() == getTabInfo() && myComponent instanceof Accessible ? 1 : 0;
}
@Override
public Accessible getAccessibleChild(int i) {
return getSelectedInfo() == getTabInfo() && myComponent instanceof Accessible ? (Accessible)myComponent : null;
}
@Override
public Locale getLocale() {
return JBTabsImpl.this.getLocale();
}
@Override
public AccessibleComponent getAccessibleComponent() {
return this;
}
@Override
public AccessibleAction getAccessibleAction() {
return this;
}
// AccessibleComponent methods
@Override
public Color getBackground() {
return JBTabsImpl.this.getBackground();
}
@Override
public void setBackground(Color c) {
JBTabsImpl.this.setBackground(c);
}
@Override
public Color getForeground() {
return JBTabsImpl.this.getForeground();
}
@Override
public void setForeground(Color c) {
JBTabsImpl.this.setForeground(c);
}
@Override
public Cursor getCursor() {
return JBTabsImpl.this.getCursor();
}
@Override
public void setCursor(Cursor c) {
JBTabsImpl.this.setCursor(c);
}
@Override
public Font getFont() {
return JBTabsImpl.this.getFont();
}
@Override
public void setFont(Font f) {
JBTabsImpl.this.setFont(f);
}
@Override
public FontMetrics getFontMetrics(Font f) {
return JBTabsImpl.this.getFontMetrics(f);
}
@Override
public boolean isEnabled() {
return getTabInfo().isEnabled();
}
@Override
public void setEnabled(boolean b) {
getTabInfo().setEnabled(b);
}
@Override
public boolean isVisible() {
return !getTabInfo().isHidden();
}
@Override
public void setVisible(boolean b) {
getTabInfo().setHidden(!b);
}
@Override
public boolean isShowing() {
return JBTabsImpl.this.isShowing();
}
@Override
public boolean contains(Point p) {
Rectangle r = getBounds();
return r.contains(p);
}
@Override
public Point getLocationOnScreen() {
Point parentLocation = JBTabsImpl.this.getLocationOnScreen();
Point componentLocation = getLocation();
componentLocation.translate(parentLocation.x, parentLocation.y);
return componentLocation;
}
@Override
public Point getLocation() {
Rectangle r = getBounds();
return new Point(r.x, r.y);
}
@Override
public void setLocation(Point p) {
// do nothing
}
/**
* Returns the bounds of tab. The bounds are with respect to the JBTabsImpl coordinate space.
*/
@Override
public Rectangle getBounds() {
return getTabLabel().getBounds();
}
@Override
public void setBounds(Rectangle r) {
// do nothing
}
@Override
public Dimension getSize() {
Rectangle r = getBounds();
return new Dimension(r.width, r.height);
}
@Override
public void setSize(Dimension d) {
// do nothing
}
@Override
public Accessible getAccessibleAt(Point p) {
return myComponent instanceof Accessible ? (Accessible)myComponent : null;
}
@Override
public boolean isFocusTraversable() {
return false;
}
@Override
public void requestFocus() {
// do nothing
}
@Override
public void addFocusListener(FocusListener l) {
// do nothing
}
@Override
public void removeFocusListener(FocusListener l) {
// do nothing
}
@Override
public AccessibleIcon [] getAccessibleIcon() {
AccessibleIcon accessibleIcon = null;
if (getTabInfo().getIcon() instanceof ImageIcon) {
AccessibleContext ac =
((ImageIcon)getTabInfo().getIcon()).getAccessibleContext();
accessibleIcon = (AccessibleIcon)ac;
}
if (accessibleIcon != null) {
AccessibleIcon [] returnIcons = new AccessibleIcon[1];
returnIcons[0] = accessibleIcon;
return returnIcons;
} else {
return null;
}
}
// AccessibleAction methods
@Override
public int getAccessibleActionCount() {
return 1;
}
@Override
public String getAccessibleActionDescription(int i) {
if (i != 0)
return null;
return "Activate";
}
@Override
public boolean doAccessibleAction(int i) {
if (i != 0)
return false;
select(getTabInfo(), true);
return true;
}
}
/**
* @deprecated unused. You should move the painting logic to an implementation of {@link JBTabPainter} interface }
*/
@Deprecated
public int getActiveTabUnderlineHeight() {
return 0;
}
/**
* @deprecated unused in current realization.
*/
@Deprecated
protected static class ShapeInfo {
public ShapeInfo() {
}
public ShapeTransform path;
public ShapeTransform fillPath;
public ShapeTransform labelPath;
public int labelBottomY;
public int labelTopY;
public int labelLeftX;
public int labelRightX;
public Insets insets;
public Color from;
public Color to;
}
}
|
package com.intellij.vcs.log.ui;
import com.google.common.util.concurrent.SettableFuture;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.util.NamedRunnable;
import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier;
import com.intellij.ui.navigation.History;
import com.intellij.util.EventDispatcher;
import com.intellij.util.PairFunction;
import com.intellij.vcs.log.VcsLogFilterCollection;
import com.intellij.vcs.log.data.VcsLogData;
import com.intellij.vcs.log.graph.PermanentGraph;
import com.intellij.vcs.log.graph.actions.GraphAction;
import com.intellij.vcs.log.graph.actions.GraphAnswer;
import com.intellij.vcs.log.impl.*;
import com.intellij.vcs.log.impl.MainVcsLogUiProperties.VcsLogHighlighterProperty;
import com.intellij.vcs.log.ui.filter.VcsLogFilterUiEx;
import com.intellij.vcs.log.ui.frame.MainFrame;
import com.intellij.vcs.log.ui.highlighters.VcsLogHighlighterFactory;
import com.intellij.vcs.log.ui.table.GraphTableModel;
import com.intellij.vcs.log.ui.table.VcsLogGraphTable;
import com.intellij.vcs.log.util.VcsLogUiUtil;
import com.intellij.vcs.log.visible.VisiblePackRefresher;
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.List;
public class VcsLogUiImpl extends AbstractVcsLogUi {
private static final String HELP_ID = "reference.changesToolWindow.log";
@NotNull private final MainVcsLogUiProperties myUiProperties;
@NotNull private final MainFrame myMainFrame;
@NotNull private final MyVcsLogUiPropertiesListener myPropertiesListener;
@NotNull private final History myHistory;
@NotNull private final EventDispatcher<VcsLogFilterListener> myFilterListenerDispatcher =
EventDispatcher.create(VcsLogFilterListener.class);
public VcsLogUiImpl(@NotNull String id,
@NotNull VcsLogData logData,
@NotNull VcsLogColorManager manager,
@NotNull MainVcsLogUiProperties uiProperties,
@NotNull VisiblePackRefresher refresher,
@Nullable VcsLogFilterCollection filters) {
super(id, logData, manager, refresher);
myUiProperties = uiProperties;
myMainFrame = new MainFrame(logData, this, uiProperties, filters);
for (VcsLogHighlighterFactory factory : LOG_HIGHLIGHTER_FACTORY_EP.getExtensions(myProject)) {
getTable().addHighlighter(factory.createHighlighter(logData, this));
}
myPropertiesListener = new MyVcsLogUiPropertiesListener();
myUiProperties.addChangeListener(myPropertiesListener);
myHistory = VcsLogUiUtil.installNavigationHistory(this);
}
@Override
protected void onVisiblePackUpdated(boolean permGraphChanged) {
myMainFrame.updateDataPack(myVisiblePack, permGraphChanged);
myPropertiesListener.onShowLongEdgesChanged();
}
@NotNull
public MainFrame getMainFrame() {
return myMainFrame;
}
private void performLongAction(@NotNull final GraphAction graphAction, @NotNull final String title) {
ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> {
final GraphAnswer<Integer> answer = myVisiblePack.getVisibleGraph().getActionController().performAction(graphAction);
final Runnable updater = answer.getGraphUpdater();
ApplicationManager.getApplication().invokeLater(() -> {
assert updater != null : "Action:" +
title +
"\nController: " +
myVisiblePack.getVisibleGraph().getActionController() +
"\nAnswer:" +
answer;
updater.run();
getTable().handleAnswer(answer);
});
}, title, false, null, getMainFrame().getMainComponent());
}
public void expandAll() {
performLongAction(new GraphAction.GraphActionImpl(null, GraphAction.Type.BUTTON_EXPAND),
"Expanding " +
(myUiProperties.get(MainVcsLogUiProperties.BEK_SORT_TYPE) == PermanentGraph.SortType.LinearBek
? "merges..."
: "linear branches..."));
}
public void collapseAll() {
performLongAction(new GraphAction.GraphActionImpl(null, GraphAction.Type.BUTTON_COLLAPSE),
"Collapsing " +
(myUiProperties.get(MainVcsLogUiProperties.BEK_SORT_TYPE) == PermanentGraph.SortType.LinearBek
? "merges..."
: "linear branches..."));
}
@Override
protected <T> void handleCommitNotFound(@NotNull T commitId,
boolean commitExists,
@NotNull PairFunction<GraphTableModel, T, Integer> rowGetter) {
if (getFilterUi().getFilters().isEmpty() || !commitExists) {
super.handleCommitNotFound(commitId, commitExists, rowGetter);
return;
}
List<NamedRunnable> runnables = new ArrayList<>();
runnables.add(new NamedRunnable("View and Reset Filters") {
@Override
public void run() {
getFilterUi().setFilter(null);
invokeOnChange(() -> jumpTo(commitId, rowGetter, SettableFuture.create()),
pack -> pack.getFilters().isEmpty());
}
});
VcsProjectLog projectLog = VcsProjectLog.getInstance(myProject);
VcsLogManager logManager = projectLog.getLogManager();
if (logManager != null && logManager.getDataManager() == myLogData) {
runnables.add(new NamedRunnable("View in New Tab") {
@Override
public void run() {
VcsLogUiImpl ui = projectLog.getTabsManager().openAnotherLogTab(logManager, VcsLogFilterObject.collection());
ui.invokeOnChange(() -> ui.jumpTo(commitId, rowGetter, SettableFuture.create()),
pack -> pack.getFilters().isEmpty());
}
});
}
VcsBalloonProblemNotifier.showOverChangesView(myProject, getCommitNotFoundMessage(commitId, true), MessageType.WARNING,
runnables.toArray(new NamedRunnable[0]));
}
@Override
public boolean isHighlighterEnabled(@NotNull String id) {
VcsLogHighlighterProperty property = VcsLogHighlighterProperty.get(id);
return myUiProperties.exists(property) && myUiProperties.get(property);
}
public void applyFiltersAndUpdateUi(@NotNull VcsLogFilterCollection filters) {
myRefresher.onFiltersChange(filters);
myFilterListenerDispatcher.getMulticaster().onFiltersChanged();
JComponent toolbar = myMainFrame.getToolbar();
toolbar.revalidate();
toolbar.repaint();
}
public void addFilterListener(@NotNull VcsLogFilterListener listener) {
myFilterListenerDispatcher.addListener(listener);
}
@NotNull
@Override
public VcsLogGraphTable getTable() {
return myMainFrame.getGraphTable();
}
@NotNull
@Override
public Component getMainComponent() {
return myMainFrame.getMainComponent();
}
@NotNull
@Override
public VcsLogFilterUiEx getFilterUi() {
return myMainFrame.getFilterUi();
}
@Override
@NotNull
public MainVcsLogUiProperties getProperties() {
return myUiProperties;
}
@Nullable
@Override
public String getHelpId() {
return HELP_ID;
}
@Nullable
@Override
public History getNavigationHistory() {
return myHistory;
}
@Override
public void dispose() {
myUiProperties.removeChangeListener(myPropertiesListener);
super.dispose();
}
private class MyVcsLogUiPropertiesListener implements VcsLogUiProperties.PropertiesChangeListener {
@Override
public <T> void onPropertyChanged(@NotNull VcsLogUiProperties.VcsLogUiProperty<T> property) {
if (CommonUiProperties.SHOW_DETAILS.equals(property)) {
myMainFrame.showDetails(myUiProperties.get(CommonUiProperties.SHOW_DETAILS));
}
else if (CommonUiProperties.SHOW_DIFF_PREVIEW.equals(property)) {
myMainFrame.showDiffPreview(myUiProperties.get(CommonUiProperties.SHOW_DIFF_PREVIEW));
}
else if (MainVcsLogUiProperties.SHOW_LONG_EDGES.equals(property)) {
onShowLongEdgesChanged();
}
else if (CommonUiProperties.SHOW_ROOT_NAMES.equals(property)) {
myMainFrame.getGraphTable().rootColumnUpdated();
}
else if (MainVcsLogUiProperties.COMPACT_REFERENCES_VIEW.equals(property)) {
myMainFrame.getGraphTable().setCompactReferencesView(myUiProperties.get(MainVcsLogUiProperties.COMPACT_REFERENCES_VIEW));
}
else if (MainVcsLogUiProperties.SHOW_TAG_NAMES.equals(property)) {
myMainFrame.getGraphTable().setShowTagNames(myUiProperties.get(MainVcsLogUiProperties.SHOW_TAG_NAMES));
}
else if (MainVcsLogUiProperties.LABELS_LEFT_ALIGNED.equals(property)) {
myMainFrame.getGraphTable().setLabelsLeftAligned(myUiProperties.get(MainVcsLogUiProperties.LABELS_LEFT_ALIGNED));
}
else if (MainVcsLogUiProperties.BEK_SORT_TYPE.equals(property)) {
myRefresher.onSortTypeChange(myUiProperties.get(MainVcsLogUiProperties.BEK_SORT_TYPE));
}
else if (CommonUiProperties.COLUMN_ORDER.equals(property)) {
myMainFrame.getGraphTable().onColumnOrderSettingChanged();
}
else if (property instanceof VcsLogHighlighterProperty) {
myMainFrame.getGraphTable().repaint();
}
else if (property instanceof CommonUiProperties.TableColumnProperty) {
myMainFrame.getGraphTable().forceReLayout(((CommonUiProperties.TableColumnProperty)property).getColumn());
}
}
private void onShowLongEdgesChanged() {
myVisiblePack.getVisibleGraph().getActionController()
.setLongEdgesHidden(!myUiProperties.get(MainVcsLogUiProperties.SHOW_LONG_EDGES));
}
}
public interface VcsLogFilterListener extends EventListener {
void onFiltersChanged();
}
}
|
import utils.Pair;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import java.awt.*;
import java.util.List;
public class CashBox extends JPanel {
public Integer sum;
private List<Coins> coins;
private List<Banknotes> banknotes;
private JButton bill_acceptor;
private JButton coin_acceptor;
private List<Coins> change;
private JButton change_window;
private JLabel sum_display;
public CashBox(List<Coins> coins, List<Banknotes> banknotes) {
super(new GridLayout(4, 1, 0, 0));
this.sum = 0;
this.coins = coins;
this.banknotes = banknotes;
setBorder(new TitledBorder(""));
setBackground(Color.lightGray);
sum_display = new JLabel(sum.toString());
sum_display.setBorder(new TitledBorder("Sum entered"));
add(sum_display);
initCoinAcceptor();
add(coin_acceptor);
initBillAcceptor();
add(bill_acceptor);
initChangeWindow();
add(change_window);
}
private void initCoinAcceptor() {
coin_acceptor = new JButton("Coin Acceptor", new ImageIcon(Panel.class.getResource("images/coin-acceptor.png")));
coin_acceptor.setHorizontalTextPosition(JLabel.CENTER);
coin_acceptor.setVerticalTextPosition(JLabel.BOTTOM);
coin_acceptor.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Object[] options = {"5 rub.", "10 rub."};
int response = JOptionPane.showOptionDialog(new JFrame(),
"Choose denomination",
"",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[1]);
int denomination = 0;
switch (response) {
case JOptionPane.YES_OPTION: denomination = 5;
break;
default: denomination = 10;
break;
}
insert(true, Arrays.asList(new Coins(1, 1, denomination)), new ArrayList<>());
}
});
}
private void initBillAcceptor() {
bill_acceptor = new JButton("Bill Acceptor", new ImageIcon(Panel.class.getResource("images/bill-acceptor.png")));
bill_acceptor.setHorizontalTextPosition(JLabel.CENTER);
bill_acceptor.setVerticalTextPosition(JLabel.BOTTOM);
bill_acceptor.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Object[] options = {"10 rub.", "50 rub.", "100 rub."};
int response = JOptionPane.showOptionDialog(new JFrame(),
"Choose denomination",
"",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[2]);
int denomination = 0;
switch (response) {
case JOptionPane.YES_OPTION: denomination = 10;
break;
case JOptionPane.NO_OPTION: denomination = 50;
break;
default: denomination = 100;
break;
}
insert(true, new ArrayList<>(), Arrays.asList(new Banknotes(1, 1, denomination)));
}
});
}
private void initChangeWindow() {
change_window = new JButton("Your Change", new ImageIcon(Panel.class.getResource("images/change.png")));
change_window.setHorizontalTextPosition(JLabel.CENTER);
change_window.setVerticalTextPosition(JLabel.BOTTOM);
}
public void insert(Boolean mode, List<Coins> coins_new, List<Banknotes> banknotes_new) {
// TODO: show new sum in sum_display
// TODO: add logic with dropping extra money (that don't fit in anymore) into Change window
int cur_sum = sum;
for (Coins coins_add : coins_new) {
addCoins(coins_add);
if (mode) {
sum += coins_add.denomination * coins_add.number;
sum_display.setText(Integer.toString(sum));
}
}
for (Banknotes banknotes_add : banknotes_new) {
addBanknotes(banknotes_add);
if (mode) {
sum += banknotes_add.denomination * banknotes_add.number;
sum_display.setText(Integer.toString(sum));
}
}
}
private void addBanknotes(Banknotes banknotes_add) {
for (Banknotes banknotes : this.banknotes) {
if (banknotes.denomination.equals(banknotes_add.denomination)) {
if (banknotes.max_size < banknotes.number + banknotes_add.number) {
banknotes.changeNumber(banknotes.max_size);
//show that you get (banknotes.number -banknotes_add.number) back
}
else {
banknotes.changeNumber(banknotes.number + banknotes_add.number);
}
break;
}
}
}
private void addCoins(Coins coins_add) {
for (Coins coins : this.coins) {
if (coins.denomination.equals(coins_add.denomination)) {
if (coins.max_size < coins.number + coins_add.number) {
coins.changeNumber(coins.max_size);
//show that you get (coins.number -coins_add.number) back
}
else {
coins.changeNumber(coins.number + coins_add.number);
}
break;
}
}
}
public void take(Boolean mode, List<Coins> coins, List<Banknotes> banknotes) {
for (Coins coin : coins) {
subCoins(mode, coin);
}
for (Banknotes banknote : banknotes) {
subBanknontes(mode, banknote);
}
}
private void subCoins(Boolean mode, Coins coins_sub) {
for (Coins coins : this.coins) {
if (coins.denomination.equals(coins_sub.denomination)) {
coins.changeNumber(Math.max(0, coins.number - coins_sub.number));
if (mode) {
sum -= coins.denomination * Math.max(0, coins.number - coins_sub.number);
}
break;
}
}
}
private void subBanknontes(Boolean mode, Banknotes banknotes_sub) {
for (Banknotes banknotes : this.banknotes) {
if (banknotes.denomination.equals(banknotes_sub.denomination)) {
banknotes.changeNumber(Math.max(0, banknotes.number - banknotes_sub.number));
if (mode) {
sum -= banknotes.denomination * Math.max(0, banknotes.number - banknotes_sub.number);
}
break;
}
}
}
public Pair<List<Coins>, List<Banknotes>> intToMoney() {
ArrayList<Coins> res_coins = new ArrayList<Coins>();
ArrayList<Banknotes> res_banknotes = new ArrayList<Banknotes>();
Collections.sort(this.coins, Money.getCompByName());
Collections.sort(this.banknotes, Money.getCompByName());
for (Banknotes banknote : this.banknotes) {
Integer count = Math.min(banknote.number, sum/banknote.denomination);
res_banknotes.add(new Banknotes(count, banknote.max_size, banknote.denomination));
}
for (Coins coin : this.coins) {
Integer count = Math.min(coin.number, sum/coin.denomination);
res_coins.add(new Coins(count, coin.max_size, coin.denomination));
}
return new Pair<>(coins, banknotes);
}
}
|
package attackontinytim.barquest;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import java.util.Calendar;
import java.util.List;
import junit.framework.Test;
import attackontinytim.barquest.Database.DBHandler;
import attackontinytim.barquest.Database.HeroRepo;
import attackontinytim.barquest.Database.TimerRepo;
import attackontinytim.barquest.Database.InsertDataValues;
import attackontinytim.barquest.Database.Testing;
import attackontinytim.barquest.Database.DatabaseManager;
public class MainActivity extends AppCompatActivity {
// global Hero
public Hero hero;
// Return
static public int MAIN_RETURN_CODE = 1;
// Buttons
private static Button battle;
private static Button scan;
private static Button character;
private static Button inventory;
private static Button shop;
private static Button levelUp;
private static Button quest;
private static Button consumables;
private static Button reset;
// DB Handler object for all database calls
private static DBHandler dbHandler;
// This is called when the activity is created
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
onClickButtonListener();
checkPermissions();
// Loads database handler
dbHandler = new DBHandler(this.getApplicationContext());
DatabaseManager.initializeInstance(dbHandler);
// Inserts value to database if database is empty
InsertDataValues.createDatabaseValues();
if (HeroRepo.getAllHeros().size() == 0){
InsertDataValues.initializeHeroValues();
}
else {
InsertDataValues.initializeHeroValues();
hero = HeroRepo.getHeroByName("HERO");
List<Long> timerList = TimerRepo.getAllTimers("HERO");
Long[] myArray = new Long[10];
myArray = timerList.toArray(myArray);
Timer[] heroTimers = new Timer[10];
for (int i = 0; i < 10; i++) {
heroTimers[i] = new Timer();
heroTimers[i].setTime(myArray[i]);
}
hero.setScanTimers(heroTimers);
}
}
private void checkPermissions() {
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
if (ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
}
if (ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA}, 0);
}
}
// THIS is disgusting
public void onClickButtonListener(){
battle = (Button)findViewById(R.id.battleButton);
scan = (Button)findViewById(R.id.scannerButton);
character = (Button)findViewById(R.id.characterButton);
inventory = (Button)findViewById(R.id.inventoryButton);
shop = (Button)findViewById(R.id.shopButton);
levelUp = (Button)findViewById(R.id.levelUpButton);
quest = (Button)findViewById(R.id.questButton);
consumables = (Button)findViewById(R.id.consumableButton);
reset = (Button)findViewById(R.id.CharReset);
battle.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent("attackontinytim.barquest.BattleActivity");
Bundle bundle = bundler.generateBundle(hero);
intent.putExtras(bundle);
startActivityForResult(intent, MAIN_RETURN_CODE);
}
}
);
scan.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent("attackontinytim.barquest.ScannerActivity");
Bundle bundle = bundler.generateBundle(hero);
intent.putExtras(bundle);
startActivityForResult(intent, MAIN_RETURN_CODE);
}
}
);
levelUp.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent("attackontinytim.barquest.LevelUpActivity");
Bundle bundle = bundler.generateBundle(hero);
intent.putExtras(bundle);
startActivityForResult(intent, MAIN_RETURN_CODE);
}
}
);
character.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent("attackontinytim.barquest.CharacterScreenActivity");
Bundle bundle = bundler.generateBundle(hero);
intent.putExtras(bundle);
startActivityForResult(intent, MAIN_RETURN_CODE);
}
}
);
inventory.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent("attackontinytim.barquest.InventoryActivity");
Bundle bundle = bundler.generateBundle(hero);
intent.putExtras(bundle);
startActivityForResult(intent, MAIN_RETURN_CODE);
}
}
);
shop.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent("attackontinytim.barquest.ShopActivity");
Bundle bundle = bundler.generateBundle(hero);
intent.putExtras(bundle);
startActivityForResult(intent, MAIN_RETURN_CODE);
}
}
);
quest.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent("attackontinytim.barquest.QuestActivity");
Bundle bundle = bundler.generateBundle(hero);
intent.putExtras(bundle);
startActivityForResult(intent, MAIN_RETURN_CODE);
}
}
);
consumables.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent("attackontinytim.barquest.ConsumableActivity");
Bundle bundle = bundler.generateBundle(hero);
intent.putExtras(bundle);
startActivityForResult(intent, MAIN_RETURN_CODE);
}
}
);
reset.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
dbHandler.resetData();
hero = HeroRepo.getHeroByName("HERO");
List<Long> timerList = TimerRepo.getAllTimers("HERO");
Long[] myArray = new Long[10];
myArray = timerList.toArray(myArray);
Timer[] heroTimers = new Timer[10];
for (int i = 0; i < 10; i++) {
heroTimers[i] = new Timer();
heroTimers[i].setTime(myArray[i]);
}
hero.setScanTimers(heroTimers);
}
}
);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
// This reconstructs the hero after a called activity ends
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_CANCELED) {
switch (requestCode) {
default:
Bundle bundle = data.getExtras();
hero = bundler.unbundleHero(bundle);
}
}
}
}
|
package com.honu.tmdb;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.honu.tmdb.rest.ApiError;
import com.honu.tmdb.rest.Movie;
import com.honu.tmdb.rest.MovieResponse;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Fragment displays grid of movie posters using recycler view
*/
public class MoviePosterGridFragment extends Fragment implements MovieDbApi.MovieListener {
static final String TAG = MoviePosterGridFragment.class.getSimpleName();
static final String KEY_MOVIES = "movies";
@Bind(R.id.recycler)
RecyclerView mRecyclerView;
Spinner mSortSpinner;
MovieDbApi mApi;
MovieGridRecyclerAdapter mAdapter;
int mSortMethod = SortOption.POPULARITY;
public MoviePosterGridFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.movie_poster_grid, null);
ButterKnife.bind(this, view);
ArrayList<Movie> movies = new ArrayList<>();
// restore movie list from instance state on orientation change
if (savedInstanceState != null) {
mSortMethod = AppPreferences.getCurrentSortMethod(getActivity());
movies = savedInstanceState.getParcelableArrayList(KEY_MOVIES);
} else {
mSortMethod = AppPreferences.getPreferredSortMethod(getActivity());
}
mAdapter = new MovieGridRecyclerAdapter();
mRecyclerView.setAdapter(mAdapter);
mAdapter.setData(movies);
mRecyclerView.setLayoutManager(new GridLayoutManager(this.getActivity(), 3));
// initialize api
mApi = MovieDbApi.getInstance(getString(R.string.tmdb_api_key));
// request movies
if (mAdapter.getItemCount() == 0) {
if (mSortMethod == SortOption.POPULARITY) {
mApi.requestMostPopularMovies(this);
} else {
mApi.requestHighestRatedMovies(this);
}
}
return view;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(KEY_MOVIES, mAdapter.data);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.movie_poster_grid, menu);
MenuItem menuItem = menu.findItem(R.id.spin_test);
// specify layout for the action
menuItem.setActionView(R.layout.sort_spinner);
View view = menuItem.getActionView();
// set custom adapter on spinner
mSortSpinner = (Spinner) view.findViewById(R.id.spinner_nav);
mSortSpinner.setAdapter(new SortSpinnerAdapter(this, getActivity(), SortOption.getSortOptions()));
mSortSpinner.setSelection(mSortMethod);
mSortSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
AppPreferences.setCurrentSortMethod(getActivity(), position);
handleSortSelection(SortOption.getSortMethod(position));
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "Options menu item selected: " + item.getItemId());
return true;
}
@Override
public void success(MovieResponse response) {
mAdapter.setData(response.getMovies());
}
@Override
public void error(ApiError error) {
Log.d(TAG, error.getReason());
}
public void handleSortSelection(int sortType) {
if (mSortMethod == sortType)
return;
mSortMethod = sortType;
switch (sortType) {
case SortOption.POPULARITY:
mApi.requestMostPopularMovies(this);
return;
case SortOption.RATING:
mApi.requestHighestRatedMovies(this);
return;
default:
// TODO: P2 - add support for Favorites
Toast.makeText(getActivity(), "Sort type not supported", Toast.LENGTH_SHORT).show();
return;
}
}
class MovieGridRecyclerAdapter extends RecyclerView.Adapter<MovieGridRecyclerAdapter.MovieGridItemViewHolder> {
ArrayList<Movie> data = new ArrayList<>();
public void setData(List<Movie> data) {
this.data.clear();
this.data.addAll(data);
this.notifyDataSetChanged();
}
@Override
public MovieGridItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.movie_poster_item, parent, false);
return new MovieGridItemViewHolder(view);
}
@Override
public void onBindViewHolder(MovieGridItemViewHolder holder, int position) {
Movie movie = data.get(position);
holder.movieTitle.setText(movie.getTitle());
int screenWidth = getResources().getDisplayMetrics().widthPixels;
Picasso.with(holder.moviePoster.getContext()).load(movie.getPosterUrl(screenWidth)).into(holder.moviePoster);
}
@Override
public int getItemCount() {
return data.size();
}
class MovieGridItemViewHolder extends RecyclerView.ViewHolder {
@Bind(R.id.movie_title)
TextView movieTitle;
@Bind(R.id.movie_poster)
ImageView moviePoster;
public MovieGridItemViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
@OnClick(R.id.movie_poster)
public void onClick() {
int adapterPosition = this.getAdapterPosition();
Log.d(TAG, "AdapterPosition: " + adapterPosition);
Movie movie = data.get(adapterPosition);
openDetails(movie);
}
private void openDetails(Movie movie) {
Log.d(TAG, "Show movie details: " + movie.getTitle());
Intent intent = new Intent(getActivity(), MovieDetailActivity.class);
intent.putExtra("movie", movie);
getActivity().startActivity(intent);
}
}
}
}
|
package com.hzn.easypickerview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.Scroller;
import java.util.ArrayList;
public class EasyPickerView extends View {
private int textSize;
// Color.BLACK
private int textColor;
// 10dp
private int textPadding;
// 2.0f
private float textMaxScale;
// alpha0.0f~1.0f0.4f
private float textMinAlpha;
private boolean isRecycleMode;
private int maxShowNum;
private TextPaint textPaint;
private Paint.FontMetrics fm;
private Scroller scroller;
private VelocityTracker velocityTracker;
private int minimumVelocity;
private int maximumVelocity;
private int scaledTouchSlop;
private ArrayList<String> dataList = new ArrayList<>();
private int cx;
private int cy;
private float maxTextWidth;
private int textHeight;
private int contentWidth;
private int contentHeight;
private float downY;
private float offsetY;
// flingoffsetY
private float oldOffsetY;
private int curIndex;
private int offsetIndex;
private float bounceDistance;
private boolean isSliding = false;
public EasyPickerView(Context context) {
this(context, null);
}
public EasyPickerView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public EasyPickerView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.EasyPickerView, defStyleAttr, 0);
textSize = a.getDimensionPixelSize(R.styleable.EasyPickerView_epvTextSize, (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));
textColor = a.getColor(R.styleable.EasyPickerView_epvTextColor, Color.BLACK);
textPadding = a.getDimensionPixelSize(R.styleable.EasyPickerView_epvTextPadding, (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 20, getResources().getDisplayMetrics()));
textMaxScale = a.getFloat(R.styleable.EasyPickerView_epvTextMaxScale, 2.0f);
textMinAlpha = a.getFloat(R.styleable.EasyPickerView_epvTextMinAlpha, 0.4f);
isRecycleMode = a.getBoolean(R.styleable.EasyPickerView_epvRecycleMode, true);
maxShowNum = a.getInteger(R.styleable.EasyPickerView_epvMaxShowNum, 3);
a.recycle();
textPaint = new TextPaint();
textPaint.setColor(textColor);
textPaint.setTextSize(textSize);
textPaint.setAntiAlias(true);
fm = textPaint.getFontMetrics();
scroller = new Scroller(context);
minimumVelocity = ViewConfiguration.get(getContext()).getScaledMinimumFlingVelocity();
maximumVelocity = ViewConfiguration.get(getContext()).getScaledMaximumFlingVelocity();
scaledTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int mode = MeasureSpec.getMode(widthMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
contentWidth = (int) (maxTextWidth * textMaxScale + getPaddingLeft() + getPaddingRight());
if (mode != MeasureSpec.EXACTLY) { // wrap_content
width = contentWidth;
}
mode = MeasureSpec.getMode(heightMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
textHeight = (int) (fm.bottom - fm.top);
contentHeight = textHeight * maxShowNum + textPadding * maxShowNum;
if (mode != MeasureSpec.EXACTLY) { // wrap_content
height = contentHeight + getPaddingTop() + getPaddingBottom();
}
cx = width / 2;
cy = height / 2;
setMeasuredDimension(width, height);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
getParent().requestDisallowInterceptTouchEvent(true);
return super.dispatchTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
addVelocityTracker(event);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (!scroller.isFinished()) {
scroller.forceFinished(true);
finishScroll();
}
downY = event.getY();
break;
case MotionEvent.ACTION_MOVE:
offsetY = event.getY() - downY;
if (isSliding || Math.abs(offsetY) > scaledTouchSlop) {
isSliding = true;
reDraw();
}
break;
case MotionEvent.ACTION_UP:
int scrollYVelocity = 2 * getScrollYVelocity() / 3;
if (Math.abs(scrollYVelocity) > minimumVelocity) {
oldOffsetY = offsetY;
scroller.fling(0, 0, 0, scrollYVelocity, 0, 0, -Integer.MAX_VALUE, Integer.MAX_VALUE);
invalidate();
} else {
finishScroll();
}
if (!isSliding) {
if (downY < contentHeight / 3)
moveBy(-1);
else if (downY > 2 * contentHeight / 3)
moveBy(1);
}
isSliding = false;
recycleVelocityTracker();
break;
}
return true;
}
@Override
protected void onDraw(Canvas canvas) {
if (null != dataList && dataList.size() > 0) {
canvas.clipRect(
cx - contentWidth / 2,
cy - contentHeight / 2,
cx + contentWidth / 2,
cy + contentHeight / 2
);
// maxShowNum
int size = dataList.size();
int centerPadding = textHeight + textPadding;
int half = maxShowNum / 2 + 1;
for (int i = -half; i <= half; i++) {
int index = curIndex - offsetIndex + i;
if (isRecycleMode) {
if (index < 0)
index = (index + 1) % dataList.size() + dataList.size() - 1;
else if (index > dataList.size() - 1)
index = index % dataList.size();
}
if (index >= 0 && index < size) {
int tempY = cy + i * centerPadding;
tempY += offsetY % centerPadding;
// ycyscale
float scale = 1.0f - (1.0f * Math.abs(tempY - cy) / centerPadding);
// textMaxScaletempScaletext 1~textMaxScale
float tempScale = scale * (textMaxScale - 1.0f) + 1.0f;
tempScale = tempScale < 1.0f ? 1.0f : tempScale;
// alpha
float textAlpha = textMinAlpha;
if (textMaxScale != 1) {
float tempAlpha = (tempScale - 1) / (textMaxScale - 1);
textAlpha = (1 - textMinAlpha) * tempAlpha + textMinAlpha;
}
textPaint.setTextSize(textSize * tempScale);
textPaint.setAlpha((int) (255 * textAlpha));
Paint.FontMetrics tempFm = textPaint.getFontMetrics();
String text = dataList.get(index);
float textWidth = textPaint.measureText(text);
canvas.drawText(text, cx - textWidth / 2, tempY - (tempFm.ascent + tempFm.descent) / 2, textPaint);
}
}
}
}
@Override
public void computeScroll() {
if (scroller.computeScrollOffset()) {
offsetY = oldOffsetY + scroller.getCurrY();
if (!scroller.isFinished())
reDraw();
else
finishScroll();
}
}
private void addVelocityTracker(MotionEvent event) {
if (velocityTracker == null)
velocityTracker = VelocityTracker.obtain();
velocityTracker.addMovement(event);
}
private void recycleVelocityTracker() {
if (velocityTracker != null) {
velocityTracker.recycle();
velocityTracker = null;
}
}
private int getScrollYVelocity() {
velocityTracker.computeCurrentVelocity(1000, maximumVelocity);
int velocity = (int) velocityTracker.getYVelocity();
return velocity;
}
private void reDraw() {
// curIndex
int i = (int) (offsetY / (textHeight + textPadding));
if (isRecycleMode || (curIndex - i >= 0 && curIndex - i < dataList.size())) {
if (offsetIndex != i) {
offsetIndex = i;
if (null != onScrollChangedListener)
onScrollChangedListener.onScrollChanged(getNowIndex(-offsetIndex));
}
postInvalidate();
} else {
finishScroll();
}
}
private void finishScroll() {
int centerPadding = textHeight + textPadding;
float v = offsetY % centerPadding;
if (v > 0.5f * centerPadding)
++offsetIndex;
else if (v < -0.5f * centerPadding)
--offsetIndex;
// curIndex
curIndex = getNowIndex(-offsetIndex);
bounceDistance = offsetIndex * centerPadding - offsetY;
offsetY += bounceDistance;
if (null != onScrollChangedListener)
onScrollChangedListener.onScrollFinished(curIndex);
reset();
postInvalidate();
}
private int getNowIndex(int offsetIndex) {
int index = curIndex + offsetIndex;
if (isRecycleMode) {
if (index < 0)
index = (index + 1) % dataList.size() + dataList.size() - 1;
else if (index > dataList.size() - 1)
index = index % dataList.size();
} else {
if (index < 0)
index = 0;
else if (index > dataList.size() - 1)
index = dataList.size() - 1;
}
return index;
}
private void reset() {
offsetY = 0;
oldOffsetY = 0;
offsetIndex = 0;
bounceDistance = 0;
}
/**
*
*
* @param dataList
*/
public void setDataList(ArrayList<String> dataList) {
this.dataList.clear();
this.dataList.addAll(dataList);
// maxTextWidth
if (null != dataList && dataList.size() > 0) {
int size = dataList.size();
for (int i = 0; i < size; i++) {
float tempWidth = textPaint.measureText(dataList.get(i));
if (tempWidth > maxTextWidth)
maxTextWidth = tempWidth;
}
curIndex = 0;
}
requestLayout();
invalidate();
}
/**
*
*
* @return
*/
public int getCurIndex() {
return getNowIndex(-offsetIndex);
}
/**
*
*
* @param index
*/
public void moveTo(int index) {
if (index < 0 || index >= dataList.size() || curIndex == index)
return;
if (!scroller.isFinished())
scroller.forceFinished(true);
finishScroll();
int dy = 0;
int centerPadding = textHeight + textPadding;
if (!isRecycleMode) {
dy = (curIndex - index) * centerPadding;
} else {
int offsetIndex = curIndex - index;
int d1 = Math.abs(offsetIndex) * centerPadding;
int d2 = (dataList.size() - Math.abs(offsetIndex)) * centerPadding;
if (offsetIndex > 0) {
if (d1 < d2)
dy = d1; // ascent
else
dy = -d2; // descent
} else {
if (d1 < d2)
dy = -d1; // descent
else
dy = d2; // ascent
}
}
scroller.startScroll(0, 0, 0, dy, 500);
invalidate();
}
/**
*
*
* @param offsetIndex
*/
public void moveBy(int offsetIndex) {
moveTo(getNowIndex(offsetIndex));
}
public interface OnScrollChangedListener {
public void onScrollChanged(int curIndex);
public void onScrollFinished(int curIndex);
}
private OnScrollChangedListener onScrollChangedListener;
public void setOnScrollChangedListener(OnScrollChangedListener onScrollChangedListener) {
this.onScrollChangedListener = onScrollChangedListener;
}
}
|
package controllers;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import models.Service;
import nl.idgis.ogc.client.wms.WMSCapabilitiesParser;
import nl.idgis.ogc.client.wms.WMSCapabilitiesParser.ParseException;
import nl.idgis.ogc.wms.WMSCapabilities;
import play.Logger;
import play.Routes;
import play.Configuration;
import play.libs.F.Promise;
import play.libs.F.PromiseTimeoutException;
import play.libs.ws.WSAuthScheme;
import play.libs.ws.WSClient;
import play.libs.ws.WSRequest;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.capabilitieswarning;
import views.html.emptylayermessage;
import views.html.index;
import views.html.servicelayer;
import views.html.layers;
/**
* The main controller of the application.
*
* @author Sandro
*
*/
public class Application extends Controller {
private @Inject Zookeeper zk; // force Zookeeper initialization
private @Inject WSClient ws;
private @Inject Configuration conf;
private @Inject WebJarAssets webJarAssets;
/**
* Fetches the names and titles of the workspaces and makes a service for each workspace. It retrieves the names
* of all workspaces and then retrieves the titles (if available) of every workspace. Then returns a service with
* the title as the name of the service. If the title isn't available it inserts the name of the workspace as the
* name of the service.
*
* @return The promise of the list of services.
*/
public Promise<List<Service>> getServicesList(String service) {
String environment = conf.getString("viewer.environmenturl");
String username = conf.getString("viewer.username");
String password = conf.getString("viewer.password");
// The protocol is omitted from the service urls to ensure that the
// client is using the same protocol to access the services as is used
// to retrieve this application.
String url = environment.replaceFirst("(.*)
String workspacesSummary = environment + "rest/workspaces.xml";
String version = "1.3.0";
WSRequest workspacesSummaryRequest = ws.url(workspacesSummary).setAuth(username, password, WSAuthScheme.BASIC);
return workspacesSummaryRequest.get().flatMap(responseWorkspacesSummary -> {
Document bodyWorkspacesSummary = responseWorkspacesSummary.asXml();
NodeList names = bodyWorkspacesSummary.getElementsByTagName("name");
List<Promise<Service>> unsortedServicesList = new ArrayList<>();
for(int i = 0; i < names.getLength(); i++) {
String name = names.item(i).getTextContent();
String workspaceSettings = environment + "rest/services/wms/workspaces/" + name + "/settings.xml";
WSRequest workspaceSettingsRequest = ws.url(workspaceSettings).setAuth(username, password, WSAuthScheme.BASIC);
if(!"".equals(service)) {
if(service.equals(name)) {
unsortedServicesList.add(workspaceSettingsRequest.get().map(responseWorkspaceSettings -> {
Document bodyWorkspaceSettings = responseWorkspaceSettings.asXml();
NodeList titles = bodyWorkspaceSettings.getElementsByTagName("title");
return getService(titles, url, name, version);
}));
}
} else {
unsortedServicesList.add(workspaceSettingsRequest.get().map(responseWorkspaceSettings -> {
Document bodyWorkspaceSettings = responseWorkspaceSettings.asXml();
NodeList titles = bodyWorkspaceSettings.getElementsByTagName("title");
return getService(titles, url, name, version);
}));
}
}
return Promise.sequence(unsortedServicesList).map(servicesList -> {
Collections.sort(servicesList, (Service s1, Service s2) -> s1.getServiceName().compareToIgnoreCase(s2.getServiceName()));
return servicesList;
});
});
}
/**
*
* @param titles list of titles of service
* @param url url of environment services
* @param name name of service
* @param version version of WMS
* @return
*/
public Service getService(NodeList titles, String url, String name, String version) {
for(int j = 0; j < titles.getLength(); j++) {
/* Parent has to be 'wms' to pick the right 'title' node. */
if(titles.item(j).getParentNode().getNodeName().equals("wms")) {
return new Service(name, titles.item(0).getTextContent(), url + name + "/wms?", version);
}
}
return new Service(name, name, url + name + "/wms?", version);
}
/**
* Fetches content from an url as an inputstream.
*
* @param url the url to fetch
* @return The inputstream.
*/
public Promise<InputStream> getInputStream(String url) {
// sets up request and parameters
WSRequest request = ws.url(url).setFollowRedirects(true).setRequestTimeout(10000);
Map<String, String[]> colStr = request().queryString();
for (Map.Entry<String, String[]> entry: colStr.entrySet()) {
for(String entryValue: entry.getValue()) {
request = request.setQueryParameter(entry.getKey(), entryValue);
}
}
// returns response as inputstream
return request.get().map(response -> {
return response.getBodyAsStream();
});
}
/**
* Parses the WMS capabilities of a service.
*
* @param service the service to parse
* @return The promise of WMSCapabilities.
*/
public Promise<WMSCapabilities> getWMSCapabilities(Service service) {
// create request url
String environment = conf.getString("viewer.environmenturl");
String protocol = environment.substring(0, environment.indexOf(":
String request = protocol + service.getEndpoint() + "version=" + service.getVersion() + "&service=wms&request=GetCapabilities";
// gets the inputstream
Promise<InputStream> capabilities = getInputStream(request);
// parses the capabilities
return capabilities.map(capabilitiesBody -> {
try {
return WMSCapabilitiesParser.parseCapabilities(capabilitiesBody);
} catch(ParseException e) {
Logger.error("An exception occured during parsing of the capabilities document from service " + service.getServiceId() + ": ", e);
throw e;
} finally {
try {
capabilitiesBody.close();
} catch(IOException io) {
Logger.error("An exception occured during closing of the capabilities stream from service " + service.getServiceId() + ": ", io);
}
}
});
}
/**
* Renders the index page.
*
* @return the promise of the result.
*/
public Promise<Result> index(String service) {
return getServicesList(service).map(servicesList -> ok(index.render(webJarAssets, servicesList)));
}
/**
* Renders the view for displaying a specific layer
*
* @param service the service of the WMS
* @param layer the layer to display
* @return the result of the html
*/
public Promise<Result> renderLayer(String service, String layer) {
String url = conf.getString("viewer.environmenturl").replaceFirst("(.*)
Service s = new Service(service, service, url + service + "/wms?", "1.3.0");
return getWMSCapabilities(s).map(capabilities -> {
Collection<WMSCapabilities.Layer> collectionLayers = capabilities.layers();
List<WMSCapabilities.Layer> layerList = new ArrayList<>();
for(WMSCapabilities.Layer wmsLayer : collectionLayers) {
layerList.addAll(wmsLayer.layers());
}
Iterator<WMSCapabilities.Layer> i = layerList.iterator();
while(i.hasNext()) {
WMSCapabilities.Layer wmsLayer = i.next();
if(!layer.equals(wmsLayer.name())) {
i.remove();
}
}
if(layerList.size() < 1) {
return notFound();
}
return ok(servicelayer.render(webJarAssets, service, layer));
});
}
/**
* Fetches the immediate layers of a service who have a CRS of EPSG:28992.
*
* @param serviceId the service id from the service whose immediate layers to fetch
* @return The promise of the result of the response.
*/
public Promise<Result> allLayers(String serviceId) {
return getServicesList("").flatMap(servicesList -> {
for(Service service : servicesList) {
if(serviceId.equals(service.getServiceId())) {
return getWMSCapabilities(service).map(capabilities -> {
// gets the rootlayer
Collection<WMSCapabilities.Layer> collectionLayers = capabilities.layers();
// loops through layers in rootlayer and adds them to a list
List<WMSCapabilities.Layer> layerList = new ArrayList<>();
for(WMSCapabilities.Layer layer : collectionLayers) {
layerList.addAll(layer.layers());
}
// checks if each layer contains the EPSG:28992 CRS
layerList = crsCheck(layerList);
// sends response
if(layerList.isEmpty()) {
return getEmptyLayerMessage("Geen lagen");
} else {
return (Result)ok(layers.render(layerList, service));
}
});
}
}
return Promise.pure(notFound());
}).recover(this::getErrorWarning);
}
/**
* Fetches the immediate layers of a layer who have a CRS of EPSG:28992.
*
* @param serviceId the service id from the service to select
* @param layerId the layer id from the layer whose immediate layers to fetch
* @return The promise of the result of the response.
*/
public Promise<Result> layers(String serviceId, String layerId) {
return getServicesList("").flatMap(servicesList -> {
for(Service service : servicesList) {
if(serviceId.equals(service.getServiceId())) {
return getWMSCapabilities(service).map(capabilities -> {
// gets a specific layer
WMSCapabilities.Layer layer = capabilities.layer(layerId);
// adds all layers of the layer to a list
List<WMSCapabilities.Layer> layerList = new ArrayList<>();
layerList = layer.layers();
// checks if each layer contains the EPSG:28992 CRS
layerList = crsCheck(layerList);
// sends response
if(layerList.isEmpty()) {
return getEmptyLayerMessage("Geen lagen");
} else {
return (Result)ok(layers.render(layerList, service));
}
});
}
}
return Promise.pure(notFound());
}).recover(this::getErrorWarning);
}
/**
* Handles parse- and promisetimeoutexceptions. If another exception is thrown throws it again.
*
* @param t an exception
* @return The result.
* @throws Throwable
*/
private Result getErrorWarning(Throwable t) throws Throwable {
if(t instanceof ParseException) {
return getErrorWarning("De lagen op dit niveau konden niet worden opgehaald.");
} else if(t instanceof PromiseTimeoutException){
return getErrorWarning("Het laden van de lagen op dit niveau heeft te lang geduurd.");
} else {
throw t;
}
}
/**
* Renders an error message.
*
* @param capWarning the text to show in the error message
* @return The result.
*/
public Result getErrorWarning(String capWarning) {
return ok(capabilitieswarning.render(capWarning));
}
/**
* Renders an info message.
*
* @param message the text to show in the info message
* @return The result.
*/
public Result getEmptyLayerMessage(String message) {
return ok(emptylayermessage.render(message));
}
/**
* Checks if a layer has the CRS of EPSG:28992 and removes the layer from the list if that's not the case.
*
* @param layerList the list of layers to check
* @return The new list of layers after checking.
*/
public List<WMSCapabilities.Layer> crsCheck(List<WMSCapabilities.Layer> layerList) {
for(WMSCapabilities.Layer layer : layerList) {
if(!layer.supportsCRS("EPSG:28992")) {
layerList.remove(layer);
}
}
return layerList;
}
/**
* Makes specific controller methods available to use in JavaScript.
*
* @return The result.
*/
public Result jsRoutes() {
return ok (Routes.javascriptRouter ("jsRoutes",
controllers.routes.javascript.Assets.versioned(),
controllers.routes.javascript.Application.allLayers(),
controllers.routes.javascript.Application.layers(),
controllers.routes.javascript.GetFeatureInfoProxy.proxy()
)).as ("text/javascript");
}
}
|
package com.hzp.pedometer.service;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import com.hzp.pedometer.persistance.db.DailyDataManager;
import com.hzp.pedometer.utils.AppConstants;
import com.hzp.pedometer.persistance.file.StepDataStorage;
import com.hzp.pedometer.persistance.sp.StepConfig;
import com.hzp.pedometer.service.step.StepManager;
import com.hzp.pedometer.utils.FileUtils;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class CoreService extends Service implements SensorEventListener {
private CoreBinder binder;
private SensorManager sensorManager;
private Sensor sensor;
private ScreenReceiver screenReceiver;
private PowerManager.WakeLock wakeLock;
private Mode mode = Mode.NORMAL;
private boolean Working = false;
private ScheduledExecutorService normalStepCountService;
private static final int RECORD_TASK_INTERVAL = 10;//min
private static final int RECORD_TASK_WAIT_TIME = 2000;
private static final int COUNT_STEP_TASK_INTERVAL = 30;//min
private int recordTempCount = 0;
public CoreService() {
binder = new CoreBinder();
}
@Override
public void onCreate() {
super.onCreate();
wakeLock = ServiceUtil.getWakeLock(this);
initManagers();
registerScreenReceiver();
initSensors();
}
private void initManagers() {
StepDataStorage.getInstance().init(getApplicationContext());
StepConfig.getInstance().init(getApplicationContext());
StepManager.getInstance().init(getApplicationContext());
DailyDataManager.getInstance().init(getApplicationContext());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(screenReceiver);
//cpu
if (wakeLock.isHeld()) {
wakeLock.release();
}
DailyDataManager.getInstance().closeDatabase();
}
private void initSensors() {
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
private void registerScreenReceiver() {
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
screenReceiver = new ScreenReceiver();
registerReceiver(screenReceiver, filter);
}
@Override
public void onSensorChanged(SensorEvent event) {
double a = Math.sqrt(
Math.pow(event.values[0], 2) +
Math.pow(event.values[1], 2) +
Math.pow(event.values[2], 2));
BigDecimal bd = new BigDecimal(a);
bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
switch (mode) {
case NORMAL: {
processNormalMode(bd.doubleValue());
break;
}
case REAL_TIME: {
processRealTimeMode(bd.doubleValue());
break;
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
//empty
}
/**
*
*
* @param a
*/
private void processRealTimeMode(double a) {
StepManager.getInstance().inputPoint(a);
}
/**
*
*
* @param a
*/
private void processNormalMode(double a) {
StepDataStorage.getInstance().saveData(a + AppConstants.Separator);
}
private void startNormalMode() {
StepManager.getInstance().setStartTime(Calendar.getInstance().getTimeInMillis());
normalStepCountService = Executors.newScheduledThreadPool(2);
normalStepCountService.scheduleAtFixedRate(new RecordStepDataTask()
, 0
, RECORD_TASK_INTERVAL
, TimeUnit.MINUTES);
}
private void stopNormalMode() {
normalStepCountService.shutdown();
StepDataStorage.getInstance().endRecord();
recordTempCount = 0;
}
private void startRealTimeMode() {
StepManager.getInstance().setStartTime(Calendar.getInstance().getTimeInMillis());
}
private void stopRealTimeMode() {
}
class RecordStepDataTask implements Runnable {
@Override
public void run() {
if (recordTempCount * RECORD_TASK_INTERVAL >=
COUNT_STEP_TASK_INTERVAL) {
countStepFromFiles();
recordTempCount = 0;
}else{
StepDataStorage.getInstance().startNewRecord();
StepDataStorage.getInstance().clearBuffer();
StepDataStorage.getInstance().saveData(
StepManager.getInstance().getStartTime() + AppConstants.Separator
);
recordTempCount++;
}
}
}
/**
*
*
* @param mode
*/
public void startStepCount(Mode mode) {
if (!isWorking()) {
this.mode = mode;
toggleWorkingState(true);
switch (mode) {
case NORMAL: {
startNormalMode();
break;
}
case REAL_TIME: {
startRealTimeMode();
break;
}
}
sensorManager.registerListener(this, sensor,
(int) (1.0 / StepConfig.getInstance().getSamplingRate()) * 1000 * 1000);
}
}
public void stopStepCount() {
if (Working) {
toggleWorkingState(false);
sensorManager.unregisterListener(this);
switch (mode) {
case NORMAL: {
stopNormalMode();
break;
}
case REAL_TIME: {
stopRealTimeMode();
break;
}
}
StepManager.getInstance().resetData();
}
}
/**
*
*
* @return
*/
public int countStepFromFiles() {
final boolean flag;
if (isWorking()) {
stopStepCount();
flag = getMode().equals(Mode.NORMAL);
} else {
flag = false;
}
StepManager.getInstance().resetData();
final String[] filenames = StepDataStorage.getInstance().getDataFileNames();
new Thread() {
@Override
public void run() {
try {
synchronized (StepDataStorage.getInstance()) {
StepDataStorage.getInstance().wait(RECORD_TASK_WAIT_TIME);
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
int stepCount;
long startTime, endTime;
if (filenames.length != 0) {
StepManager.getInstance().setBroadcastEnable(false);
for (String filename : filenames) {
startTime = StepDataStorage.getInstance().getDataStartTime(filename);
if (startTime == 0) {
continue;
}
StepManager.getInstance().setStartTime(startTime);
StepManager.getInstance().inputPointSync(filename);
stepCount = StepManager.getInstance().getStepCount();
endTime = StepManager.getInstance().getEndTime();
if (stepCount != 0) {
DailyDataManager.getInstance().saveData(
FileUtils.getFileLastModified(getApplicationContext(), filename),
startTime,
endTime,
stepCount
);
}
}
StepDataStorage.getInstance().deleteFile(filenames);
}
StepManager.getInstance().setBroadcastEnable(true);
if (flag) {
startStepCount(Mode.NORMAL);
}
}
}
}.start();
return filenames.length;
}
public boolean isWorking() {
return Working;
}
private void toggleWorkingState(boolean working) {
this.Working = working;
}
public StepManager getStepManager() {
return StepManager.getInstance();
}
public Mode getMode() {
return mode;
}
private class ScreenReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case Intent.ACTION_SCREEN_ON:
if (wakeLock.isHeld()) {
wakeLock.release();
}
break;
case Intent.ACTION_SCREEN_OFF:
//cpu
if (isWorking()) {
wakeLock.acquire();
}
break;
}
}
}
public class CoreBinder extends Binder {
public CoreService getService() {
return CoreService.this;
}
}
}
|
package com.lsw.weather.activity;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lsw.weather.R;
import com.lsw.weather.adapter.DailyForecastAdapter;
import com.lsw.weather.adapter.HourlyForecastAdapter;
import com.lsw.weather.adapter.SuggestionAdapter;
import com.lsw.weather.api.WeatherApi;
import com.lsw.weather.model.WeatherEntity;
import com.lsw.weather.model.WeatherEntity.HeWeatherBean;
import com.lsw.weather.util.HttpUtil;
import com.lsw.weather.util.ImageUtils;
import com.lsw.weather.util.SpeechUtil;
import com.lsw.weather.view.ScrollListView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class MainActivity extends BaseActivity {
@BindView(R.id.iv_weather_image)
ImageView ivWeatherImage;
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.collapsing_toolbar)
CollapsingToolbarLayout collapsingToolbar;
@BindView(R.id.appbar)
AppBarLayout appbar;
@BindView(R.id.fab_speech)
FloatingActionButton fabSpeech;
@BindView(R.id.swipe_refresh_layout)
SwipeRefreshLayout swipeRefreshLayout;
@BindView(R.id.iv_icon)
ImageView ivIcon;
@BindView(R.id.tv_temp)
TextView tvTemp;
@BindView(R.id.tv_max_temp)
TextView tvMaxTemp;
@BindView(R.id.tv_min_temp)
TextView tvMinTemp;
@BindView(R.id.tv_more_info)
TextView tvMoreInfo;
@BindView(R.id.ll_weather_container)
LinearLayout llWeatherContainer;
@BindView(R.id.nested_scroll_view)
NestedScrollView nestedScrollView;
@BindView(R.id.lv_hourly_forecast)
ScrollListView lvHourlyForecast;
@BindView(R.id.lv_daily_forecast)
ScrollListView lvDailyForecast;
@BindView(R.id.lv_suggestion)
ScrollListView lvSuggestion;
@BindView(R.id.tv_today_weather)
TextView tvTodayWeather;
private static final String TAG = "MainActivity";
private static final int REQUEST_CODE_PICK_CITY = 0;
private String cityName = "";
//AMapLocationClient
public AMapLocationClient mLocationClient = null;
//AMapLocationClientOption
public AMapLocationClientOption mLocationOption = null;
private HeWeatherBean mHeWeatherBean;
private SpeechUtil speechUtil;
private static final int REQUEST_CODE_PERMISSION = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
//Toolbar,
setSupportActionBar(toolbar);
if(getSupportActionBar() !=null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu);
}
nestedScrollView.setVisibility(View.GONE);
List<String> permissionList = new ArrayList<>();
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
permissionList.add(Manifest.permission.READ_PHONE_STATE);
}
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (!permissionList.isEmpty()) {
String[] permissions = permissionList.toArray(new String[permissionList.size()]);
ActivityCompat.requestPermissions(MainActivity.this, permissions, REQUEST_CODE_PERMISSION);
} else {
showWeather();
}
AnimationDrawable animation = (AnimationDrawable) fabSpeech.getDrawable();
speechUtil = new SpeechUtil(this, animation);
swipeRefreshLayout.setColorSchemeResources(R.color.bg_orange, R.color.bg_blue, R.color.bg_green, R.color.bg_red);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
loadWeatherData(cityName);
}
});
fabSpeech.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mHeWeatherBean != null) {
String text = voiceWeather(MainActivity.this, mHeWeatherBean);
speechUtil.speak(text);
}
}
});
}
private void showWeather() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String weatherStr = prefs.getString("weather", null);
if (weatherStr != null) {
Gson gson=new Gson();
WeatherEntity entity = gson.fromJson(weatherStr, new TypeToken<WeatherEntity>(){}.getType());
HeWeatherBean weather = entity.getHeWeather().get(0);
updateView(weather);
} else {
swipeRefreshLayout.setRefreshing(true);
onLocationCity();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_CODE_PERMISSION:
if (grantResults.length > 0) {
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
return;
}
}
showWeather();
} else {
Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
}
break;
default:
}
}
/**
*
*
* @param city
*/
private void loadWeatherData(String city) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(HttpUtil.WEATHER_URL)
.addConverterFactory(GsonConverterFactory.create())// json
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())// RxJava
.build();
WeatherApi weatherApi = retrofit.create(WeatherApi.class);
weatherApi.getWeather(city, HttpUtil.HE_WEATHER_KEY)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<WeatherEntity>() {
@Override
public void onCompleted() {
Log.d(TAG, "onCompleted: ");
}
@Override
public void onError(Throwable e) {
Log.d(TAG, "onError: " + e.getMessage());
}
@Override
public void onNext(WeatherEntity entity) {
Log.d(TAG, "onNext: ");
Gson gson = new Gson();
String weatherStr = gson.toJson(entity);
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();
editor.putString("weather", weatherStr);
editor.apply();
mHeWeatherBean = entity.getHeWeather().get(0);
updateView(mHeWeatherBean);
Snackbar.make(toolbar,"",Snackbar.LENGTH_SHORT).show();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PICK_CITY && resultCode == RESULT_OK){
if (data != null){
cityName = data.getStringExtra(CityPickerActivity.KEY_PICKED_CITY);
swipeRefreshLayout.setRefreshing(true);
loadWeatherData(cityName);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
startActivityForResult(new Intent(MainActivity.this, CityPickerActivity.class), REQUEST_CODE_PICK_CITY);
break;
case R.id.action_share:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.share_content));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(Intent.createChooser(intent, getString(R.string.share)));
break;
case R.id.action_about:
Intent aboutIntent = new Intent(MainActivity.this,AboutActivity.class);
startActivity(aboutIntent);
break;
default:
}
return true;
}
/**
*
*
* @param weather
*/
private void updateView(HeWeatherBean weather) {
ivWeatherImage.setImageResource(ImageUtils.getWeatherImage(weather.getNow().getCond().getTxt()));
ivIcon.setImageResource(ImageUtils.getIconByCode(this, weather.getNow().getCond().getCode()));
tvTodayWeather.setText(weather.getNow().getCond().getTxt());
tvTemp.setText(getString(R.string.tempC, weather.getNow().getTmp()));
tvMaxTemp.setText(getString(R.string.now_max_temp, weather.getDaily_forecast().get(0).getTmp().getMax()));
tvMinTemp.setText(getString(R.string.now_min_temp, weather.getDaily_forecast().get(0).getTmp().getMin()));
StringBuilder sb = new StringBuilder();
sb.append("").append(weather.getNow().getFl()).append("°");
if (weather.getAqi() != null && !TextUtils.isEmpty(weather.getAqi().getCity().getQlty())) {
sb.append(" ").append(weather.getAqi().getCity().getQlty().contains("") ? "" : "").append(weather.getAqi().getCity().getQlty());
}
sb.append(" ").append(weather.getNow().getWind().getDir()).append(weather.getNow().getWind().getSc()).append(weather.getNow().getWind().getSc().contains("") ? "" : "");
tvMoreInfo.setText(sb.toString());
lvHourlyForecast.setAdapter(new HourlyForecastAdapter(weather.getHourly_forecast()));
lvDailyForecast.setAdapter(new DailyForecastAdapter(weather.getDaily_forecast()));
lvSuggestion.setAdapter(new SuggestionAdapter(weather.getSuggestion()));
collapsingToolbar.setTitle(weather.getBasic().getCity());
cityName = weather.getBasic().getCity();
nestedScrollView.setVisibility(View.VISIBLE);
swipeRefreshLayout.setRefreshing(false);
}
private void onLocationCity() {
mLocationClient = new AMapLocationClient(getApplicationContext());
mLocationClient.setLocationListener(new AMapLocationListener() {
@Override
public void onLocationChanged(AMapLocation aMapLocation) {
if (aMapLocation != null) {
if (aMapLocation.getErrorCode() == 0) {
//amapLocation
cityName = getLocationCityName(aMapLocation.getProvince(), aMapLocation.getCity(), aMapLocation.getDistrict());
// collapsingToolbar.setTitle(cityName);
loadWeatherData(cityName);
Log.d(TAG, "onLocationChanged: city = " + cityName);
} else {
//ErrCodeerrInfo
Log.e(TAG, "onLocationChanged: " + aMapLocation.getErrorCode() + ",errInfo:" + aMapLocation.getErrorInfo());
}
}
}
});
//AMapLocationClientOption
mLocationOption = new AMapLocationClientOption();
//AMapLocationMode.Hight_Accuracy
mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
//false
mLocationOption.setOnceLocation(true);
//setOnceLocationLatest(boolean b)trueSDK3struesetOnceLocation(boolean b)truefalse
mLocationOption.setOnceLocationLatest(true);
mLocationClient.setLocationOption(mLocationOption);
mLocationClient.startLocation();
}
/**
*
*
* @param province
* @param city
* @param district
* @return
*/
private String getLocationCityName(String province, String city, String district) {
//district""""
if (district != null) {
String districtEnd = district.substring((district.length() - 1), district.length());//
if (districtEnd.equals("")) {
return district.substring(0, (district.length() - 1));
} else if (districtEnd.equals("")) {
return district.substring(0, (district.length() - 1));
} else {
return district;
}
} else if (city != null) {//city""
String cityEnd = city.substring((city.length() - 1), city.length());
if (cityEnd.equals("")) {
return city.substring(0, (city.length() - 1));
} else {
return city;
}
} else if (province != null) {//province""""
String provinceEnd = province.substring((province.length() - 1), province.length());
if (provinceEnd.equals("")) {
return province.substring(0, (province.length() - 1));
} else if (provinceEnd.equals("")) {
return province.substring(0, (province.length() - 1));
} else {
return province;
}
} else {
return "";
}
}
/**
*
*
* @param context
* @param weather
* @return
*/
public static String voiceWeather(Context context, HeWeatherBean weather) {
StringBuilder sb = new StringBuilder();
int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
if (hour >= 7 && hour < 12) {
sb.append("");
} else if (hour < 19) {
sb.append("");
} else {
sb.append("");
}
sb.append("");
sb.append(context.getString(R.string.app_name))
.append("")
.append("");
sb.append("")
.append(weather.getDaily_forecast().get(0).getCond().getTxt_d())
.append("")
.append(weather.getDaily_forecast().get(0).getCond().getTxt_n())
.append("");
sb.append("")
.append(weather.getDaily_forecast().get(0).getTmp().getMin())
.append("~")
.append(weather.getDaily_forecast().get(0).getTmp().getMax())
.append("℃")
.append("");
sb.append(weather.getDaily_forecast().get(0).getWind().getDir())
.append(weather.getDaily_forecast().get(0).getWind().getSc())
.append(weather.getDaily_forecast().get(0).getWind().getSc().contains("") ? "" : "")
.append("");
return sb.toString();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.